"use strict";
var wp;
(wp ||= {}).editSite = (() => {
  var __create = Object.create;
  var __defProp = Object.defineProperty;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __getProtoOf = Object.getPrototypeOf;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
    get: (a2, b2) => (typeof require !== "undefined" ? require : a2)[b2]
  }) : x2)(function(x2) {
    if (typeof require !== "undefined") return require.apply(this, arguments);
    throw Error('Dynamic require of "' + x2 + '" is not supported');
  });
  var __commonJS = (cb, mod) => function __require4() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };
  var __export = (target, all) => {
    for (var name2 in all)
      __defProp(target, name2, { get: all[name2], enumerable: true });
  };
  var __copyProps = (to2, from, except, desc) => {
    if (from && typeof from === "object" || typeof from === "function") {
      for (let key of __getOwnPropNames(from))
        if (!__hasOwnProp.call(to2, key) && key !== except)
          __defProp(to2, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
    }
    return to2;
  };
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
    // If the importer is in node compatibility mode or this is not an ESM
    // file that has been converted to a CommonJS file using a Babel-
    // compatible transform (i.e. "__esModule" has not been set), then set
    // "default" to the CommonJS "module.exports" for node compatibility.
    isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
    mod
  ));
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

  // package-external:@wordpress/blocks
  var require_blocks = __commonJS({
    "package-external:@wordpress/blocks"(exports, module) {
      module.exports = window.wp.blocks;
    }
  });

  // package-external:@wordpress/block-library
  var require_block_library = __commonJS({
    "package-external:@wordpress/block-library"(exports, module) {
      module.exports = window.wp.blockLibrary;
    }
  });

  // package-external:@wordpress/data
  var require_data = __commonJS({
    "package-external:@wordpress/data"(exports, module) {
      module.exports = window.wp.data;
    }
  });

  // package-external:@wordpress/deprecated
  var require_deprecated = __commonJS({
    "package-external:@wordpress/deprecated"(exports, module) {
      module.exports = window.wp.deprecated;
    }
  });

  // package-external:@wordpress/element
  var require_element = __commonJS({
    "package-external:@wordpress/element"(exports, module) {
      module.exports = window.wp.element;
    }
  });

  // package-external:@wordpress/editor
  var require_editor = __commonJS({
    "package-external:@wordpress/editor"(exports, module) {
      module.exports = window.wp.editor;
    }
  });

  // package-external:@wordpress/preferences
  var require_preferences = __commonJS({
    "package-external:@wordpress/preferences"(exports, module) {
      module.exports = window.wp.preferences;
    }
  });

  // package-external:@wordpress/widgets
  var require_widgets = __commonJS({
    "package-external:@wordpress/widgets"(exports, module) {
      module.exports = window.wp.widgets;
    }
  });

  // package-external:@wordpress/core-data
  var require_core_data = __commonJS({
    "package-external:@wordpress/core-data"(exports, module) {
      module.exports = window.wp.coreData;
    }
  });

  // package-external:@wordpress/block-editor
  var require_block_editor = __commonJS({
    "package-external:@wordpress/block-editor"(exports, module) {
      module.exports = window.wp.blockEditor;
    }
  });

  // package-external:@wordpress/i18n
  var require_i18n = __commonJS({
    "package-external:@wordpress/i18n"(exports, module) {
      module.exports = window.wp.i18n;
    }
  });

  // package-external:@wordpress/patterns
  var require_patterns = __commonJS({
    "package-external:@wordpress/patterns"(exports, module) {
      module.exports = window.wp.patterns;
    }
  });

  // package-external:@wordpress/private-apis
  var require_private_apis = __commonJS({
    "package-external:@wordpress/private-apis"(exports, module) {
      module.exports = window.wp.privateApis;
    }
  });

  // package-external:@wordpress/router
  var require_router = __commonJS({
    "package-external:@wordpress/router"(exports, module) {
      module.exports = window.wp.router;
    }
  });

  // vendor-external:react
  var require_react = __commonJS({
    "vendor-external:react"(exports, module) {
      module.exports = window.React;
    }
  });

  // vendor-external:react/jsx-runtime
  var require_jsx_runtime = __commonJS({
    "vendor-external:react/jsx-runtime"(exports, module) {
      module.exports = window.ReactJSXRuntime;
    }
  });

  // vendor-external:react-dom
  var require_react_dom = __commonJS({
    "vendor-external:react-dom"(exports, module) {
      module.exports = window.ReactDOM;
    }
  });

  // node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js
  var require_use_sync_external_store_shim_development = __commonJS({
    "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js"(exports) {
      "use strict";
      (function() {
        function is2(x2, y2) {
          return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
        }
        function useSyncExternalStore$2(subscribe3, getSnapshot) {
          didWarnOld18Alpha || void 0 === React61.startTransition || (didWarnOld18Alpha = true, console.error(
            "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
          ));
          var value = getSnapshot();
          if (!didWarnUncachedGetSnapshot) {
            var cachedValue = getSnapshot();
            objectIs(value, cachedValue) || (console.error(
              "The result of getSnapshot should be cached to avoid an infinite loop"
            ), didWarnUncachedGetSnapshot = true);
          }
          cachedValue = useState88({
            inst: { value, getSnapshot }
          });
          var inst = cachedValue[0].inst, forceUpdate = cachedValue[1];
          useLayoutEffect11(
            function() {
              inst.value = value;
              inst.getSnapshot = getSnapshot;
              checkIfSnapshotChanged(inst) && forceUpdate({ inst });
            },
            [subscribe3, value, getSnapshot]
          );
          useEffect70(
            function() {
              checkIfSnapshotChanged(inst) && forceUpdate({ inst });
              return subscribe3(function() {
                checkIfSnapshotChanged(inst) && forceUpdate({ inst });
              });
            },
            [subscribe3]
          );
          useDebugValue2(value);
          return value;
        }
        function checkIfSnapshotChanged(inst) {
          var latestGetSnapshot = inst.getSnapshot;
          inst = inst.value;
          try {
            var nextValue = latestGetSnapshot();
            return !objectIs(inst, nextValue);
          } catch (error2) {
            return true;
          }
        }
        function useSyncExternalStore$1(subscribe3, getSnapshot) {
          return getSnapshot();
        }
        "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
        var React61 = require_react(), objectIs = "function" === typeof Object.is ? Object.is : is2, useState88 = React61.useState, useEffect70 = React61.useEffect, useLayoutEffect11 = React61.useLayoutEffect, useDebugValue2 = React61.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2;
        exports.useSyncExternalStore = void 0 !== React61.useSyncExternalStore ? React61.useSyncExternalStore : shim;
        "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
      })();
    }
  });

  // node_modules/use-sync-external-store/shim/index.js
  var require_shim = __commonJS({
    "node_modules/use-sync-external-store/shim/index.js"(exports, module) {
      "use strict";
      if (false) {
        module.exports = null;
      } else {
        module.exports = require_use_sync_external_store_shim_development();
      }
    }
  });

  // node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js
  var require_with_selector_development = __commonJS({
    "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js"(exports) {
      "use strict";
      (function() {
        function is2(x2, y2) {
          return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
        }
        "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
        var React61 = require_react(), shim = require_shim(), objectIs = "function" === typeof Object.is ? Object.is : is2, useSyncExternalStore3 = shim.useSyncExternalStore, useRef77 = React61.useRef, useEffect70 = React61.useEffect, useMemo95 = React61.useMemo, useDebugValue2 = React61.useDebugValue;
        exports.useSyncExternalStoreWithSelector = function(subscribe3, getSnapshot, getServerSnapshot, selector2, isEqual2) {
          var instRef = useRef77(null);
          if (null === instRef.current) {
            var inst = { hasValue: false, value: null };
            instRef.current = inst;
          } else inst = instRef.current;
          instRef = useMemo95(
            function() {
              function memoizedSelector(nextSnapshot) {
                if (!hasMemo) {
                  hasMemo = true;
                  memoizedSnapshot = nextSnapshot;
                  nextSnapshot = selector2(nextSnapshot);
                  if (void 0 !== isEqual2 && inst.hasValue) {
                    var currentSelection = inst.value;
                    if (isEqual2(currentSelection, nextSnapshot))
                      return memoizedSelection = currentSelection;
                  }
                  return memoizedSelection = nextSnapshot;
                }
                currentSelection = memoizedSelection;
                if (objectIs(memoizedSnapshot, nextSnapshot))
                  return currentSelection;
                var nextSelection = selector2(nextSnapshot);
                if (void 0 !== isEqual2 && isEqual2(currentSelection, nextSelection))
                  return memoizedSnapshot = nextSnapshot, currentSelection;
                memoizedSnapshot = nextSnapshot;
                return memoizedSelection = nextSelection;
              }
              var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot;
              return [
                function() {
                  return memoizedSelector(getSnapshot());
                },
                null === maybeGetServerSnapshot ? void 0 : function() {
                  return memoizedSelector(maybeGetServerSnapshot());
                }
              ];
            },
            [getSnapshot, getServerSnapshot, selector2, isEqual2]
          );
          var value = useSyncExternalStore3(subscribe3, instRef[0], instRef[1]);
          useEffect70(
            function() {
              inst.hasValue = true;
              inst.value = value;
            },
            [value]
          );
          useDebugValue2(value);
          return value;
        };
        "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
      })();
    }
  });

  // node_modules/use-sync-external-store/shim/with-selector.js
  var require_with_selector = __commonJS({
    "node_modules/use-sync-external-store/shim/with-selector.js"(exports, module) {
      "use strict";
      if (false) {
        module.exports = null;
      } else {
        module.exports = require_with_selector_development();
      }
    }
  });

  // package-external:@wordpress/a11y
  var require_a11y = __commonJS({
    "package-external:@wordpress/a11y"(exports, module) {
      module.exports = window.wp.a11y;
    }
  });

  // package-external:@wordpress/primitives
  var require_primitives = __commonJS({
    "package-external:@wordpress/primitives"(exports, module) {
      module.exports = window.wp.primitives;
    }
  });

  // package-external:@wordpress/compose
  var require_compose = __commonJS({
    "package-external:@wordpress/compose"(exports, module) {
      module.exports = window.wp.compose;
    }
  });

  // package-external:@wordpress/theme
  var require_theme = __commonJS({
    "package-external:@wordpress/theme"(exports, module) {
      module.exports = window.wp.theme;
    }
  });

  // package-external:@wordpress/components
  var require_components = __commonJS({
    "package-external:@wordpress/components"(exports, module) {
      module.exports = window.wp.components;
    }
  });

  // package-external:@wordpress/dom
  var require_dom = __commonJS({
    "package-external:@wordpress/dom"(exports, module) {
      module.exports = window.wp.dom;
    }
  });

  // package-external:@wordpress/plugins
  var require_plugins = __commonJS({
    "package-external:@wordpress/plugins"(exports, module) {
      module.exports = window.wp.plugins;
    }
  });

  // package-external:@wordpress/notices
  var require_notices = __commonJS({
    "package-external:@wordpress/notices"(exports, module) {
      module.exports = window.wp.notices;
    }
  });

  // package-external:@wordpress/url
  var require_url = __commonJS({
    "package-external:@wordpress/url"(exports, module) {
      module.exports = window.wp.url;
    }
  });

  // package-external:@wordpress/keyboard-shortcuts
  var require_keyboard_shortcuts = __commonJS({
    "package-external:@wordpress/keyboard-shortcuts"(exports, module) {
      module.exports = window.wp.keyboardShortcuts;
    }
  });

  // package-external:@wordpress/keycodes
  var require_keycodes = __commonJS({
    "package-external:@wordpress/keycodes"(exports, module) {
      module.exports = window.wp.keycodes;
    }
  });

  // package-external:@wordpress/api-fetch
  var require_api_fetch = __commonJS({
    "package-external:@wordpress/api-fetch"(exports, module) {
      module.exports = window.wp.apiFetch;
    }
  });

  // package-external:@wordpress/commands
  var require_commands = __commonJS({
    "package-external:@wordpress/commands"(exports, module) {
      module.exports = window.wp.commands;
    }
  });

  // package-external:@wordpress/html-entities
  var require_html_entities = __commonJS({
    "package-external:@wordpress/html-entities"(exports, module) {
      module.exports = window.wp.htmlEntities;
    }
  });

  // package-external:@wordpress/style-engine
  var require_style_engine = __commonJS({
    "package-external:@wordpress/style-engine"(exports, module) {
      module.exports = window.wp.styleEngine;
    }
  });

  // node_modules/fast-deep-equal/es6/index.js
  var require_es6 = __commonJS({
    "node_modules/fast-deep-equal/es6/index.js"(exports, module) {
      "use strict";
      module.exports = function equal(a2, b2) {
        if (a2 === b2) return true;
        if (a2 && b2 && typeof a2 == "object" && typeof b2 == "object") {
          if (a2.constructor !== b2.constructor) return false;
          var length, i2, keys;
          if (Array.isArray(a2)) {
            length = a2.length;
            if (length != b2.length) return false;
            for (i2 = length; i2-- !== 0; )
              if (!equal(a2[i2], b2[i2])) return false;
            return true;
          }
          if (a2 instanceof Map && b2 instanceof Map) {
            if (a2.size !== b2.size) return false;
            for (i2 of a2.entries())
              if (!b2.has(i2[0])) return false;
            for (i2 of a2.entries())
              if (!equal(i2[1], b2.get(i2[0]))) return false;
            return true;
          }
          if (a2 instanceof Set && b2 instanceof Set) {
            if (a2.size !== b2.size) return false;
            for (i2 of a2.entries())
              if (!b2.has(i2[0])) return false;
            return true;
          }
          if (ArrayBuffer.isView(a2) && ArrayBuffer.isView(b2)) {
            length = a2.length;
            if (length != b2.length) return false;
            for (i2 = length; i2-- !== 0; )
              if (a2[i2] !== b2[i2]) return false;
            return true;
          }
          if (a2.constructor === RegExp) return a2.source === b2.source && a2.flags === b2.flags;
          if (a2.valueOf !== Object.prototype.valueOf) return a2.valueOf() === b2.valueOf();
          if (a2.toString !== Object.prototype.toString) return a2.toString() === b2.toString();
          keys = Object.keys(a2);
          length = keys.length;
          if (length !== Object.keys(b2).length) return false;
          for (i2 = length; i2-- !== 0; )
            if (!Object.prototype.hasOwnProperty.call(b2, keys[i2])) return false;
          for (i2 = length; i2-- !== 0; ) {
            var key = keys[i2];
            if (!equal(a2[key], b2[key])) return false;
          }
          return true;
        }
        return a2 !== a2 && b2 !== b2;
      };
    }
  });

  // node_modules/deepmerge/dist/cjs.js
  var require_cjs = __commonJS({
    "node_modules/deepmerge/dist/cjs.js"(exports, module) {
      "use strict";
      var isMergeableObject = function isMergeableObject2(value) {
        return isNonNullObject(value) && !isSpecial(value);
      };
      function isNonNullObject(value) {
        return !!value && typeof value === "object";
      }
      function isSpecial(value) {
        var stringValue = Object.prototype.toString.call(value);
        return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value);
      }
      var canUseSymbol = typeof Symbol === "function" && Symbol.for;
      var REACT_ELEMENT_TYPE = canUseSymbol ? /* @__PURE__ */ Symbol.for("react.element") : 60103;
      function isReactElement(value) {
        return value.$$typeof === REACT_ELEMENT_TYPE;
      }
      function emptyTarget(val) {
        return Array.isArray(val) ? [] : {};
      }
      function cloneUnlessOtherwiseSpecified(value, options) {
        return options.clone !== false && options.isMergeableObject(value) ? deepmerge2(emptyTarget(value), value, options) : value;
      }
      function defaultArrayMerge(target, source, options) {
        return target.concat(source).map(function(element) {
          return cloneUnlessOtherwiseSpecified(element, options);
        });
      }
      function getMergeFunction(key, options) {
        if (!options.customMerge) {
          return deepmerge2;
        }
        var customMerge = options.customMerge(key);
        return typeof customMerge === "function" ? customMerge : deepmerge2;
      }
      function getEnumerableOwnPropertySymbols(target) {
        return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol3) {
          return Object.propertyIsEnumerable.call(target, symbol3);
        }) : [];
      }
      function getKeys2(target) {
        return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
      }
      function propertyIsOnObject(object, property) {
        try {
          return property in object;
        } catch (_) {
          return false;
        }
      }
      function propertyIsUnsafe(target, key) {
        return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key));
      }
      function mergeObject(target, source, options) {
        var destination = {};
        if (options.isMergeableObject(target)) {
          getKeys2(target).forEach(function(key) {
            destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
          });
        }
        getKeys2(source).forEach(function(key) {
          if (propertyIsUnsafe(target, key)) {
            return;
          }
          if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
            destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
          } else {
            destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
          }
        });
        return destination;
      }
      function deepmerge2(target, source, options) {
        options = options || {};
        options.arrayMerge = options.arrayMerge || defaultArrayMerge;
        options.isMergeableObject = options.isMergeableObject || isMergeableObject;
        options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
        var sourceIsArray = Array.isArray(source);
        var targetIsArray = Array.isArray(target);
        var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
        if (!sourceAndTargetTypesMatch) {
          return cloneUnlessOtherwiseSpecified(source, options);
        } else if (sourceIsArray) {
          return options.arrayMerge(target, source, options);
        } else {
          return mergeObject(target, source, options);
        }
      }
      deepmerge2.all = function deepmergeAll(array, options) {
        if (!Array.isArray(array)) {
          throw new Error("first argument should be an array");
        }
        return array.reduce(function(prev, next) {
          return deepmerge2(prev, next, options);
        }, {});
      };
      var deepmerge_1 = deepmerge2;
      module.exports = deepmerge_1;
    }
  });

  // package-external:@wordpress/blob
  var require_blob = __commonJS({
    "package-external:@wordpress/blob"(exports, module) {
      module.exports = window.wp.blob;
    }
  });

  // node_modules/remove-accents/index.js
  var require_remove_accents = __commonJS({
    "node_modules/remove-accents/index.js"(exports, module) {
      var characterMap = {
        "\xC0": "A",
        "\xC1": "A",
        "\xC2": "A",
        "\xC3": "A",
        "\xC4": "A",
        "\xC5": "A",
        "\u1EA4": "A",
        "\u1EAE": "A",
        "\u1EB2": "A",
        "\u1EB4": "A",
        "\u1EB6": "A",
        "\xC6": "AE",
        "\u1EA6": "A",
        "\u1EB0": "A",
        "\u0202": "A",
        "\u1EA2": "A",
        "\u1EA0": "A",
        "\u1EA8": "A",
        "\u1EAA": "A",
        "\u1EAC": "A",
        "\xC7": "C",
        "\u1E08": "C",
        "\xC8": "E",
        "\xC9": "E",
        "\xCA": "E",
        "\xCB": "E",
        "\u1EBE": "E",
        "\u1E16": "E",
        "\u1EC0": "E",
        "\u1E14": "E",
        "\u1E1C": "E",
        "\u0206": "E",
        "\u1EBA": "E",
        "\u1EBC": "E",
        "\u1EB8": "E",
        "\u1EC2": "E",
        "\u1EC4": "E",
        "\u1EC6": "E",
        "\xCC": "I",
        "\xCD": "I",
        "\xCE": "I",
        "\xCF": "I",
        "\u1E2E": "I",
        "\u020A": "I",
        "\u1EC8": "I",
        "\u1ECA": "I",
        "\xD0": "D",
        "\xD1": "N",
        "\xD2": "O",
        "\xD3": "O",
        "\xD4": "O",
        "\xD5": "O",
        "\xD6": "O",
        "\xD8": "O",
        "\u1ED0": "O",
        "\u1E4C": "O",
        "\u1E52": "O",
        "\u020E": "O",
        "\u1ECE": "O",
        "\u1ECC": "O",
        "\u1ED4": "O",
        "\u1ED6": "O",
        "\u1ED8": "O",
        "\u1EDC": "O",
        "\u1EDE": "O",
        "\u1EE0": "O",
        "\u1EDA": "O",
        "\u1EE2": "O",
        "\xD9": "U",
        "\xDA": "U",
        "\xDB": "U",
        "\xDC": "U",
        "\u1EE6": "U",
        "\u1EE4": "U",
        "\u1EEC": "U",
        "\u1EEE": "U",
        "\u1EF0": "U",
        "\xDD": "Y",
        "\xE0": "a",
        "\xE1": "a",
        "\xE2": "a",
        "\xE3": "a",
        "\xE4": "a",
        "\xE5": "a",
        "\u1EA5": "a",
        "\u1EAF": "a",
        "\u1EB3": "a",
        "\u1EB5": "a",
        "\u1EB7": "a",
        "\xE6": "ae",
        "\u1EA7": "a",
        "\u1EB1": "a",
        "\u0203": "a",
        "\u1EA3": "a",
        "\u1EA1": "a",
        "\u1EA9": "a",
        "\u1EAB": "a",
        "\u1EAD": "a",
        "\xE7": "c",
        "\u1E09": "c",
        "\xE8": "e",
        "\xE9": "e",
        "\xEA": "e",
        "\xEB": "e",
        "\u1EBF": "e",
        "\u1E17": "e",
        "\u1EC1": "e",
        "\u1E15": "e",
        "\u1E1D": "e",
        "\u0207": "e",
        "\u1EBB": "e",
        "\u1EBD": "e",
        "\u1EB9": "e",
        "\u1EC3": "e",
        "\u1EC5": "e",
        "\u1EC7": "e",
        "\xEC": "i",
        "\xED": "i",
        "\xEE": "i",
        "\xEF": "i",
        "\u1E2F": "i",
        "\u020B": "i",
        "\u1EC9": "i",
        "\u1ECB": "i",
        "\xF0": "d",
        "\xF1": "n",
        "\xF2": "o",
        "\xF3": "o",
        "\xF4": "o",
        "\xF5": "o",
        "\xF6": "o",
        "\xF8": "o",
        "\u1ED1": "o",
        "\u1E4D": "o",
        "\u1E53": "o",
        "\u020F": "o",
        "\u1ECF": "o",
        "\u1ECD": "o",
        "\u1ED5": "o",
        "\u1ED7": "o",
        "\u1ED9": "o",
        "\u1EDD": "o",
        "\u1EDF": "o",
        "\u1EE1": "o",
        "\u1EDB": "o",
        "\u1EE3": "o",
        "\xF9": "u",
        "\xFA": "u",
        "\xFB": "u",
        "\xFC": "u",
        "\u1EE7": "u",
        "\u1EE5": "u",
        "\u1EED": "u",
        "\u1EEF": "u",
        "\u1EF1": "u",
        "\xFD": "y",
        "\xFF": "y",
        "\u0100": "A",
        "\u0101": "a",
        "\u0102": "A",
        "\u0103": "a",
        "\u0104": "A",
        "\u0105": "a",
        "\u0106": "C",
        "\u0107": "c",
        "\u0108": "C",
        "\u0109": "c",
        "\u010A": "C",
        "\u010B": "c",
        "\u010C": "C",
        "\u010D": "c",
        "C\u0306": "C",
        "c\u0306": "c",
        "\u010E": "D",
        "\u010F": "d",
        "\u0110": "D",
        "\u0111": "d",
        "\u0112": "E",
        "\u0113": "e",
        "\u0114": "E",
        "\u0115": "e",
        "\u0116": "E",
        "\u0117": "e",
        "\u0118": "E",
        "\u0119": "e",
        "\u011A": "E",
        "\u011B": "e",
        "\u011C": "G",
        "\u01F4": "G",
        "\u011D": "g",
        "\u01F5": "g",
        "\u011E": "G",
        "\u011F": "g",
        "\u0120": "G",
        "\u0121": "g",
        "\u0122": "G",
        "\u0123": "g",
        "\u0124": "H",
        "\u0125": "h",
        "\u0126": "H",
        "\u0127": "h",
        "\u1E2A": "H",
        "\u1E2B": "h",
        "\u0128": "I",
        "\u0129": "i",
        "\u012A": "I",
        "\u012B": "i",
        "\u012C": "I",
        "\u012D": "i",
        "\u012E": "I",
        "\u012F": "i",
        "\u0130": "I",
        "\u0131": "i",
        "\u0132": "IJ",
        "\u0133": "ij",
        "\u0134": "J",
        "\u0135": "j",
        "\u0136": "K",
        "\u0137": "k",
        "\u1E30": "K",
        "\u1E31": "k",
        "K\u0306": "K",
        "k\u0306": "k",
        "\u0139": "L",
        "\u013A": "l",
        "\u013B": "L",
        "\u013C": "l",
        "\u013D": "L",
        "\u013E": "l",
        "\u013F": "L",
        "\u0140": "l",
        "\u0141": "l",
        "\u0142": "l",
        "\u1E3E": "M",
        "\u1E3F": "m",
        "M\u0306": "M",
        "m\u0306": "m",
        "\u0143": "N",
        "\u0144": "n",
        "\u0145": "N",
        "\u0146": "n",
        "\u0147": "N",
        "\u0148": "n",
        "\u0149": "n",
        "N\u0306": "N",
        "n\u0306": "n",
        "\u014C": "O",
        "\u014D": "o",
        "\u014E": "O",
        "\u014F": "o",
        "\u0150": "O",
        "\u0151": "o",
        "\u0152": "OE",
        "\u0153": "oe",
        "P\u0306": "P",
        "p\u0306": "p",
        "\u0154": "R",
        "\u0155": "r",
        "\u0156": "R",
        "\u0157": "r",
        "\u0158": "R",
        "\u0159": "r",
        "R\u0306": "R",
        "r\u0306": "r",
        "\u0212": "R",
        "\u0213": "r",
        "\u015A": "S",
        "\u015B": "s",
        "\u015C": "S",
        "\u015D": "s",
        "\u015E": "S",
        "\u0218": "S",
        "\u0219": "s",
        "\u015F": "s",
        "\u0160": "S",
        "\u0161": "s",
        "\u0162": "T",
        "\u0163": "t",
        "\u021B": "t",
        "\u021A": "T",
        "\u0164": "T",
        "\u0165": "t",
        "\u0166": "T",
        "\u0167": "t",
        "T\u0306": "T",
        "t\u0306": "t",
        "\u0168": "U",
        "\u0169": "u",
        "\u016A": "U",
        "\u016B": "u",
        "\u016C": "U",
        "\u016D": "u",
        "\u016E": "U",
        "\u016F": "u",
        "\u0170": "U",
        "\u0171": "u",
        "\u0172": "U",
        "\u0173": "u",
        "\u0216": "U",
        "\u0217": "u",
        "V\u0306": "V",
        "v\u0306": "v",
        "\u0174": "W",
        "\u0175": "w",
        "\u1E82": "W",
        "\u1E83": "w",
        "X\u0306": "X",
        "x\u0306": "x",
        "\u0176": "Y",
        "\u0177": "y",
        "\u0178": "Y",
        "Y\u0306": "Y",
        "y\u0306": "y",
        "\u0179": "Z",
        "\u017A": "z",
        "\u017B": "Z",
        "\u017C": "z",
        "\u017D": "Z",
        "\u017E": "z",
        "\u017F": "s",
        "\u0192": "f",
        "\u01A0": "O",
        "\u01A1": "o",
        "\u01AF": "U",
        "\u01B0": "u",
        "\u01CD": "A",
        "\u01CE": "a",
        "\u01CF": "I",
        "\u01D0": "i",
        "\u01D1": "O",
        "\u01D2": "o",
        "\u01D3": "U",
        "\u01D4": "u",
        "\u01D5": "U",
        "\u01D6": "u",
        "\u01D7": "U",
        "\u01D8": "u",
        "\u01D9": "U",
        "\u01DA": "u",
        "\u01DB": "U",
        "\u01DC": "u",
        "\u1EE8": "U",
        "\u1EE9": "u",
        "\u1E78": "U",
        "\u1E79": "u",
        "\u01FA": "A",
        "\u01FB": "a",
        "\u01FC": "AE",
        "\u01FD": "ae",
        "\u01FE": "O",
        "\u01FF": "o",
        "\xDE": "TH",
        "\xFE": "th",
        "\u1E54": "P",
        "\u1E55": "p",
        "\u1E64": "S",
        "\u1E65": "s",
        "X\u0301": "X",
        "x\u0301": "x",
        "\u0403": "\u0413",
        "\u0453": "\u0433",
        "\u040C": "\u041A",
        "\u045C": "\u043A",
        "A\u030B": "A",
        "a\u030B": "a",
        "E\u030B": "E",
        "e\u030B": "e",
        "I\u030B": "I",
        "i\u030B": "i",
        "\u01F8": "N",
        "\u01F9": "n",
        "\u1ED2": "O",
        "\u1ED3": "o",
        "\u1E50": "O",
        "\u1E51": "o",
        "\u1EEA": "U",
        "\u1EEB": "u",
        "\u1E80": "W",
        "\u1E81": "w",
        "\u1EF2": "Y",
        "\u1EF3": "y",
        "\u0200": "A",
        "\u0201": "a",
        "\u0204": "E",
        "\u0205": "e",
        "\u0208": "I",
        "\u0209": "i",
        "\u020C": "O",
        "\u020D": "o",
        "\u0210": "R",
        "\u0211": "r",
        "\u0214": "U",
        "\u0215": "u",
        "B\u030C": "B",
        "b\u030C": "b",
        "\u010C\u0323": "C",
        "\u010D\u0323": "c",
        "\xCA\u030C": "E",
        "\xEA\u030C": "e",
        "F\u030C": "F",
        "f\u030C": "f",
        "\u01E6": "G",
        "\u01E7": "g",
        "\u021E": "H",
        "\u021F": "h",
        "J\u030C": "J",
        "\u01F0": "j",
        "\u01E8": "K",
        "\u01E9": "k",
        "M\u030C": "M",
        "m\u030C": "m",
        "P\u030C": "P",
        "p\u030C": "p",
        "Q\u030C": "Q",
        "q\u030C": "q",
        "\u0158\u0329": "R",
        "\u0159\u0329": "r",
        "\u1E66": "S",
        "\u1E67": "s",
        "V\u030C": "V",
        "v\u030C": "v",
        "W\u030C": "W",
        "w\u030C": "w",
        "X\u030C": "X",
        "x\u030C": "x",
        "Y\u030C": "Y",
        "y\u030C": "y",
        "A\u0327": "A",
        "a\u0327": "a",
        "B\u0327": "B",
        "b\u0327": "b",
        "\u1E10": "D",
        "\u1E11": "d",
        "\u0228": "E",
        "\u0229": "e",
        "\u0190\u0327": "E",
        "\u025B\u0327": "e",
        "\u1E28": "H",
        "\u1E29": "h",
        "I\u0327": "I",
        "i\u0327": "i",
        "\u0197\u0327": "I",
        "\u0268\u0327": "i",
        "M\u0327": "M",
        "m\u0327": "m",
        "O\u0327": "O",
        "o\u0327": "o",
        "Q\u0327": "Q",
        "q\u0327": "q",
        "U\u0327": "U",
        "u\u0327": "u",
        "X\u0327": "X",
        "x\u0327": "x",
        "Z\u0327": "Z",
        "z\u0327": "z",
        "\u0439": "\u0438",
        "\u0419": "\u0418",
        "\u0451": "\u0435",
        "\u0401": "\u0415"
      };
      var chars = Object.keys(characterMap).join("|");
      var allAccents = new RegExp(chars, "g");
      var firstAccent = new RegExp(chars, "");
      function matcher(match3) {
        return characterMap[match3];
      }
      var removeAccents3 = function(string) {
        return string.replace(allAccents, matcher);
      };
      var hasAccents = function(string) {
        return !!string.match(firstAccent);
      };
      module.exports = removeAccents3;
      module.exports.has = hasAccents;
      module.exports.remove = removeAccents3;
    }
  });

  // package-external:@wordpress/date
  var require_date = __commonJS({
    "package-external:@wordpress/date"(exports, module) {
      module.exports = window.wp.date;
    }
  });

  // package-external:@wordpress/warning
  var require_warning = __commonJS({
    "package-external:@wordpress/warning"(exports, module) {
      module.exports = window.wp.warning;
    }
  });

  // package-external:@wordpress/rich-text
  var require_rich_text = __commonJS({
    "package-external:@wordpress/rich-text"(exports, module) {
      module.exports = window.wp.richText;
    }
  });

  // package-external:@wordpress/media-utils
  var require_media_utils = __commonJS({
    "package-external:@wordpress/media-utils"(exports, module) {
      module.exports = window.wp.mediaUtils;
    }
  });

  // packages/edit-site/build-module/index.mjs
  var index_exports = {};
  __export(index_exports, {
    PluginMoreMenuItem: () => PluginMoreMenuItem,
    PluginSidebar: () => PluginSidebar,
    PluginSidebarMoreMenuItem: () => PluginSidebarMoreMenuItem,
    PluginTemplateSettingPanel: () => plugin_template_setting_panel_default,
    initializeEditor: () => initializeEditor,
    reinitializeEditor: () => reinitializeEditor,
    store: () => store
  });
  var import_blocks15 = __toESM(require_blocks(), 1);
  var import_block_library4 = __toESM(require_block_library(), 1);
  var import_data89 = __toESM(require_data(), 1);
  var import_deprecated6 = __toESM(require_deprecated(), 1);
  var import_element200 = __toESM(require_element(), 1);
  var import_editor46 = __toESM(require_editor(), 1);
  var import_preferences13 = __toESM(require_preferences(), 1);
  var import_widgets = __toESM(require_widgets(), 1);

  // packages/edit-site/build-module/store/index.mjs
  var import_data3 = __toESM(require_data(), 1);

  // packages/edit-site/build-module/store/reducer.mjs
  var import_data = __toESM(require_data(), 1);
  function settings(state = {}, action) {
    switch (action.type) {
      case "UPDATE_SETTINGS":
        return {
          ...state,
          ...action.settings
        };
    }
    return state;
  }
  function editedPost(state = {}, action) {
    switch (action.type) {
      case "SET_EDITED_POST":
        return {
          postType: action.postType,
          id: action.id,
          context: action.context
        };
      case "SET_EDITED_POST_CONTEXT":
        return {
          ...state,
          context: action.context
        };
    }
    return state;
  }
  function saveViewPanel(state = false, action) {
    switch (action.type) {
      case "SET_IS_SAVE_VIEW_OPENED":
        return action.isOpen;
    }
    return state;
  }
  function routes(state = [], action) {
    switch (action.type) {
      case "REGISTER_ROUTE":
        return [...state, action.route];
      case "UNREGISTER_ROUTE":
        return state.filter((route) => route.name !== action.name);
    }
    return state;
  }
  var reducer_default = (0, import_data.combineReducers)({
    settings,
    editedPost,
    saveViewPanel,
    routes
  });

  // packages/edit-site/build-module/store/actions.mjs
  var actions_exports = {};
  __export(actions_exports, {
    __experimentalSetPreviewDeviceType: () => __experimentalSetPreviewDeviceType,
    addTemplate: () => addTemplate,
    closeGeneralSidebar: () => closeGeneralSidebar,
    openGeneralSidebar: () => openGeneralSidebar,
    openNavigationPanelToMenu: () => openNavigationPanelToMenu,
    removeTemplate: () => removeTemplate,
    revertTemplate: () => revertTemplate,
    setEditedEntity: () => setEditedEntity,
    setEditedPostContext: () => setEditedPostContext,
    setHasPageContentFocus: () => setHasPageContentFocus,
    setHomeTemplateId: () => setHomeTemplateId,
    setIsInserterOpened: () => setIsInserterOpened,
    setIsListViewOpened: () => setIsListViewOpened,
    setIsNavigationPanelOpened: () => setIsNavigationPanelOpened,
    setIsSaveViewOpened: () => setIsSaveViewOpened,
    setNavigationMenu: () => setNavigationMenu,
    setNavigationPanelActiveMenu: () => setNavigationPanelActiveMenu,
    setPage: () => setPage,
    setTemplate: () => setTemplate,
    setTemplatePart: () => setTemplatePart,
    switchEditorMode: () => switchEditorMode,
    toggleDistractionFree: () => toggleDistractionFree,
    toggleFeature: () => toggleFeature,
    updateSettings: () => updateSettings
  });
  var import_blocks = __toESM(require_blocks(), 1);
  var import_deprecated = __toESM(require_deprecated(), 1);
  var import_core_data = __toESM(require_core_data(), 1);
  var import_block_editor = __toESM(require_block_editor(), 1);
  var import_editor = __toESM(require_editor(), 1);
  var import_preferences = __toESM(require_preferences(), 1);

  // packages/edit-site/build-module/utils/constants.mjs
  var import_i18n = __toESM(require_i18n(), 1);
  var import_patterns = __toESM(require_patterns(), 1);

  // packages/edit-site/build-module/lock-unlock.mjs
  var import_private_apis = __toESM(require_private_apis(), 1);
  var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
    "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
    "@wordpress/edit-site"
  );

  // packages/edit-site/build-module/utils/constants.mjs
  var ATTACHMENT_POST_TYPE = "attachment";
  var NAVIGATION_POST_TYPE = "wp_navigation";
  var TEMPLATE_POST_TYPE = "wp_template";
  var TEMPLATE_PART_POST_TYPE = "wp_template_part";
  var TEMPLATE_ORIGINS = {
    custom: "custom",
    theme: "theme",
    plugin: "plugin"
  };
  var TEMPLATE_PART_AREA_DEFAULT_CATEGORY = "uncategorized";
  var TEMPLATE_PART_ALL_AREAS_CATEGORY = "all-parts";
  var {
    PATTERN_TYPES,
    PATTERN_DEFAULT_CATEGORY,
    PATTERN_USER_CATEGORY,
    EXCLUDED_PATTERN_SOURCES,
    PATTERN_SYNC_TYPES
  } = unlock(import_patterns.privateApis);
  var FOCUSABLE_ENTITIES = [
    TEMPLATE_PART_POST_TYPE,
    NAVIGATION_POST_TYPE,
    PATTERN_TYPES.user
  ];
  var POST_TYPE_LABELS = {
    [TEMPLATE_POST_TYPE]: (0, import_i18n.__)("Template"),
    [TEMPLATE_PART_POST_TYPE]: (0, import_i18n.__)("Template part"),
    [PATTERN_TYPES.user]: (0, import_i18n.__)("Pattern"),
    [NAVIGATION_POST_TYPE]: (0, import_i18n.__)("Navigation")
  };
  var LAYOUT_LIST = "list";
  var OPERATOR_IS_ANY = "isAny";
  var OPERATOR_IS_NONE = "isNone";
  var OPERATOR_BEFORE = "before";
  var OPERATOR_AFTER = "after";

  // packages/edit-site/build-module/store/actions.mjs
  var { interfaceStore } = unlock(import_editor.privateApis);
  function toggleFeature(featureName) {
    return function({ registry }) {
      (0, import_deprecated.default)(
        "dispatch( 'core/edit-site' ).toggleFeature( featureName )",
        {
          since: "6.0",
          alternative: "dispatch( 'core/preferences').toggle( 'core/edit-site', featureName )"
        }
      );
      registry.dispatch(import_preferences.store).toggle("core/edit-site", featureName);
    };
  }
  var __experimentalSetPreviewDeviceType = (deviceType) => ({ registry }) => {
    (0, import_deprecated.default)(
      "dispatch( 'core/edit-site' ).__experimentalSetPreviewDeviceType",
      {
        since: "6.5",
        version: "6.7",
        hint: "registry.dispatch( editorStore ).setDeviceType"
      }
    );
    registry.dispatch(import_editor.store).setDeviceType(deviceType);
  };
  function setTemplate() {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).setTemplate", {
      since: "6.5",
      version: "6.8",
      hint: "The setTemplate is not needed anymore, the correct entity is resolved from the URL automatically."
    });
    return {
      type: "NOTHING"
    };
  }
  var addTemplate = (template) => async ({ dispatch: dispatch2, registry }) => {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).addTemplate", {
      since: "6.5",
      version: "6.8",
      hint: "use saveEntityRecord directly"
    });
    const newTemplate = await registry.dispatch(import_core_data.store).saveEntityRecord("postType", TEMPLATE_POST_TYPE, template);
    if (template.content) {
      registry.dispatch(import_core_data.store).editEntityRecord(
        "postType",
        TEMPLATE_POST_TYPE,
        newTemplate.id,
        { blocks: (0, import_blocks.parse)(template.content) },
        { undoIgnore: true }
      );
    }
    dispatch2({
      type: "SET_EDITED_POST",
      postType: TEMPLATE_POST_TYPE,
      id: newTemplate.id
    });
  };
  var removeTemplate = (template) => ({ registry }) => {
    return unlock(registry.dispatch(import_editor.store)).removeTemplates([
      template
    ]);
  };
  function setTemplatePart(templatePartId) {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).setTemplatePart", {
      since: "6.8"
    });
    return {
      type: "SET_EDITED_POST",
      postType: TEMPLATE_PART_POST_TYPE,
      id: templatePartId
    };
  }
  function setNavigationMenu(navigationMenuId) {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).setNavigationMenu", {
      since: "6.8"
    });
    return {
      type: "SET_EDITED_POST",
      postType: NAVIGATION_POST_TYPE,
      id: navigationMenuId
    };
  }
  function setEditedEntity(postType2, postId, context) {
    return {
      type: "SET_EDITED_POST",
      postType: postType2,
      id: postId,
      context
    };
  }
  function setHomeTemplateId() {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).setHomeTemplateId", {
      since: "6.2",
      version: "6.4"
    });
    return {
      type: "NOTHING"
    };
  }
  function setEditedPostContext(context) {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).setEditedPostContext", {
      since: "6.8"
    });
    return {
      type: "SET_EDITED_POST_CONTEXT",
      context
    };
  }
  function setPage() {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).setPage", {
      since: "6.5",
      version: "6.8",
      hint: "The setPage is not needed anymore, the correct entity is resolved from the URL automatically."
    });
    return { type: "NOTHING" };
  }
  function setNavigationPanelActiveMenu() {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).setNavigationPanelActiveMenu", {
      since: "6.2",
      version: "6.4"
    });
    return { type: "NOTHING" };
  }
  function openNavigationPanelToMenu() {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).openNavigationPanelToMenu", {
      since: "6.2",
      version: "6.4"
    });
    return { type: "NOTHING" };
  }
  function setIsNavigationPanelOpened() {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).setIsNavigationPanelOpened", {
      since: "6.2",
      version: "6.4"
    });
    return { type: "NOTHING" };
  }
  var setIsInserterOpened = (value) => ({ registry }) => {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).setIsInserterOpened", {
      since: "6.5",
      alternative: "dispatch( 'core/editor').setIsInserterOpened"
    });
    registry.dispatch(import_editor.store).setIsInserterOpened(value);
  };
  var setIsListViewOpened = (isOpen) => ({ registry }) => {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).setIsListViewOpened", {
      since: "6.5",
      alternative: "dispatch( 'core/editor').setIsListViewOpened"
    });
    registry.dispatch(import_editor.store).setIsListViewOpened(isOpen);
  };
  function updateSettings(settings2) {
    return {
      type: "UPDATE_SETTINGS",
      settings: settings2
    };
  }
  function setIsSaveViewOpened(isOpen) {
    return {
      type: "SET_IS_SAVE_VIEW_OPENED",
      isOpen
    };
  }
  var revertTemplate = (template, options) => ({ registry }) => {
    return unlock(registry.dispatch(import_editor.store)).revertTemplate(
      template,
      options
    );
  };
  var openGeneralSidebar = (name2) => ({ registry }) => {
    registry.dispatch(interfaceStore).enableComplementaryArea("core", name2);
  };
  var closeGeneralSidebar = () => ({ registry }) => {
    registry.dispatch(interfaceStore).disableComplementaryArea("core");
  };
  var switchEditorMode = (mode) => ({ registry }) => {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).switchEditorMode", {
      since: "6.6",
      alternative: "dispatch( 'core/editor').switchEditorMode"
    });
    registry.dispatch(import_editor.store).switchEditorMode(mode);
  };
  var setHasPageContentFocus = (hasPageContentFocus2) => ({ dispatch: dispatch2, registry }) => {
    (0, import_deprecated.default)(`dispatch( 'core/edit-site' ).setHasPageContentFocus`, {
      since: "6.5"
    });
    if (hasPageContentFocus2) {
      registry.dispatch(import_block_editor.store).clearSelectedBlock();
    }
    dispatch2({
      type: "SET_HAS_PAGE_CONTENT_FOCUS",
      hasPageContentFocus: hasPageContentFocus2
    });
  };
  var toggleDistractionFree = () => ({ registry }) => {
    (0, import_deprecated.default)("dispatch( 'core/edit-site' ).toggleDistractionFree", {
      since: "6.6",
      alternative: "dispatch( 'core/editor').toggleDistractionFree"
    });
    registry.dispatch(import_editor.store).toggleDistractionFree();
  };

  // packages/edit-site/build-module/store/private-actions.mjs
  var private_actions_exports = {};
  __export(private_actions_exports, {
    registerRoute: () => registerRoute,
    unregisterRoute: () => unregisterRoute
  });
  function registerRoute(route) {
    return {
      type: "REGISTER_ROUTE",
      route
    };
  }
  function unregisterRoute(name2) {
    return {
      type: "UNREGISTER_ROUTE",
      name: name2
    };
  }

  // packages/edit-site/build-module/store/selectors.mjs
  var selectors_exports = {};
  __export(selectors_exports, {
    __experimentalGetInsertionPoint: () => __experimentalGetInsertionPoint,
    __experimentalGetPreviewDeviceType: () => __experimentalGetPreviewDeviceType,
    getCanUserCreateMedia: () => getCanUserCreateMedia,
    getCurrentTemplateNavigationPanelSubMenu: () => getCurrentTemplateNavigationPanelSubMenu,
    getCurrentTemplateTemplateParts: () => getCurrentTemplateTemplateParts,
    getEditedPostContext: () => getEditedPostContext,
    getEditedPostId: () => getEditedPostId,
    getEditedPostType: () => getEditedPostType,
    getEditorMode: () => getEditorMode,
    getHomeTemplateId: () => getHomeTemplateId,
    getNavigationPanelActiveMenu: () => getNavigationPanelActiveMenu,
    getPage: () => getPage,
    getReusableBlocks: () => getReusableBlocks,
    getSettings: () => getSettings,
    hasPageContentFocus: () => hasPageContentFocus,
    isFeatureActive: () => isFeatureActive,
    isInserterOpened: () => isInserterOpened,
    isListViewOpened: () => isListViewOpened,
    isNavigationOpened: () => isNavigationOpened,
    isPage: () => isPage,
    isSaveViewOpened: () => isSaveViewOpened
  });
  var import_core_data2 = __toESM(require_core_data(), 1);
  var import_data2 = __toESM(require_data(), 1);
  var import_deprecated2 = __toESM(require_deprecated(), 1);
  var import_preferences2 = __toESM(require_preferences(), 1);
  var import_editor2 = __toESM(require_editor(), 1);
  var import_block_editor2 = __toESM(require_block_editor(), 1);

  // packages/edit-site/build-module/utils/get-filtered-template-parts.mjs
  var import_blocks2 = __toESM(require_blocks(), 1);
  var EMPTY_ARRAY = [];
  function getFilteredTemplatePartBlocks(blocks = EMPTY_ARRAY, templateParts) {
    const templatePartsById = templateParts ? (
      // Key template parts by their ID.
      templateParts.reduce(
        (newTemplateParts, part) => ({
          ...newTemplateParts,
          [part.id]: part
        }),
        {}
      )
    ) : {};
    const result = [];
    const stack = [...blocks];
    while (stack.length) {
      const { innerBlocks, ...block } = stack.shift();
      stack.unshift(...innerBlocks);
      if ((0, import_blocks2.isTemplatePart)(block)) {
        const {
          attributes: { theme: theme2, slug }
        } = block;
        const templatePartId = `${theme2}//${slug}`;
        const templatePart = templatePartsById[templatePartId];
        if (templatePart) {
          result.push({
            templatePart,
            block
          });
        }
      }
    }
    return result;
  }

  // packages/edit-site/build-module/store/selectors.mjs
  var isFeatureActive = (0, import_data2.createRegistrySelector)(
    (select4) => (_, featureName) => {
      (0, import_deprecated2.default)(`select( 'core/edit-site' ).isFeatureActive`, {
        since: "6.0",
        alternative: `select( 'core/preferences' ).get`
      });
      return !!select4(import_preferences2.store).get(
        "core/edit-site",
        featureName
      );
    }
  );
  var __experimentalGetPreviewDeviceType = (0, import_data2.createRegistrySelector)(
    (select4) => () => {
      (0, import_deprecated2.default)(
        `select( 'core/edit-site' ).__experimentalGetPreviewDeviceType`,
        {
          since: "6.5",
          version: "6.7",
          alternative: `select( 'core/editor' ).getDeviceType`
        }
      );
      return select4(import_editor2.store).getDeviceType();
    }
  );
  var getCanUserCreateMedia = (0, import_data2.createRegistrySelector)(
    (select4) => () => {
      (0, import_deprecated2.default)(
        `wp.data.select( 'core/edit-site' ).getCanUserCreateMedia()`,
        {
          since: "6.7",
          alternative: `wp.data.select( 'core' ).canUser( 'create', { kind: 'postType', type: 'attachment' } )`
        }
      );
      return select4(import_core_data2.store).canUser("create", "media");
    }
  );
  var getReusableBlocks = (0, import_data2.createRegistrySelector)((select4) => () => {
    (0, import_deprecated2.default)(`select( 'core/edit-site' ).getReusableBlocks()`, {
      since: "6.5",
      version: "6.8",
      alternative: `select( 'core/core' ).getEntityRecords( 'postType', 'wp_block' )`
    });
    return select4(import_core_data2.store).getEntityRecords("postType", "wp_block", {
      per_page: -1
    });
  });
  function getSettings(state) {
    return state.settings;
  }
  function getHomeTemplateId() {
    (0, import_deprecated2.default)("select( 'core/edit-site' ).getHomeTemplateId", {
      since: "6.2",
      version: "6.4"
    });
  }
  function getEditedPostType(state) {
    (0, import_deprecated2.default)("select( 'core/edit-site' ).getEditedPostType", {
      since: "6.8",
      alternative: "select( 'core/editor' ).getCurrentPostType"
    });
    return state.editedPost.postType;
  }
  function getEditedPostId(state) {
    (0, import_deprecated2.default)("select( 'core/edit-site' ).getEditedPostId", {
      since: "6.8",
      alternative: "select( 'core/editor' ).getCurrentPostId"
    });
    return state.editedPost.id;
  }
  function getEditedPostContext(state) {
    (0, import_deprecated2.default)("select( 'core/edit-site' ).getEditedPostContext", {
      since: "6.8"
    });
    return state.editedPost.context;
  }
  function getPage(state) {
    (0, import_deprecated2.default)("select( 'core/edit-site' ).getPage", {
      since: "6.8"
    });
    return { context: state.editedPost.context };
  }
  var isInserterOpened = (0, import_data2.createRegistrySelector)((select4) => () => {
    (0, import_deprecated2.default)(`select( 'core/edit-site' ).isInserterOpened`, {
      since: "6.5",
      alternative: `select( 'core/editor' ).isInserterOpened`
    });
    return select4(import_editor2.store).isInserterOpened();
  });
  var __experimentalGetInsertionPoint = (0, import_data2.createRegistrySelector)(
    (select4) => () => {
      (0, import_deprecated2.default)(
        `select( 'core/edit-site' ).__experimentalGetInsertionPoint`,
        {
          since: "6.5",
          version: "6.7"
        }
      );
      return unlock(select4(import_editor2.store)).getInserter();
    }
  );
  var isListViewOpened = (0, import_data2.createRegistrySelector)((select4) => () => {
    (0, import_deprecated2.default)(`select( 'core/edit-site' ).isListViewOpened`, {
      since: "6.5",
      alternative: `select( 'core/editor' ).isListViewOpened`
    });
    return select4(import_editor2.store).isListViewOpened();
  });
  function isSaveViewOpened(state) {
    return state.saveViewPanel;
  }
  function getBlocksAndTemplateParts(select4) {
    const templateParts = select4(import_core_data2.store).getEntityRecords(
      "postType",
      TEMPLATE_PART_POST_TYPE,
      { per_page: -1 }
    );
    const { getBlocksByName, getBlocksByClientId } = select4(import_block_editor2.store);
    const clientIds = getBlocksByName("core/template-part");
    const blocks = getBlocksByClientId(clientIds);
    return [blocks, templateParts];
  }
  var getCurrentTemplateTemplateParts = (0, import_data2.createRegistrySelector)(
    (select4) => (0, import_data2.createSelector)(
      () => {
        (0, import_deprecated2.default)(
          `select( 'core/edit-site' ).getCurrentTemplateTemplateParts()`,
          {
            since: "6.7",
            version: "6.9",
            alternative: `select( 'core/block-editor' ).getBlocksByName( 'core/template-part' )`
          }
        );
        return getFilteredTemplatePartBlocks(
          ...getBlocksAndTemplateParts(select4)
        );
      },
      () => getBlocksAndTemplateParts(select4)
    )
  );
  var getEditorMode = (0, import_data2.createRegistrySelector)((select4) => () => {
    return select4(import_preferences2.store).get("core", "editorMode");
  });
  function getCurrentTemplateNavigationPanelSubMenu() {
    (0, import_deprecated2.default)(
      "dispatch( 'core/edit-site' ).getCurrentTemplateNavigationPanelSubMenu",
      {
        since: "6.2",
        version: "6.4"
      }
    );
  }
  function getNavigationPanelActiveMenu() {
    (0, import_deprecated2.default)("dispatch( 'core/edit-site' ).getNavigationPanelActiveMenu", {
      since: "6.2",
      version: "6.4"
    });
  }
  function isNavigationOpened() {
    (0, import_deprecated2.default)("dispatch( 'core/edit-site' ).isNavigationOpened", {
      since: "6.2",
      version: "6.4"
    });
  }
  function isPage(state) {
    (0, import_deprecated2.default)("select( 'core/edit-site' ).isPage", {
      since: "6.8",
      alternative: "select( 'core/editor' ).getCurrentPostType"
    });
    return !!state.editedPost.context?.postId;
  }
  function hasPageContentFocus() {
    (0, import_deprecated2.default)(`select( 'core/edit-site' ).hasPageContentFocus`, {
      since: "6.5"
    });
    return false;
  }

  // packages/edit-site/build-module/store/private-selectors.mjs
  var private_selectors_exports = {};
  __export(private_selectors_exports, {
    getRoutes: () => getRoutes
  });
  function getRoutes(state) {
    return state.routes;
  }

  // packages/edit-site/build-module/store/constants.mjs
  var STORE_NAME = "core/edit-site";

  // packages/edit-site/build-module/store/index.mjs
  var storeConfig = {
    reducer: reducer_default,
    actions: actions_exports,
    selectors: selectors_exports
  };
  var store = (0, import_data3.createReduxStore)(STORE_NAME, storeConfig);
  (0, import_data3.register)(store);
  unlock(store).registerPrivateSelectors(private_selectors_exports);
  unlock(store).registerPrivateActions(private_actions_exports);

  // packages/edit-site/build-module/components/app/index.mjs
  var import_data88 = __toESM(require_data(), 1);
  var import_router37 = __toESM(require_router(), 1);
  var import_element199 = __toESM(require_element(), 1);
  var import_core_data69 = __toESM(require_core_data(), 1);

  // node_modules/clsx/dist/clsx.mjs
  function r(e2) {
    var t3, f2, n2 = "";
    if ("string" == typeof e2 || "number" == typeof e2) n2 += e2;
    else if ("object" == typeof e2) if (Array.isArray(e2)) {
      var o3 = e2.length;
      for (t3 = 0; t3 < o3; t3++) e2[t3] && (f2 = r(e2[t3])) && (n2 && (n2 += " "), n2 += f2);
    } else for (f2 in e2) e2[f2] && (n2 && (n2 += " "), n2 += f2);
    return n2;
  }
  function clsx() {
    for (var e2, t3, f2 = 0, n2 = "", o3 = arguments.length; f2 < o3; f2++) (e2 = arguments[f2]) && (t3 = r(e2)) && (n2 && (n2 += " "), n2 += t3);
    return n2;
  }
  var clsx_default = clsx;

  // packages/ui/build-module/badge/badge.mjs
  var import_element11 = __toESM(require_element(), 1);

  // node_modules/@base-ui/utils/useControlled.mjs
  var React = __toESM(require_react(), 1);

  // node_modules/@base-ui/utils/error.mjs
  var set;
  if (true) {
    set = /* @__PURE__ */ new Set();
  }
  function error(...messages) {
    if (true) {
      const messageKey = messages.join(" ");
      if (!set.has(messageKey)) {
        set.add(messageKey);
        console.error(`Base UI: ${messageKey}`);
      }
    }
  }

  // node_modules/@base-ui/utils/useControlled.mjs
  function useControlled({
    controlled,
    default: defaultProp,
    name: name2,
    state = "value"
  }) {
    const {
      current: isControlled
    } = React.useRef(controlled !== void 0);
    const [valueState, setValue] = React.useState(defaultProp);
    const value = isControlled ? controlled : valueState;
    if (true) {
      React.useEffect(() => {
        if (isControlled !== (controlled !== void 0)) {
          error([`A component is changing the ${isControlled ? "" : "un"}controlled ${state} state of ${name2} to be ${isControlled ? "un" : ""}controlled.`, "Elements should not switch from uncontrolled to controlled (or vice versa).", `Decide between using a controlled or uncontrolled ${name2} element for the lifetime of the component.`, "The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.", "More info: https://fb.me/react-controlled-components"].join("\n"));
        }
      }, [state, name2, controlled]);
      const {
        current: defaultValue2
      } = React.useRef(defaultProp);
      React.useEffect(() => {
        if (!isControlled && serializeToDevModeString(defaultValue2) !== serializeToDevModeString(defaultProp)) {
          error([`A component is changing the default ${state} state of an uncontrolled ${name2} after being initialized. To suppress this warning opt to use a controlled ${name2}.`].join("\n"));
        }
      }, [defaultProp]);
    }
    const setValueIfUncontrolled = React.useCallback((newValue) => {
      if (!isControlled) {
        setValue(newValue);
      }
    }, []);
    return [value, setValueIfUncontrolled];
  }
  function serializeToDevModeString(input) {
    let nextId2 = 0;
    const seen = /* @__PURE__ */ new WeakMap();
    try {
      const result = JSON.stringify(input, function replacer(key, value) {
        if (key === "_owner" && this != null && typeof this === "object" && "$$typeof" in this) {
          return void 0;
        }
        if (typeof value === "bigint") {
          return `__bigint__:${value}`;
        }
        if (value !== null && typeof value === "object") {
          const id = seen.get(value);
          if (id !== void 0) {
            return `__object__:${id}`;
          }
          seen.set(value, nextId2);
          nextId2 += 1;
        }
        return value;
      });
      return result ?? `__top__:${typeof input}`;
    } catch {
      return "__unserializable__";
    }
  }

  // node_modules/@base-ui/utils/safeReact.mjs
  var React2 = __toESM(require_react(), 1);
  var SafeReact = {
    ...React2
  };

  // node_modules/@base-ui/utils/useRefWithInit.mjs
  var React3 = __toESM(require_react(), 1);
  var UNINITIALIZED = {};
  function useRefWithInit(init2, initArg) {
    const ref = React3.useRef(UNINITIALIZED);
    if (ref.current === UNINITIALIZED) {
      ref.current = init2(initArg);
    }
    return ref;
  }

  // node_modules/@base-ui/utils/useStableCallback.mjs
  var useInsertionEffect = SafeReact.useInsertionEffect;
  var useSafeInsertionEffect = (
    // React 17 doesn't have useInsertionEffect.
    useInsertionEffect && // Preact replaces useInsertionEffect with useLayoutEffect and fires too late.
    useInsertionEffect !== SafeReact.useLayoutEffect ? useInsertionEffect : (fn) => fn()
  );
  function useStableCallback(callback) {
    const stable = useRefWithInit(createStableCallback).current;
    stable.next = callback;
    useSafeInsertionEffect(stable.effect);
    return stable.trampoline;
  }
  function createStableCallback() {
    const stable = {
      next: void 0,
      callback: assertNotCalled,
      trampoline: (...args) => stable.callback?.(...args),
      effect: () => {
        stable.callback = stable.next;
      }
    };
    return stable;
  }
  function assertNotCalled() {
    if (true) {
      throw (
        /* minify-error-disabled */
        new Error("Base UI: Cannot call an event handler while rendering.")
      );
    }
  }

  // node_modules/@base-ui/utils/useIsoLayoutEffect.mjs
  var React4 = __toESM(require_react(), 1);
  var noop = () => {
  };
  var useIsoLayoutEffect = typeof document !== "undefined" ? React4.useLayoutEffect : noop;

  // node_modules/@base-ui/utils/warn.mjs
  var set2;
  if (true) {
    set2 = /* @__PURE__ */ new Set();
  }
  function warn(...messages) {
    if (true) {
      const messageKey = messages.join(" ");
      if (!set2.has(messageKey)) {
        set2.add(messageKey);
        console.warn(`Base UI: ${messageKey}`);
      }
    }
  }

  // node_modules/@base-ui/react/internals/direction-context/DirectionContext.mjs
  var React5 = __toESM(require_react(), 1);
  var DirectionContext = /* @__PURE__ */ React5.createContext(void 0);
  if (true) DirectionContext.displayName = "DirectionContext";
  function useDirection() {
    const context = React5.useContext(DirectionContext);
    return context?.direction ?? "ltr";
  }

  // node_modules/@base-ui/react/internals/useRenderElement.mjs
  var React8 = __toESM(require_react(), 1);

  // node_modules/@base-ui/utils/useMergedRefs.mjs
  function useMergedRefs(a2, b2, c6, d2) {
    const forkRef = useRefWithInit(createForkRef).current;
    if (didChange(forkRef, a2, b2, c6, d2)) {
      update(forkRef, [a2, b2, c6, d2]);
    }
    return forkRef.callback;
  }
  function useMergedRefsN(refs) {
    const forkRef = useRefWithInit(createForkRef).current;
    if (didChangeN(forkRef, refs)) {
      update(forkRef, refs);
    }
    return forkRef.callback;
  }
  function createForkRef() {
    return {
      callback: null,
      cleanup: null,
      refs: []
    };
  }
  function didChange(forkRef, a2, b2, c6, d2) {
    return forkRef.refs[0] !== a2 || forkRef.refs[1] !== b2 || forkRef.refs[2] !== c6 || forkRef.refs[3] !== d2;
  }
  function didChangeN(forkRef, newRefs) {
    return forkRef.refs.length !== newRefs.length || forkRef.refs.some((ref, index2) => ref !== newRefs[index2]);
  }
  function update(forkRef, refs) {
    forkRef.refs = refs;
    if (refs.every((ref) => ref == null)) {
      forkRef.callback = null;
      return;
    }
    forkRef.callback = (instance) => {
      if (forkRef.cleanup) {
        forkRef.cleanup();
        forkRef.cleanup = null;
      }
      if (instance != null) {
        const cleanupCallbacks = Array(refs.length).fill(null);
        for (let i2 = 0; i2 < refs.length; i2 += 1) {
          const ref = refs[i2];
          if (ref == null) {
            continue;
          }
          switch (typeof ref) {
            case "function": {
              const refCleanup = ref(instance);
              if (typeof refCleanup === "function") {
                cleanupCallbacks[i2] = refCleanup;
              }
              break;
            }
            case "object": {
              ref.current = instance;
              break;
            }
            default:
          }
        }
        forkRef.cleanup = () => {
          for (let i2 = 0; i2 < refs.length; i2 += 1) {
            const ref = refs[i2];
            if (ref == null) {
              continue;
            }
            switch (typeof ref) {
              case "function": {
                const cleanupCallback = cleanupCallbacks[i2];
                if (typeof cleanupCallback === "function") {
                  cleanupCallback();
                } else {
                  ref(null);
                }
                break;
              }
              case "object": {
                ref.current = null;
                break;
              }
              default:
            }
          }
        };
      }
    };
  }

  // node_modules/@base-ui/utils/getReactElementRef.mjs
  var React7 = __toESM(require_react(), 1);

  // node_modules/@base-ui/utils/reactVersion.mjs
  var React6 = __toESM(require_react(), 1);
  var majorVersion = parseInt(React6.version, 10);
  function isReactVersionAtLeast(reactVersionToCheck) {
    return majorVersion >= reactVersionToCheck;
  }

  // node_modules/@base-ui/utils/getReactElementRef.mjs
  function getReactElementRef(element) {
    if (!/* @__PURE__ */ React7.isValidElement(element)) {
      return null;
    }
    const reactElement = element;
    const propsWithRef = reactElement.props;
    return (isReactVersionAtLeast(19) ? propsWithRef?.ref : reactElement.ref) ?? null;
  }

  // node_modules/@base-ui/utils/mergeObjects.mjs
  function mergeObjects(a2, b2) {
    if (a2 && !b2) {
      return a2;
    }
    if (!a2 && b2) {
      return b2;
    }
    if (a2 || b2) {
      return {
        ...a2,
        ...b2
      };
    }
    return void 0;
  }

  // node_modules/@base-ui/utils/empty.mjs
  function NOOP() {
  }
  var EMPTY_ARRAY2 = Object.freeze([]);
  var EMPTY_OBJECT = Object.freeze({});

  // node_modules/@base-ui/react/internals/getStateAttributesProps.mjs
  function getStateAttributesProps(state, customMapping) {
    const props = {};
    for (const key in state) {
      const value = state[key];
      if (customMapping?.hasOwnProperty(key)) {
        const customProps = customMapping[key](value);
        if (customProps != null) {
          Object.assign(props, customProps);
        }
        continue;
      }
      if (value === true) {
        props[`data-${key.toLowerCase()}`] = "";
      } else if (value) {
        props[`data-${key.toLowerCase()}`] = value.toString();
      }
    }
    return props;
  }

  // node_modules/@base-ui/react/utils/resolveClassName.mjs
  function resolveClassName(className, state) {
    return typeof className === "function" ? className(state) : className;
  }

  // node_modules/@base-ui/react/utils/resolveStyle.mjs
  function resolveStyle(style, state) {
    return typeof style === "function" ? style(state) : style;
  }

  // node_modules/@base-ui/react/merge-props/mergeProps.mjs
  var EMPTY_PROPS = {};
  function mergeProps(a2, b2, c6, d2, e2) {
    if (!c6 && !d2 && !e2 && !a2) {
      return createInitialMergedProps(b2);
    }
    let merged = createInitialMergedProps(a2);
    if (b2) {
      merged = mergeInto(merged, b2);
    }
    if (c6) {
      merged = mergeInto(merged, c6);
    }
    if (d2) {
      merged = mergeInto(merged, d2);
    }
    if (e2) {
      merged = mergeInto(merged, e2);
    }
    return merged;
  }
  function mergePropsN(props) {
    if (props.length === 0) {
      return EMPTY_PROPS;
    }
    if (props.length === 1) {
      return createInitialMergedProps(props[0]);
    }
    let merged = createInitialMergedProps(props[0]);
    for (let i2 = 1; i2 < props.length; i2 += 1) {
      merged = mergeInto(merged, props[i2]);
    }
    return merged;
  }
  function createInitialMergedProps(inputProps) {
    if (isPropsGetter(inputProps)) {
      return {
        ...resolvePropsGetter(inputProps, EMPTY_PROPS)
      };
    }
    return copyInitialProps(inputProps);
  }
  function mergeInto(merged, inputProps) {
    if (isPropsGetter(inputProps)) {
      return resolvePropsGetter(inputProps, merged);
    }
    return mutablyMergeInto(merged, inputProps);
  }
  function copyInitialProps(inputProps) {
    const copiedProps = {
      ...inputProps
    };
    for (const propName in copiedProps) {
      const propValue = copiedProps[propName];
      if (isEventHandler(propName, propValue)) {
        copiedProps[propName] = wrapEventHandler(propValue);
      }
    }
    return copiedProps;
  }
  function mutablyMergeInto(mergedProps, externalProps) {
    if (!externalProps) {
      return mergedProps;
    }
    for (const propName in externalProps) {
      const externalPropValue = externalProps[propName];
      switch (propName) {
        case "style": {
          mergedProps[propName] = mergeObjects(mergedProps.style, externalPropValue);
          break;
        }
        case "className": {
          mergedProps[propName] = mergeClassNames(mergedProps.className, externalPropValue);
          break;
        }
        default: {
          if (isEventHandler(propName, externalPropValue)) {
            mergedProps[propName] = mergeEventHandlers(mergedProps[propName], externalPropValue);
          } else {
            mergedProps[propName] = externalPropValue;
          }
        }
      }
    }
    return mergedProps;
  }
  function isEventHandler(key, value) {
    const code0 = key.charCodeAt(0);
    const code1 = key.charCodeAt(1);
    const code2 = key.charCodeAt(2);
    return code0 === 111 && code1 === 110 && code2 >= 65 && code2 <= 90 && (typeof value === "function" || typeof value === "undefined");
  }
  function isPropsGetter(inputProps) {
    return typeof inputProps === "function";
  }
  function resolvePropsGetter(inputProps, previousProps) {
    if (isPropsGetter(inputProps)) {
      return inputProps(previousProps);
    }
    return inputProps ?? EMPTY_PROPS;
  }
  function mergeEventHandlers(ourHandler, theirHandler) {
    if (!theirHandler) {
      return ourHandler;
    }
    if (!ourHandler) {
      return wrapEventHandler(theirHandler);
    }
    return (...args) => {
      const event = args[0];
      if (isSyntheticEvent(event)) {
        const baseUIEvent = event;
        makeEventPreventable(baseUIEvent);
        const result2 = theirHandler(...args);
        if (!baseUIEvent.baseUIHandlerPrevented) {
          ourHandler?.(...args);
        }
        return result2;
      }
      const result = theirHandler(...args);
      ourHandler?.(...args);
      return result;
    };
  }
  function wrapEventHandler(handler) {
    if (!handler) {
      return handler;
    }
    return (...args) => {
      const event = args[0];
      if (isSyntheticEvent(event)) {
        makeEventPreventable(event);
      }
      return handler(...args);
    };
  }
  function makeEventPreventable(event) {
    event.preventBaseUIHandler = () => {
      event.baseUIHandlerPrevented = true;
    };
    return event;
  }
  function mergeClassNames(ourClassName, theirClassName) {
    if (theirClassName) {
      if (ourClassName) {
        return theirClassName + " " + ourClassName;
      }
      return theirClassName;
    }
    return ourClassName;
  }
  function isSyntheticEvent(event) {
    return event != null && typeof event === "object" && "nativeEvent" in event;
  }

  // node_modules/@base-ui/react/internals/useRenderElement.mjs
  var import_react = __toESM(require_react(), 1);
  function useRenderElement(element, componentProps, params = {}) {
    const renderProp = componentProps.render;
    const outProps = useRenderElementProps(componentProps, params);
    if (params.enabled === false) {
      return null;
    }
    const state = params.state ?? EMPTY_OBJECT;
    return evaluateRenderProp(element, renderProp, outProps, state);
  }
  function useRenderElementProps(componentProps, params = {}) {
    const {
      className: classNameProp,
      style: styleProp,
      render: renderProp
    } = componentProps;
    const {
      state = EMPTY_OBJECT,
      ref,
      props,
      stateAttributesMapping: stateAttributesMapping4,
      enabled = true
    } = params;
    const className = enabled ? resolveClassName(classNameProp, state) : void 0;
    const style = enabled ? resolveStyle(styleProp, state) : void 0;
    const stateProps = enabled ? getStateAttributesProps(state, stateAttributesMapping4) : EMPTY_OBJECT;
    const resolvedProps = enabled && props ? resolveRenderFunctionProps(props) : void 0;
    const outProps = enabled ? mergeObjects(stateProps, resolvedProps) ?? {} : EMPTY_OBJECT;
    if (typeof document !== "undefined") {
      if (!enabled) {
        useMergedRefs(null, null);
      } else if (Array.isArray(ref)) {
        outProps.ref = useMergedRefsN([outProps.ref, getReactElementRef(renderProp), ...ref]);
      } else {
        outProps.ref = useMergedRefs(outProps.ref, getReactElementRef(renderProp), ref);
      }
    }
    if (!enabled) {
      return EMPTY_OBJECT;
    }
    if (className !== void 0) {
      outProps.className = mergeClassNames(outProps.className, className);
    }
    if (style !== void 0) {
      outProps.style = mergeObjects(outProps.style, style);
    }
    return outProps;
  }
  function resolveRenderFunctionProps(props) {
    if (Array.isArray(props)) {
      return mergePropsN(props);
    }
    return mergeProps(void 0, props);
  }
  var REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy");
  var COMPONENT_IDENTIFIER_PATTERN = /^[A-Z][A-Za-z0-9$]*$/;
  var LOWERCASE_CHARACTER_PATTERN = /[a-z]/;
  function evaluateRenderProp(element, render4, props, state) {
    if (render4) {
      if (typeof render4 === "function") {
        if (true) {
          warnIfRenderPropLooksLikeComponent(render4);
        }
        return render4(props, state);
      }
      const mergedProps = mergeProps(props, render4.props);
      mergedProps.ref = props.ref;
      let newElement = render4;
      if (newElement?.$$typeof === REACT_LAZY_TYPE) {
        const children = React8.Children.toArray(render4);
        newElement = children[0];
      }
      if (true) {
        if (!/* @__PURE__ */ React8.isValidElement(newElement)) {
          throw new Error(["Base UI: The `render` prop was provided an invalid React element as `React.isValidElement(render)` is `false`.", "A valid React element must be provided to the `render` prop because it is cloned with props to replace the default element.", "https://base-ui.com/r/invalid-render-prop"].join("\n"));
        }
      }
      return /* @__PURE__ */ React8.cloneElement(newElement, mergedProps);
    }
    if (element) {
      if (typeof element === "string") {
        return renderTag(element, props);
      }
    }
    throw new Error(true ? "Base UI: Render element or function are not defined." : formatErrorMessage_default(8));
  }
  function warnIfRenderPropLooksLikeComponent(renderFn) {
    const functionName = renderFn.name;
    if (functionName.length === 0) {
      return;
    }
    if (!COMPONENT_IDENTIFIER_PATTERN.test(functionName)) {
      return;
    }
    if (!LOWERCASE_CHARACTER_PATTERN.test(functionName)) {
      return;
    }
    warn(`The \`render\` prop received a function named \`${functionName}\` that starts with an uppercase letter.`, "This usually means a React component was passed directly as `render={Component}`.", "Base UI calls `render` as a plain function, which can break the Rules of Hooks during reconciliation.", "If this is an intentional render callback, rename it to start with a lowercase letter.", "Use `render={<Component />}` or `render={(props) => <Component {...props} />}` instead.", "https://base-ui.com/r/invalid-render-prop");
  }
  function renderTag(Tag, props) {
    if (Tag === "button") {
      return /* @__PURE__ */ (0, import_react.createElement)("button", {
        type: "button",
        ...props,
        key: props.key
      });
    }
    if (Tag === "img") {
      return /* @__PURE__ */ (0, import_react.createElement)("img", {
        alt: "",
        ...props,
        key: props.key
      });
    }
    return /* @__PURE__ */ React8.createElement(Tag, props);
  }

  // node_modules/@base-ui/utils/useId.mjs
  var React9 = __toESM(require_react(), 1);
  var globalId = 0;
  function useGlobalId(idOverride, prefix2 = "mui") {
    const [defaultId, setDefaultId] = React9.useState(idOverride);
    const id = idOverride || defaultId;
    React9.useEffect(() => {
      if (defaultId == null) {
        globalId += 1;
        setDefaultId(`${prefix2}-${globalId}`);
      }
    }, [defaultId, prefix2]);
    return id;
  }
  var maybeReactUseId = SafeReact.useId;
  function useId(idOverride, prefix2) {
    if (maybeReactUseId !== void 0) {
      const reactId = maybeReactUseId();
      return idOverride ?? (prefix2 ? `${prefix2}-${reactId}` : reactId);
    }
    return useGlobalId(idOverride, prefix2);
  }

  // node_modules/@base-ui/react/internals/useBaseUiId.mjs
  function useBaseUiId(idOverride) {
    return useId(idOverride, "base-ui");
  }

  // node_modules/@base-ui/react/collapsible/root/useCollapsibleRoot.mjs
  var React12 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/internals/reason-parts.mjs
  var reason_parts_exports = {};
  __export(reason_parts_exports, {
    cancelOpen: () => cancelOpen,
    chipRemovePress: () => chipRemovePress,
    clearPress: () => clearPress,
    closePress: () => closePress,
    closeWatcher: () => closeWatcher,
    decrementPress: () => decrementPress,
    disabled: () => disabled,
    drag: () => drag,
    escapeKey: () => escapeKey,
    focusOut: () => focusOut,
    imperativeAction: () => imperativeAction,
    incrementPress: () => incrementPress,
    initial: () => initial,
    inputBlur: () => inputBlur,
    inputChange: () => inputChange,
    inputClear: () => inputClear,
    inputPaste: () => inputPaste,
    inputPress: () => inputPress,
    itemPress: () => itemPress,
    keyboard: () => keyboard,
    linkPress: () => linkPress,
    listNavigation: () => listNavigation,
    missing: () => missing,
    none: () => none,
    outsidePress: () => outsidePress,
    pointer: () => pointer,
    scrub: () => scrub,
    siblingOpen: () => siblingOpen,
    swipe: () => swipe,
    trackPress: () => trackPress,
    triggerFocus: () => triggerFocus,
    triggerHover: () => triggerHover,
    triggerPress: () => triggerPress,
    wheel: () => wheel,
    windowResize: () => windowResize
  });
  var none = "none";
  var triggerPress = "trigger-press";
  var triggerHover = "trigger-hover";
  var triggerFocus = "trigger-focus";
  var outsidePress = "outside-press";
  var itemPress = "item-press";
  var closePress = "close-press";
  var linkPress = "link-press";
  var clearPress = "clear-press";
  var chipRemovePress = "chip-remove-press";
  var trackPress = "track-press";
  var incrementPress = "increment-press";
  var decrementPress = "decrement-press";
  var inputChange = "input-change";
  var inputClear = "input-clear";
  var inputBlur = "input-blur";
  var inputPaste = "input-paste";
  var inputPress = "input-press";
  var focusOut = "focus-out";
  var escapeKey = "escape-key";
  var closeWatcher = "close-watcher";
  var listNavigation = "list-navigation";
  var keyboard = "keyboard";
  var pointer = "pointer";
  var drag = "drag";
  var wheel = "wheel";
  var scrub = "scrub";
  var cancelOpen = "cancel-open";
  var siblingOpen = "sibling-open";
  var disabled = "disabled";
  var missing = "missing";
  var initial = "initial";
  var imperativeAction = "imperative-action";
  var swipe = "swipe";
  var windowResize = "window-resize";

  // node_modules/@base-ui/react/internals/createBaseUIEventDetails.mjs
  function createChangeEventDetails(reason, event, trigger, customProperties) {
    let canceled = false;
    let allowPropagation = false;
    const custom = customProperties ?? EMPTY_OBJECT;
    const details = {
      reason,
      event: event ?? new Event("base-ui"),
      cancel() {
        canceled = true;
      },
      allowPropagation() {
        allowPropagation = true;
      },
      get isCanceled() {
        return canceled;
      },
      get isPropagationAllowed() {
        return allowPropagation;
      },
      trigger,
      ...custom
    };
    return details;
  }

  // node_modules/@base-ui/react/internals/useTransitionStatus.mjs
  var React11 = __toESM(require_react(), 1);

  // node_modules/@base-ui/utils/useOnMount.mjs
  var React10 = __toESM(require_react(), 1);
  var EMPTY = [];
  function useOnMount(fn) {
    React10.useEffect(fn, EMPTY);
  }

  // node_modules/@base-ui/utils/useAnimationFrame.mjs
  var EMPTY2 = null;
  var LAST_RAF = globalThis.requestAnimationFrame;
  var Scheduler = class {
    /* This implementation uses an array as a backing data-structure for frame callbacks.
     * It allows `O(1)` callback cancelling by inserting a `null` in the array, though it
     * never calls the native `cancelAnimationFrame` if there are no frames left. This can
     * be much more efficient if there is a call pattern that alterns as
     * "request-cancel-request-cancel-…".
     * But in the case of "request-request-…-cancel-cancel-…", it leaves the final animation
     * frame to run anyway. We turn that frame into a `O(1)` no-op via `callbacksCount`. */
    callbacks = [];
    callbacksCount = 0;
    nextId = 1;
    startId = 1;
    isScheduled = false;
    tick = (timestamp) => {
      this.isScheduled = false;
      const currentCallbacks = this.callbacks;
      const currentCallbacksCount = this.callbacksCount;
      this.callbacks = [];
      this.callbacksCount = 0;
      this.startId = this.nextId;
      if (currentCallbacksCount > 0) {
        for (let i2 = 0; i2 < currentCallbacks.length; i2 += 1) {
          currentCallbacks[i2]?.(timestamp);
        }
      }
    };
    request(fn) {
      const id = this.nextId;
      this.nextId += 1;
      this.callbacks.push(fn);
      this.callbacksCount += 1;
      const didRAFChange = LAST_RAF !== requestAnimationFrame && (LAST_RAF = requestAnimationFrame, true);
      if (!this.isScheduled || didRAFChange) {
        requestAnimationFrame(this.tick);
        this.isScheduled = true;
      }
      return id;
    }
    cancel(id) {
      const index2 = id - this.startId;
      if (index2 < 0 || index2 >= this.callbacks.length) {
        return;
      }
      this.callbacks[index2] = null;
      this.callbacksCount -= 1;
    }
  };
  var scheduler = new Scheduler();
  var AnimationFrame = class _AnimationFrame {
    static create() {
      return new _AnimationFrame();
    }
    static request(fn) {
      return scheduler.request(fn);
    }
    static cancel(id) {
      return scheduler.cancel(id);
    }
    currentId = EMPTY2;
    /**
     * Executes `fn` after `delay`, clearing any previously scheduled call.
     */
    request(fn) {
      this.cancel();
      this.currentId = scheduler.request(() => {
        this.currentId = EMPTY2;
        fn();
      });
    }
    cancel = () => {
      if (this.currentId !== EMPTY2) {
        scheduler.cancel(this.currentId);
        this.currentId = EMPTY2;
      }
    };
    disposeEffect = () => {
      return this.cancel;
    };
  };
  function useAnimationFrame() {
    const timeout = useRefWithInit(AnimationFrame.create).current;
    useOnMount(timeout.disposeEffect);
    return timeout;
  }

  // node_modules/@base-ui/react/internals/useTransitionStatus.mjs
  function useTransitionStatus(open, enableIdleState = false, deferEndingState = false) {
    const [transitionStatus, setTransitionStatus] = React11.useState(open && enableIdleState ? "idle" : void 0);
    const [mounted, setMounted] = React11.useState(open);
    if (open && !mounted) {
      setMounted(true);
      setTransitionStatus("starting");
    }
    if (!open && mounted && transitionStatus !== "ending" && !deferEndingState) {
      setTransitionStatus("ending");
    }
    if (!open && !mounted && transitionStatus === "ending") {
      setTransitionStatus(void 0);
    }
    useIsoLayoutEffect(() => {
      if (!open && mounted && transitionStatus !== "ending" && deferEndingState) {
        const frame = AnimationFrame.request(() => {
          setTransitionStatus("ending");
        });
        return () => {
          AnimationFrame.cancel(frame);
        };
      }
      return void 0;
    }, [open, mounted, transitionStatus, deferEndingState]);
    useIsoLayoutEffect(() => {
      if (!open || enableIdleState) {
        return void 0;
      }
      const frame = AnimationFrame.request(() => {
        setTransitionStatus(void 0);
      });
      return () => {
        AnimationFrame.cancel(frame);
      };
    }, [enableIdleState, open]);
    useIsoLayoutEffect(() => {
      if (!open || !enableIdleState) {
        return void 0;
      }
      if (open && mounted && transitionStatus !== "idle") {
        setTransitionStatus("starting");
      }
      const frame = AnimationFrame.request(() => {
        setTransitionStatus("idle");
      });
      return () => {
        AnimationFrame.cancel(frame);
      };
    }, [enableIdleState, open, mounted, transitionStatus]);
    return {
      mounted,
      setMounted,
      transitionStatus
    };
  }

  // node_modules/@base-ui/react/collapsible/root/useCollapsibleRoot.mjs
  function useCollapsibleRoot(parameters) {
    const {
      open: openParam,
      defaultOpen,
      onOpenChange,
      disabled: disabled2
    } = parameters;
    const [open, setOpen] = useControlled({
      controlled: openParam,
      default: defaultOpen,
      name: "Collapsible",
      state: "open"
    });
    const {
      mounted,
      setMounted,
      transitionStatus
    } = useTransitionStatus(open, true, true);
    const defaultPanelId = useBaseUiId();
    const [panelIdState, setPanelIdState] = React12.useState();
    const panelId = panelIdState ?? defaultPanelId;
    const handleTrigger = useStableCallback((event) => {
      const nextOpen = !open;
      const eventDetails = createChangeEventDetails(reason_parts_exports.triggerPress, event.nativeEvent);
      onOpenChange(nextOpen, eventDetails);
      if (eventDetails.isCanceled) {
        return;
      }
      setOpen(nextOpen);
    });
    return React12.useMemo(() => ({
      disabled: disabled2,
      handleTrigger,
      mounted,
      open,
      panelId,
      setMounted,
      setOpen,
      setPanelIdState,
      transitionStatus
    }), [disabled2, handleTrigger, mounted, open, panelId, setMounted, setOpen, setPanelIdState, transitionStatus]);
  }

  // node_modules/@base-ui/react/collapsible/root/CollapsibleRootContext.mjs
  var React13 = __toESM(require_react(), 1);
  var CollapsibleRootContext = /* @__PURE__ */ React13.createContext(void 0);
  if (true) CollapsibleRootContext.displayName = "CollapsibleRootContext";
  function useCollapsibleRootContext() {
    const context = React13.useContext(CollapsibleRootContext);
    if (context === void 0) {
      throw new Error(true ? "Base UI: CollapsibleRootContext is missing. Collapsible parts must be placed within <Collapsible.Root>." : formatErrorMessage_default(15));
    }
    return context;
  }

  // node_modules/@base-ui/react/internals/stateAttributesMapping.mjs
  var TransitionStatusDataAttributes = /* @__PURE__ */ (function(TransitionStatusDataAttributes2) {
    TransitionStatusDataAttributes2["startingStyle"] = "data-starting-style";
    TransitionStatusDataAttributes2["endingStyle"] = "data-ending-style";
    return TransitionStatusDataAttributes2;
  })({});
  var STARTING_HOOK = {
    [TransitionStatusDataAttributes.startingStyle]: ""
  };
  var ENDING_HOOK = {
    [TransitionStatusDataAttributes.endingStyle]: ""
  };
  var transitionStatusMapping = {
    transitionStatus(value) {
      if (value === "starting") {
        return STARTING_HOOK;
      }
      if (value === "ending") {
        return ENDING_HOOK;
      }
      return null;
    }
  };

  // node_modules/@base-ui/react/collapsible/panel/CollapsiblePanelDataAttributes.mjs
  var CollapsiblePanelDataAttributes = (function(CollapsiblePanelDataAttributes2) {
    CollapsiblePanelDataAttributes2["open"] = "data-open";
    CollapsiblePanelDataAttributes2["closed"] = "data-closed";
    CollapsiblePanelDataAttributes2[CollapsiblePanelDataAttributes2["startingStyle"] = TransitionStatusDataAttributes.startingStyle] = "startingStyle";
    CollapsiblePanelDataAttributes2[CollapsiblePanelDataAttributes2["endingStyle"] = TransitionStatusDataAttributes.endingStyle] = "endingStyle";
    return CollapsiblePanelDataAttributes2;
  })({});

  // node_modules/@base-ui/react/collapsible/trigger/CollapsibleTriggerDataAttributes.mjs
  var CollapsibleTriggerDataAttributes = /* @__PURE__ */ (function(CollapsibleTriggerDataAttributes2) {
    CollapsibleTriggerDataAttributes2["panelOpen"] = "data-panel-open";
    return CollapsibleTriggerDataAttributes2;
  })({});

  // node_modules/@base-ui/react/utils/collapsibleOpenStateMapping.mjs
  var PANEL_OPEN_HOOK = {
    [CollapsiblePanelDataAttributes.open]: ""
  };
  var PANEL_CLOSED_HOOK = {
    [CollapsiblePanelDataAttributes.closed]: ""
  };
  var triggerOpenStateMapping = {
    open(value) {
      if (value) {
        return {
          [CollapsibleTriggerDataAttributes.panelOpen]: ""
        };
      }
      return null;
    }
  };
  var collapsibleOpenStateMapping = {
    open(value) {
      if (value) {
        return PANEL_OPEN_HOOK;
      }
      return PANEL_CLOSED_HOOK;
    }
  };

  // node_modules/@base-ui/react/internals/use-button/useButton.mjs
  var React16 = __toESM(require_react(), 1);

  // node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs
  function hasWindow() {
    return typeof window !== "undefined";
  }
  function getNodeName(node) {
    if (isNode(node)) {
      return (node.nodeName || "").toLowerCase();
    }
    return "#document";
  }
  function getWindow(node) {
    var _node$ownerDocument;
    return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
  }
  function getDocumentElement(node) {
    var _ref;
    return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
  }
  function isNode(value) {
    if (!hasWindow()) {
      return false;
    }
    return value instanceof Node || value instanceof getWindow(value).Node;
  }
  function isElement(value) {
    if (!hasWindow()) {
      return false;
    }
    return value instanceof Element || value instanceof getWindow(value).Element;
  }
  function isHTMLElement(value) {
    if (!hasWindow()) {
      return false;
    }
    return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
  }
  function isShadowRoot(value) {
    if (!hasWindow() || typeof ShadowRoot === "undefined") {
      return false;
    }
    return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
  }
  function isOverflowElement(element) {
    const {
      overflow,
      overflowX,
      overflowY,
      display
    } = getComputedStyle2(element);
    return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && display !== "inline" && display !== "contents";
  }
  function isTableElement(element) {
    return /^(table|td|th)$/.test(getNodeName(element));
  }
  function isTopLayer(element) {
    try {
      if (element.matches(":popover-open")) {
        return true;
      }
    } catch (_e) {
    }
    try {
      return element.matches(":modal");
    } catch (_e) {
      return false;
    }
  }
  var willChangeRe = /transform|translate|scale|rotate|perspective|filter/;
  var containRe = /paint|layout|strict|content/;
  var isNotNone = (value) => !!value && value !== "none";
  var isWebKitValue;
  function isContainingBlock(elementOrCss) {
    const css = isElement(elementOrCss) ? getComputedStyle2(elementOrCss) : elementOrCss;
    return isNotNone(css.transform) || isNotNone(css.translate) || isNotNone(css.scale) || isNotNone(css.rotate) || isNotNone(css.perspective) || !isWebKit() && (isNotNone(css.backdropFilter) || isNotNone(css.filter)) || willChangeRe.test(css.willChange || "") || containRe.test(css.contain || "");
  }
  function getContainingBlock(element) {
    let currentNode = getParentNode(element);
    while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
      if (isContainingBlock(currentNode)) {
        return currentNode;
      } else if (isTopLayer(currentNode)) {
        return null;
      }
      currentNode = getParentNode(currentNode);
    }
    return null;
  }
  function isWebKit() {
    if (isWebKitValue == null) {
      isWebKitValue = typeof CSS !== "undefined" && CSS.supports && CSS.supports("-webkit-backdrop-filter", "none");
    }
    return isWebKitValue;
  }
  function isLastTraversableNode(node) {
    return /^(html|body|#document)$/.test(getNodeName(node));
  }
  function getComputedStyle2(element) {
    return getWindow(element).getComputedStyle(element);
  }
  function getNodeScroll(element) {
    if (isElement(element)) {
      return {
        scrollLeft: element.scrollLeft,
        scrollTop: element.scrollTop
      };
    }
    return {
      scrollLeft: element.scrollX,
      scrollTop: element.scrollY
    };
  }
  function getParentNode(node) {
    if (getNodeName(node) === "html") {
      return node;
    }
    const result = (
      // Step into the shadow DOM of the parent of a slotted node.
      node.assignedSlot || // DOM Element detected.
      node.parentNode || // ShadowRoot detected.
      isShadowRoot(node) && node.host || // Fallback.
      getDocumentElement(node)
    );
    return isShadowRoot(result) ? result.host : result;
  }
  function getNearestOverflowAncestor(node) {
    const parentNode = getParentNode(node);
    if (isLastTraversableNode(parentNode)) {
      return node.ownerDocument ? node.ownerDocument.body : node.body;
    }
    if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
      return parentNode;
    }
    return getNearestOverflowAncestor(parentNode);
  }
  function getOverflowAncestors(node, list, traverseIframes) {
    var _node$ownerDocument2;
    if (list === void 0) {
      list = [];
    }
    if (traverseIframes === void 0) {
      traverseIframes = true;
    }
    const scrollableAncestor = getNearestOverflowAncestor(node);
    const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
    const win = getWindow(scrollableAncestor);
    if (isBody) {
      const frameElement = getFrameElement(win);
      return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);
    } else {
      return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
    }
  }
  function getFrameElement(win) {
    return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;
  }

  // node_modules/@base-ui/react/internals/composite/root/CompositeRootContext.mjs
  var React14 = __toESM(require_react(), 1);
  var CompositeRootContext = /* @__PURE__ */ React14.createContext(void 0);
  if (true) CompositeRootContext.displayName = "CompositeRootContext";
  function useCompositeRootContext(optional = false) {
    const context = React14.useContext(CompositeRootContext);
    if (context === void 0 && !optional) {
      throw new Error(true ? "Base UI: CompositeRootContext is missing. Composite parts must be placed within <Composite.Root>." : formatErrorMessage_default(16));
    }
    return context;
  }

  // node_modules/@base-ui/react/utils/useFocusableWhenDisabled.mjs
  var React15 = __toESM(require_react(), 1);
  function useFocusableWhenDisabled(parameters) {
    const {
      focusableWhenDisabled,
      disabled: disabled2,
      composite = false,
      tabIndex: tabIndexProp = 0,
      isNativeButton
    } = parameters;
    const isFocusableComposite = composite && focusableWhenDisabled !== false;
    const isNonFocusableComposite = composite && focusableWhenDisabled === false;
    const props = React15.useMemo(() => {
      const additionalProps = {
        // allow Tabbing away from focusableWhenDisabled elements
        onKeyDown(event) {
          if (disabled2 && focusableWhenDisabled && event.key !== "Tab") {
            event.preventDefault();
          }
        }
      };
      if (!composite) {
        additionalProps.tabIndex = tabIndexProp;
        if (!isNativeButton && disabled2) {
          additionalProps.tabIndex = focusableWhenDisabled ? tabIndexProp : -1;
        }
      }
      if (isNativeButton && (focusableWhenDisabled || isFocusableComposite) || !isNativeButton && disabled2) {
        additionalProps["aria-disabled"] = disabled2;
      }
      if (isNativeButton && (!focusableWhenDisabled || isNonFocusableComposite)) {
        additionalProps.disabled = disabled2;
      }
      return additionalProps;
    }, [composite, disabled2, focusableWhenDisabled, isFocusableComposite, isNonFocusableComposite, isNativeButton, tabIndexProp]);
    return {
      props
    };
  }

  // node_modules/@base-ui/react/internals/use-button/useButton.mjs
  function useButton(parameters = {}) {
    const {
      disabled: disabled2 = false,
      focusableWhenDisabled,
      tabIndex = 0,
      native: isNativeButton = true,
      composite: compositeProp
    } = parameters;
    const elementRef = React16.useRef(null);
    const compositeRootContext = useCompositeRootContext(true);
    const isCompositeItem = compositeProp ?? compositeRootContext !== void 0;
    const {
      props: focusableWhenDisabledProps
    } = useFocusableWhenDisabled({
      focusableWhenDisabled,
      disabled: disabled2,
      composite: isCompositeItem,
      tabIndex,
      isNativeButton
    });
    if (true) {
      React16.useEffect(() => {
        if (!elementRef.current) {
          return;
        }
        const isButtonTag = isButtonElement(elementRef.current);
        if (isNativeButton) {
          if (!isButtonTag) {
            const ownerStackMessage = SafeReact.captureOwnerStack?.() || "";
            const message2 = "A component that acts as a button expected a native <button> because the `nativeButton` prop is true. Rendering a non-<button> removes native button semantics, which can impact forms and accessibility. Use a real <button> in the `render` prop, or set `nativeButton` to `false`.";
            error(`${message2}${ownerStackMessage}`);
          }
        } else if (isButtonTag) {
          const ownerStackMessage = SafeReact.captureOwnerStack?.() || "";
          const message2 = "A component that acts as a button expected a non-<button> because the `nativeButton` prop is false. Rendering a <button> keeps native behavior while Base UI applies non-native attributes and handlers, which can add unintended extra attributes (such as `role` or `aria-disabled`). Use a non-<button> in the `render` prop, or set `nativeButton` to `true`.";
          error(`${message2}${ownerStackMessage}`);
        }
      }, [isNativeButton]);
    }
    const updateDisabled = React16.useCallback(() => {
      const element = elementRef.current;
      if (!isButtonElement(element)) {
        return;
      }
      if (isCompositeItem && disabled2 && focusableWhenDisabledProps.disabled === void 0 && element.disabled) {
        element.disabled = false;
      }
    }, [disabled2, focusableWhenDisabledProps.disabled, isCompositeItem]);
    useIsoLayoutEffect(updateDisabled, [updateDisabled]);
    const getButtonProps = React16.useCallback((externalProps = {}) => {
      const {
        onClick: externalOnClick,
        onMouseDown: externalOnMouseDown,
        onKeyUp: externalOnKeyUp,
        onKeyDown: externalOnKeyDown,
        onPointerDown: externalOnPointerDown,
        ...otherExternalProps
      } = externalProps;
      return mergeProps({
        onClick(event) {
          if (disabled2) {
            event.preventDefault();
            return;
          }
          externalOnClick?.(event);
        },
        onMouseDown(event) {
          if (!disabled2) {
            externalOnMouseDown?.(event);
          }
        },
        onKeyDown(event) {
          if (disabled2) {
            return;
          }
          makeEventPreventable(event);
          externalOnKeyDown?.(event);
          if (event.baseUIHandlerPrevented) {
            return;
          }
          const isCurrentTarget = event.target === event.currentTarget;
          const currentTarget = event.currentTarget;
          const isButton2 = isButtonElement(currentTarget);
          const isLink = !isNativeButton && isValidLinkElement(currentTarget);
          const shouldClick = isCurrentTarget && (isNativeButton ? isButton2 : !isLink);
          const isEnterKey = event.key === "Enter";
          const isSpaceKey = event.key === " ";
          const role = currentTarget.getAttribute("role");
          const isTextNavigationRole = role?.startsWith("menuitem") || role === "option" || role === "gridcell";
          if (isCurrentTarget && isCompositeItem && isSpaceKey) {
            if (event.defaultPrevented && isTextNavigationRole) {
              return;
            }
            event.preventDefault();
            if (isLink || isNativeButton && isButton2) {
              currentTarget.click();
              event.preventBaseUIHandler();
            } else if (shouldClick) {
              externalOnClick?.(event);
              event.preventBaseUIHandler();
            }
            return;
          }
          if (shouldClick) {
            if (!isNativeButton && (isSpaceKey || isEnterKey)) {
              event.preventDefault();
            }
            if (!isNativeButton && isEnterKey) {
              externalOnClick?.(event);
            }
          }
        },
        onKeyUp(event) {
          if (disabled2) {
            return;
          }
          makeEventPreventable(event);
          externalOnKeyUp?.(event);
          if (event.target === event.currentTarget && isNativeButton && isCompositeItem && isButtonElement(event.currentTarget) && event.key === " ") {
            event.preventDefault();
            return;
          }
          if (event.baseUIHandlerPrevented) {
            return;
          }
          if (event.target === event.currentTarget && !isNativeButton && !isCompositeItem && event.key === " ") {
            externalOnClick?.(event);
          }
        },
        onPointerDown(event) {
          if (disabled2) {
            event.preventDefault();
            return;
          }
          externalOnPointerDown?.(event);
        }
      }, isNativeButton ? {
        type: "button"
      } : {
        role: "button"
      }, focusableWhenDisabledProps, otherExternalProps);
    }, [disabled2, focusableWhenDisabledProps, isCompositeItem, isNativeButton]);
    const buttonRef = useStableCallback((element) => {
      elementRef.current = element;
      updateDisabled();
    });
    return {
      getButtonProps,
      buttonRef
    };
  }
  function isButtonElement(elem) {
    return isHTMLElement(elem) && elem.tagName === "BUTTON";
  }
  function isValidLinkElement(elem) {
    return Boolean(elem?.tagName === "A" && elem?.href);
  }

  // node_modules/@base-ui/react/collapsible/panel/useCollapsiblePanel.mjs
  var React18 = __toESM(require_react(), 1);

  // node_modules/@base-ui/utils/addEventListener.mjs
  function addEventListener(target, type, listener, options) {
    target.addEventListener(type, listener, options);
    return () => {
      target.removeEventListener(type, listener, options);
    };
  }

  // node_modules/@base-ui/utils/useValueAsRef.mjs
  function useValueAsRef(value) {
    const latest = useRefWithInit(createLatestRef, value).current;
    latest.next = value;
    useIsoLayoutEffect(latest.effect);
    return latest;
  }
  function createLatestRef(value) {
    const latest = {
      current: value,
      next: value,
      effect: () => {
        latest.current = latest.next;
      }
    };
    return latest;
  }

  // node_modules/@base-ui/utils/owner.mjs
  function ownerDocument(node) {
    return node?.ownerDocument || document;
  }

  // node_modules/@base-ui/react/internals/useOpenChangeComplete.mjs
  var React17 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/internals/useAnimationsFinished.mjs
  var ReactDOM = __toESM(require_react_dom(), 1);

  // node_modules/@base-ui/react/utils/resolveRef.mjs
  function resolveRef(maybeRef) {
    if (maybeRef == null) {
      return maybeRef;
    }
    return "current" in maybeRef ? maybeRef.current : maybeRef;
  }

  // node_modules/@base-ui/react/internals/useAnimationsFinished.mjs
  function useAnimationsFinished(elementOrRef, waitForStartingStyleRemoved = false, treatAbortedAsFinished = true) {
    const frame = useAnimationFrame();
    return useStableCallback((fnToExecute, signal = null) => {
      frame.cancel();
      const element = resolveRef(elementOrRef);
      if (element == null) {
        return;
      }
      const resolvedElement = element;
      const done = () => {
        ReactDOM.flushSync(fnToExecute);
      };
      if (typeof resolvedElement.getAnimations !== "function" || globalThis.BASE_UI_ANIMATIONS_DISABLED) {
        fnToExecute();
        return;
      }
      function exec() {
        Promise.all(resolvedElement.getAnimations().map((animation) => animation.finished)).then(() => {
          if (!signal?.aborted) {
            done();
          }
        }).catch(() => {
          if (treatAbortedAsFinished) {
            if (!signal?.aborted) {
              done();
            }
            return;
          }
          const currentAnimations = resolvedElement.getAnimations();
          if (!signal?.aborted && currentAnimations.length > 0 && currentAnimations.some((animation) => animation.pending || animation.playState !== "finished")) {
            exec();
          }
        });
      }
      if (waitForStartingStyleRemoved) {
        const startingStyleAttribute = TransitionStatusDataAttributes.startingStyle;
        if (!resolvedElement.hasAttribute(startingStyleAttribute)) {
          frame.request(exec);
          return;
        }
        const attributeObserver = new MutationObserver(() => {
          if (!resolvedElement.hasAttribute(startingStyleAttribute)) {
            attributeObserver.disconnect();
            exec();
          }
        });
        attributeObserver.observe(resolvedElement, {
          attributes: true,
          attributeFilter: [startingStyleAttribute]
        });
        signal?.addEventListener("abort", () => attributeObserver.disconnect(), {
          once: true
        });
        return;
      }
      frame.request(exec);
    });
  }

  // node_modules/@base-ui/react/internals/useOpenChangeComplete.mjs
  function useOpenChangeComplete(parameters) {
    const {
      enabled = true,
      open,
      ref,
      onComplete: onCompleteParam
    } = parameters;
    const onComplete = useStableCallback(onCompleteParam);
    const runOnceAnimationsFinish = useAnimationsFinished(ref, open, false);
    React17.useEffect(() => {
      if (!enabled) {
        return void 0;
      }
      const abortController = new AbortController();
      runOnceAnimationsFinish(onComplete, abortController.signal);
      return () => {
        abortController.abort();
      };
    }, [enabled, open, onComplete, runOnceAnimationsFinish]);
  }

  // node_modules/@base-ui/react/collapsible/panel/useCollapsiblePanel.mjs
  var EMPTY_DIMENSIONS = {
    height: void 0,
    width: void 0
  };
  function useCollapsiblePanel(parameters) {
    const {
      externalRef,
      hiddenUntilFound,
      id: idParam,
      keepMounted,
      mounted,
      onOpenChange,
      open,
      setMounted,
      setOpen,
      transitionStatus
    } = parameters;
    const panelRef = React18.useRef(null);
    const animationTypeRef = React18.useRef(null);
    const [dimensions, setDimensionsUnwrapped] = React18.useState(EMPTY_DIMENSIONS);
    const lastMeasuredDimensionsRef = React18.useRef(EMPTY_DIMENSIONS);
    const shouldSkipNextOpenRef = React18.useRef(false);
    const shouldPreventMountAnimationRef = React18.useRef(open);
    const shouldPreventActivityResumeAnimationRef = React18.useRef(false);
    const [forcePanelIdle, setForcePanelIdle] = React18.useState(false);
    const pendingTemporaryStyleRestoreRef = React18.useRef(null);
    const mergedPanelRef = useMergedRefs(externalRef, panelRef);
    const latestStateRef = useValueAsRef({
      mounted,
      open
    });
    const runOnceCloseAnimationsFinish = useAnimationsFinished(panelRef, false, false);
    const hidden = !open && !mounted;
    const panelTransitionStatus = forcePanelIdle ? "idle" : transitionStatus;
    const shouldPreventOpenAnimation = open && // These 2 refs are safe to read in render, they are only written from committed
    // layout/effect paths and gate one-shot motion suppression for the next open
    // lifecycle. They intentionally expose the last committed motion snapshot.
    (shouldPreventMountAnimationRef.current || shouldPreventActivityResumeAnimationRef.current);
    const renderedDimensions = !open && mounted && // These 2 refs are also safe to read in render, both hold the last committed
    // animation mode and measurement. This fallback only restores a previously
    // measured pixel size after the live dimensions state has been reset back to `auto`.
    animationTypeRef.current === "css-animation" && dimensions.height === void 0 && dimensions.width === void 0 ? lastMeasuredDimensionsRef.current : dimensions;
    const shouldPersistHiddenTransitionStyles = hiddenUntilFound && hidden && animationTypeRef.current !== "css-animation";
    const setDimensions = useStableCallback((nextDimensions, shouldCacheMeasurement = true) => {
      if (shouldCacheMeasurement) {
        lastMeasuredDimensionsRef.current = nextDimensions;
      }
      setDimensionsUnwrapped(nextDimensions);
    });
    const restorePendingTemporaryStyle = useStableCallback(() => {
      pendingTemporaryStyleRestoreRef.current?.();
      pendingTemporaryStyleRestoreRef.current = null;
    });
    const setPendingTemporaryStyleRestore = useStableCallback((restore) => {
      restorePendingTemporaryStyle();
      pendingTemporaryStyleRestoreRef.current = () => {
        pendingTemporaryStyleRestoreRef.current = null;
        restore();
      };
    });
    const markActivityResumeAnimationSuppressed = useStableCallback(() => {
      if (open && mounted && animationTypeRef.current === "css-animation") {
        shouldPreventActivityResumeAnimationRef.current = true;
      }
    });
    useIsoLayoutEffect(() => {
      if (!forcePanelIdle || transitionStatus === "starting") {
        return;
      }
      setForcePanelIdle(false);
    }, [forcePanelIdle, transitionStatus]);
    React18.useEffect(() => {
      return () => {
        markActivityResumeAnimationSuppressed();
        restorePendingTemporaryStyle();
      };
    }, [markActivityResumeAnimationSuppressed, restorePendingTemporaryStyle]);
    useIsoLayoutEffect(() => {
      const panel = panelRef.current;
      if (!panel) {
        return void 0;
      }
      if (!open && pendingTemporaryStyleRestoreRef.current) {
        restorePendingTemporaryStyle();
      }
      const animationType = getAnimationType(panel, shouldPreventOpenAnimation);
      animationTypeRef.current = animationType;
      if (open && transitionStatus === "idle" && shouldPreventMountAnimationRef.current && animationType === "css-animation") {
        lastMeasuredDimensionsRef.current = getDimensions(panel);
        return void 0;
      }
      if (open && transitionStatus === "starting") {
        const skipNextOpen = shouldSkipNextOpenRef.current;
        shouldSkipNextOpenRef.current = false;
        if (animationType === "none") {
          setDimensions(getDimensions(panel));
          setForcePanelIdle(true);
          return void 0;
        }
        if (animationType === "css-transition") {
          const restoreLayoutStyles = resetLayoutStyles(panel);
          setDimensions(getDimensions(panel));
          if (!skipNextOpen) {
            return restoreLayoutStyles;
          }
          const restoreTransitionDuration = setTemporaryStyle(panel, "transition-duration", "0s");
          setPendingTemporaryStyleRestore(restoreTransitionDuration);
          setForcePanelIdle(true);
          return restoreLayoutStyles;
        }
        if (animationType === "css-animation") {
          setDimensions(getDimensions(panel));
          if (!skipNextOpen) {
            const restoreAnimationName2 = setTemporaryStyle(panel, "animation-name", "none");
            restoreAnimationName2();
            return void 0;
          }
          const restoreAnimationName = setTemporaryStyle(panel, "animation-name", "none");
          const restoreAnimationDuration = setTemporaryStyle(panel, "animation-duration", "0s");
          restoreAnimationName();
          setPendingTemporaryStyleRestore(restoreAnimationDuration);
          setForcePanelIdle(true);
          return void 0;
        }
      }
      if (!open && mounted && (transitionStatus === "idle" || transitionStatus === "starting")) {
        shouldPreventMountAnimationRef.current = false;
        shouldPreventActivityResumeAnimationRef.current = false;
        if (animationType === "none") {
          setDimensions(EMPTY_DIMENSIONS, false);
          setMounted(false);
          return void 0;
        }
        setDimensions(getDimensions(panel));
        return void 0;
      }
      if (transitionStatus !== "ending") {
        return void 0;
      }
      if (animationType === "none") {
        setMounted(false);
        return void 0;
      }
      const nextDimensions = getDimensions(panel);
      const hasMeasuredSize = (nextDimensions.height ?? 0) > 0 || (nextDimensions.width ?? 0) > 0;
      if (!hasMeasuredSize) {
        setMounted(false);
        return void 0;
      }
      setDimensions(nextDimensions);
      if (animationType === "css-animation") {
        const restoreAnimationName = setTemporaryStyle(panel, "animation-name", "none");
        restoreAnimationName();
      }
      return void 0;
    }, [mounted, open, restorePendingTemporaryStyle, setDimensions, setMounted, setPendingTemporaryStyleRestore, shouldPreventOpenAnimation, transitionStatus]);
    useOpenChangeComplete({
      enabled: open && mounted && panelTransitionStatus === "idle",
      open: true,
      ref: panelRef,
      onComplete() {
        if (!open) {
          return;
        }
        setDimensions(EMPTY_DIMENSIONS, false);
      }
    });
    React18.useEffect(() => {
      if (open || !mounted || panelTransitionStatus !== "ending") {
        return void 0;
      }
      const panel = panelRef.current;
      if (!panel) {
        return void 0;
      }
      const abortController = new AbortController();
      let endingStyleFrame = -1;
      function handleComplete() {
        if (latestStateRef.current.open) {
          return;
        }
        setMounted(false);
        setDimensions(EMPTY_DIMENSIONS, false);
      }
      endingStyleFrame = AnimationFrame.request(() => {
        if (!abortController.signal.aborted) {
          runOnceCloseAnimationsFinish(handleComplete, abortController.signal);
        }
      });
      return () => {
        AnimationFrame.cancel(endingStyleFrame);
        abortController.abort();
      };
    }, [latestStateRef, mounted, open, panelTransitionStatus, runOnceCloseAnimationsFinish, setDimensions, setMounted]);
    useIsoLayoutEffect(() => {
      const panel = panelRef.current;
      if (!panel || !hiddenUntilFound || !hidden) {
        return;
      }
      panel.setAttribute("hidden", "until-found");
    }, [hidden, hiddenUntilFound]);
    React18.useEffect(function registerBeforeMatchListener() {
      const panel = panelRef.current;
      if (!panel) {
        return void 0;
      }
      function handleBeforeMatch(event) {
        const eventDetails = createChangeEventDetails(reason_parts_exports.none, event);
        onOpenChange(true, eventDetails);
        if (eventDetails.isCanceled) {
          return;
        }
        shouldSkipNextOpenRef.current = true;
        setOpen(true);
      }
      return addEventListener(panel, "beforematch", handleBeforeMatch);
    }, [onOpenChange, setOpen]);
    const shouldRender = keepMounted || hiddenUntilFound || mounted || open;
    return {
      height: renderedDimensions.height,
      props: {
        ...shouldPersistHiddenTransitionStyles ? {
          [CollapsiblePanelDataAttributes.startingStyle]: ""
        } : void 0,
        hidden,
        id: idParam
      },
      ref: mergedPanelRef,
      shouldPreventOpenAnimation,
      shouldRender,
      transitionStatus: panelTransitionStatus,
      width: renderedDimensions.width
    };
  }
  function getDimensions(element) {
    return {
      height: element.scrollHeight,
      width: element.scrollWidth
    };
  }
  function getAnimationType(element, hasSuppressedMountAnimation = false) {
    const panelStyles = getWindow(element).getComputedStyle(element);
    const hasAnimation = (panelStyles.animationName.split(",").map((name2) => name2.trim()).some((name2) => name2 !== "" && name2 !== "none") || hasSuppressedMountAnimation) && hasNonZeroDuration(panelStyles.animationDuration);
    const hasTransition = hasNonZeroDuration(panelStyles.transitionDuration);
    if (hasAnimation && hasTransition) {
      if (true) {
        warn("CSS transitions and CSS animations both detected on Collapsible or Accordion panel.", "Only one of either animation type should be used.");
      }
      return "css-transition";
    }
    if (hasTransition) {
      return "css-transition";
    }
    if (hasAnimation) {
      return "css-animation";
    }
    return "none";
  }
  function hasNonZeroDuration(value) {
    return value.split(",").map((part) => part.trim()).some((part) => part !== "" && Number.parseFloat(part) > 0);
  }
  function setTemporaryStyle(element, property, value) {
    const previousValue = element.style.getPropertyValue(property);
    const previousPriority = element.style.getPropertyPriority(property);
    element.style.setProperty(property, value);
    return () => {
      if (previousValue === "") {
        element.style.removeProperty(property);
        return;
      }
      element.style.setProperty(property, previousValue, previousPriority);
    };
  }
  function resetLayoutStyles(element) {
    const originalLayoutStyles = {
      "justify-content": element.style.justifyContent,
      "align-items": element.style.alignItems,
      "align-content": element.style.alignContent,
      "justify-items": element.style.justifyItems
    };
    Object.keys(originalLayoutStyles).forEach((key) => {
      element.style.setProperty(key, "initial", "important");
    });
    function restoreLayoutStyles() {
      Object.entries(originalLayoutStyles).forEach(([key, value]) => {
        if (value === "") {
          element.style.removeProperty(key);
          return;
        }
        element.style.setProperty(key, value);
      });
    }
    const frame = AnimationFrame.request(restoreLayoutStyles);
    return () => {
      AnimationFrame.cancel(frame);
      restoreLayoutStyles();
    };
  }

  // node_modules/@base-ui/utils/useOnFirstRender.mjs
  var React19 = __toESM(require_react(), 1);
  function useOnFirstRender(fn) {
    const ref = React19.useRef(true);
    if (ref.current) {
      ref.current = false;
      fn();
    }
  }

  // node_modules/@base-ui/utils/platform/parts.mjs
  var parts_exports = {};
  __export(parts_exports, {
    engine: () => engine_exports,
    env: () => env_exports,
    os: () => os_exports,
    screenReader: () => screen_reader_exports
  });

  // node_modules/@base-ui/utils/platform/os.mjs
  var os_exports = {};
  __export(os_exports, {
    android: () => android,
    apple: () => apple,
    ios: () => ios,
    linux: () => linux,
    mac: () => mac,
    windows: () => windows
  });

  // node_modules/@base-ui/utils/platform/shared.mjs
  function readRawData() {
    if (typeof navigator === "undefined") {
      return {
        userAgent: "",
        platform: "",
        maxTouchPoints: 0
      };
    }
    if (true) {
      const uaData = navigator.userAgentData;
      if (uaData && Array.isArray(uaData.brands)) {
        return {
          userAgent: uaData.brands.map(({
            brand,
            version: version2
          }) => `${brand}/${version2}`).join(" "),
          platform: uaData.platform ?? navigator.platform ?? "",
          maxTouchPoints: navigator.maxTouchPoints ?? 0
        };
      }
    }
    return {
      userAgent: navigator.userAgent,
      platform: navigator.platform ?? "",
      maxTouchPoints: navigator.maxTouchPoints ?? 0
    };
  }
  var {
    userAgent,
    platform,
    maxTouchPoints
  } = readRawData();
  var lowerUserAgent = userAgent.toLowerCase();
  var lowerPlatform = platform.toLowerCase();

  // node_modules/@base-ui/utils/platform/os.mjs
  var ios = /^i(os$|p)/.test(lowerPlatform) || lowerPlatform === "macintel" && maxTouchPoints > 1;
  var ANDROID_STRING = "android";
  var android = lowerPlatform === ANDROID_STRING || lowerUserAgent.includes(ANDROID_STRING);
  var mac = !ios && lowerPlatform.startsWith("mac");
  var windows = lowerPlatform.startsWith("win");
  var linux = !android && /^(linux|chrome os)/.test(lowerPlatform);
  var apple = mac || ios;

  // node_modules/@base-ui/utils/platform/engine.mjs
  var engine_exports = {};
  __export(engine_exports, {
    blink: () => blink,
    gecko: () => gecko,
    webkit: () => webkit
  });
  var webkit = typeof CSS !== "undefined" && !!CSS.supports?.("-webkit-backdrop-filter:none");
  var gecko = !webkit && lowerUserAgent.includes("firefox");
  var blink = !webkit && lowerUserAgent.includes("chrom");

  // node_modules/@base-ui/utils/platform/screen-reader.mjs
  var screen_reader_exports = {};
  __export(screen_reader_exports, {
    voiceOver: () => voiceOver
  });
  var voiceOver = apple;

  // node_modules/@base-ui/utils/platform/env.mjs
  var env_exports = {};
  __export(env_exports, {
    jsdom: () => jsdom
  });
  var jsdom = /jsdom|happydom/.test(lowerUserAgent);

  // node_modules/@base-ui/utils/useTimeout.mjs
  var EMPTY3 = 0;
  var Timeout = class _Timeout {
    static create() {
      return new _Timeout();
    }
    currentId = EMPTY3;
    /**
     * Executes `fn` after `delay`, clearing any previously scheduled call.
     */
    start(delay, fn) {
      this.clear();
      this.currentId = setTimeout(() => {
        this.currentId = EMPTY3;
        fn();
      }, delay);
    }
    isStarted() {
      return this.currentId !== EMPTY3;
    }
    clear = () => {
      if (this.currentId !== EMPTY3) {
        clearTimeout(this.currentId);
        this.currentId = EMPTY3;
      }
    };
    disposeEffect = () => {
      return this.clear;
    };
  };
  function useTimeout() {
    const timeout = useRefWithInit(Timeout.create).current;
    useOnMount(timeout.disposeEffect);
    return timeout;
  }

  // node_modules/@base-ui/react/floating-ui-react/components/FloatingDelayGroup.mjs
  var React20 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/floating-ui-react/utils/event.mjs
  function isReactEvent(event) {
    return "nativeEvent" in event;
  }
  function isMouseLikePointerType(pointerType, strict) {
    const values = ["mouse", "pen"];
    if (!strict) {
      values.push("", void 0);
    }
    return values.includes(pointerType);
  }
  function isClickLikeEvent(event) {
    const type = event.type;
    return type === "click" || type === "mousedown" || type === "keydown" || type === "keyup";
  }

  // node_modules/@base-ui/react/floating-ui-react/utils/constants.mjs
  var FOCUSABLE_ATTRIBUTE = "data-base-ui-focusable";
  var TYPEABLE_SELECTOR = "input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])";

  // node_modules/@base-ui/react/internals/shadowDom.mjs
  function activeElement(doc) {
    let element = doc.activeElement;
    while (element?.shadowRoot?.activeElement != null) {
      element = element.shadowRoot.activeElement;
    }
    return element;
  }
  function contains(parent, child) {
    if (!parent || !child) {
      return false;
    }
    const rootNode = child.getRootNode?.();
    if (parent.contains(child)) {
      return true;
    }
    if (rootNode && isShadowRoot(rootNode)) {
      let next = child;
      while (next) {
        if (parent === next) {
          return true;
        }
        next = next.parentNode || next.host;
      }
    }
    return false;
  }
  function getTarget(event) {
    if ("composedPath" in event) {
      return event.composedPath()[0];
    }
    return event.target;
  }

  // node_modules/@base-ui/react/floating-ui-react/utils/element.mjs
  function isTargetInsideEnabledTrigger(target, triggerElements) {
    if (!isElement(target)) {
      return false;
    }
    const targetElement = target;
    if (triggerElements.hasElement(targetElement)) {
      return !targetElement.hasAttribute("data-trigger-disabled");
    }
    for (const [, trigger] of triggerElements.entries()) {
      if (contains(trigger, targetElement)) {
        return !trigger.hasAttribute("data-trigger-disabled");
      }
    }
    return false;
  }
  function isEventTargetWithin(event, node) {
    if (node == null) {
      return false;
    }
    if ("composedPath" in event) {
      return event.composedPath().includes(node);
    }
    const eventAgain = event;
    return eventAgain.target != null && node.contains(eventAgain.target);
  }
  function isRootElement(element) {
    return element.matches("html,body");
  }
  function isTypeableElement(element) {
    return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);
  }
  function isInteractiveElement(element) {
    return element?.closest(`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${TYPEABLE_SELECTOR}`) != null;
  }
  function matchesFocusVisible(element) {
    if (!element || parts_exports.env.jsdom) {
      return true;
    }
    try {
      return element.matches(":focus-visible");
    } catch (_e) {
      return true;
    }
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useHoverShared.mjs
  function resolveValue(value, pointerType) {
    if (pointerType != null && !isMouseLikePointerType(pointerType)) {
      return 0;
    }
    if (typeof value === "function") {
      return value();
    }
    return value;
  }
  function getDelay(value, prop, pointerType) {
    const result = resolveValue(value, pointerType);
    if (typeof result === "number") {
      return result;
    }
    return result?.[prop];
  }
  function getRestMs(value) {
    if (typeof value === "function") {
      return value();
    }
    return value;
  }
  function isClickLikeOpenEvent(openEventType, interactedInside) {
    return interactedInside || openEventType === "click" || openEventType === "mousedown";
  }
  function isHoverOpenEvent(openEventType) {
    return openEventType?.includes("mouse") && openEventType !== "mousedown";
  }

  // node_modules/@base-ui/react/floating-ui-react/components/FloatingDelayGroup.mjs
  var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
  var FloatingDelayGroupContext = /* @__PURE__ */ React20.createContext({
    hasProvider: false,
    timeoutMs: 0,
    delayRef: {
      current: 0
    },
    initialDelayRef: {
      current: 0
    },
    timeout: new Timeout(),
    currentIdRef: {
      current: null
    },
    currentContextRef: {
      current: null
    }
  });
  if (true) FloatingDelayGroupContext.displayName = "FloatingDelayGroupContext";
  function resetDelayRef(delayRef, initialDelayRef) {
    delayRef.current = initialDelayRef.current;
  }
  function FloatingDelayGroup(props) {
    const {
      children,
      delay,
      timeoutMs = 0
    } = props;
    const delayRef = React20.useRef(delay);
    const initialDelayRef = React20.useRef(delay);
    const currentIdRef = React20.useRef(null);
    const currentContextRef = React20.useRef(null);
    const timeout = useTimeout();
    useIsoLayoutEffect(() => {
      initialDelayRef.current = delay;
      if (!currentIdRef.current) {
        delayRef.current = delay;
        return;
      }
      delayRef.current = {
        open: getDelay(delayRef.current, "open"),
        close: getDelay(delay, "close")
      };
    }, [delay, currentIdRef, delayRef, initialDelayRef]);
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FloatingDelayGroupContext.Provider, {
      value: React20.useMemo(() => ({
        hasProvider: true,
        delayRef,
        initialDelayRef,
        currentIdRef,
        timeoutMs,
        currentContextRef,
        timeout
      }), [timeoutMs, timeout]),
      children
    });
  }
  function useDelayGroup(context, options = {
    open: false
  }) {
    const {
      open
    } = options;
    const store2 = "rootStore" in context ? context.rootStore : context;
    const floatingId = store2.useState("floatingId");
    const groupContext = React20.useContext(FloatingDelayGroupContext);
    const {
      currentIdRef,
      delayRef,
      timeoutMs,
      initialDelayRef,
      currentContextRef,
      hasProvider,
      timeout
    } = groupContext;
    const [isInstantPhase, setIsInstantPhase] = React20.useState(false);
    const openRef = React20.useRef(open);
    const isUnmountedRef = React20.useRef(false);
    useIsoLayoutEffect(() => {
      openRef.current = open;
    }, [open]);
    useIsoLayoutEffect(() => {
      return () => {
        isUnmountedRef.current = true;
      };
    }, []);
    useIsoLayoutEffect(() => {
      function unset() {
        if (!isUnmountedRef.current) {
          setIsInstantPhase(false);
        }
        currentContextRef.current?.setIsInstantPhase(false);
        currentIdRef.current = null;
        currentContextRef.current = null;
        delayRef.current = initialDelayRef.current;
        timeout.clear();
      }
      if (!currentIdRef.current) {
        return void 0;
      }
      if (!open && currentIdRef.current === floatingId) {
        setIsInstantPhase(false);
        if (timeoutMs) {
          const closingId = floatingId;
          timeout.start(timeoutMs, () => {
            if (store2.select("open") || currentIdRef.current && currentIdRef.current !== closingId) {
              return;
            }
            unset();
          });
          return () => {
            if (openRef.current || currentIdRef.current !== closingId) {
              timeout.clear();
            }
          };
        }
        unset();
      }
      return void 0;
    }, [open, floatingId, currentIdRef, delayRef, timeoutMs, initialDelayRef, currentContextRef, timeout, store2]);
    useIsoLayoutEffect(() => {
      if (!open) {
        return;
      }
      const prevContext = currentContextRef.current;
      const prevId = currentIdRef.current;
      timeout.clear();
      currentContextRef.current = {
        onOpenChange: store2.setOpen,
        setIsInstantPhase
      };
      currentIdRef.current = floatingId;
      delayRef.current = {
        open: 0,
        close: getDelay(initialDelayRef.current, "close")
      };
      if (prevId !== null && prevId !== floatingId) {
        setIsInstantPhase(true);
        prevContext?.setIsInstantPhase(true);
        prevContext?.onOpenChange(false, createChangeEventDetails(reason_parts_exports.none));
      } else {
        setIsInstantPhase(false);
        prevContext?.setIsInstantPhase(false);
      }
    }, [open, floatingId, store2, currentIdRef, delayRef, initialDelayRef, currentContextRef, timeout]);
    useIsoLayoutEffect(() => {
      return () => {
        if (currentIdRef.current === floatingId) {
          currentContextRef.current = null;
          if (!openRef.current) {
            return;
          }
          currentIdRef.current = null;
          resetDelayRef(delayRef, initialDelayRef);
          timeout.clear();
        }
      };
    }, [currentContextRef, currentIdRef, delayRef, floatingId, initialDelayRef, timeout]);
    return React20.useMemo(() => ({
      hasProvider,
      delayRef,
      isInstantPhase
    }), [hasProvider, delayRef, isInstantPhase]);
  }

  // node_modules/@base-ui/utils/mergeCleanups.mjs
  function mergeCleanups(...cleanups) {
    return () => {
      for (let i2 = 0; i2 < cleanups.length; i2 += 1) {
        const cleanup = cleanups[i2];
        if (cleanup) {
          cleanup();
        }
      }
    };
  }

  // node_modules/@base-ui/react/utils/FocusGuard.mjs
  var React21 = __toESM(require_react(), 1);

  // node_modules/@base-ui/utils/visuallyHidden.mjs
  var visuallyHiddenBase = {
    clipPath: "inset(50%)",
    overflow: "hidden",
    whiteSpace: "nowrap",
    border: 0,
    padding: 0,
    width: 1,
    height: 1,
    margin: -1
  };
  var visuallyHidden = {
    ...visuallyHiddenBase,
    position: "fixed",
    top: 0,
    left: 0
  };
  var visuallyHiddenInput = {
    ...visuallyHiddenBase,
    position: "absolute"
  };

  // node_modules/@base-ui/react/utils/FocusGuard.mjs
  var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
  var FocusGuard = /* @__PURE__ */ React21.forwardRef(function FocusGuard2(props, ref) {
    const [role, setRole] = React21.useState();
    useIsoLayoutEffect(() => {
      if (parts_exports.screenReader.voiceOver && parts_exports.engine.webkit) {
        setRole("button");
      }
    }, []);
    const restProps = {
      tabIndex: 0,
      // Role is only for VoiceOver
      role
    };
    return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", {
      ...props,
      ref,
      style: visuallyHidden,
      "aria-hidden": role ? void 0 : true,
      ...restProps,
      "data-base-ui-focus-guard": ""
    });
  });
  if (true) FocusGuard.displayName = "FocusGuard";

  // node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs
  var sides = ["top", "right", "bottom", "left"];
  var min = Math.min;
  var max = Math.max;
  var round = Math.round;
  var floor = Math.floor;
  var createCoords = (v2) => ({
    x: v2,
    y: v2
  });
  var oppositeSideMap = {
    left: "right",
    right: "left",
    bottom: "top",
    top: "bottom"
  };
  function clamp(start2, value, end) {
    return max(start2, min(value, end));
  }
  function evaluate(value, param) {
    return typeof value === "function" ? value(param) : value;
  }
  function getSide(placement) {
    return placement.split("-")[0];
  }
  function getAlignment(placement) {
    return placement.split("-")[1];
  }
  function getOppositeAxis(axis) {
    return axis === "x" ? "y" : "x";
  }
  function getAxisLength(axis) {
    return axis === "y" ? "height" : "width";
  }
  function getSideAxis(placement) {
    const firstChar = placement[0];
    return firstChar === "t" || firstChar === "b" ? "y" : "x";
  }
  function getAlignmentAxis(placement) {
    return getOppositeAxis(getSideAxis(placement));
  }
  function getAlignmentSides(placement, rects, rtl) {
    if (rtl === void 0) {
      rtl = false;
    }
    const alignment = getAlignment(placement);
    const alignmentAxis = getAlignmentAxis(placement);
    const length = getAxisLength(alignmentAxis);
    let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top";
    if (rects.reference[length] > rects.floating[length]) {
      mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
    }
    return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
  }
  function getExpandedPlacements(placement) {
    const oppositePlacement = getOppositePlacement(placement);
    return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
  }
  function getOppositeAlignmentPlacement(placement) {
    return placement.includes("start") ? placement.replace("start", "end") : placement.replace("end", "start");
  }
  var lrPlacement = ["left", "right"];
  var rlPlacement = ["right", "left"];
  var tbPlacement = ["top", "bottom"];
  var btPlacement = ["bottom", "top"];
  function getSideList(side, isStart, rtl) {
    switch (side) {
      case "top":
      case "bottom":
        if (rtl) return isStart ? rlPlacement : lrPlacement;
        return isStart ? lrPlacement : rlPlacement;
      case "left":
      case "right":
        return isStart ? tbPlacement : btPlacement;
      default:
        return [];
    }
  }
  function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
    const alignment = getAlignment(placement);
    let list = getSideList(getSide(placement), direction === "start", rtl);
    if (alignment) {
      list = list.map((side) => side + "-" + alignment);
      if (flipAlignment) {
        list = list.concat(list.map(getOppositeAlignmentPlacement));
      }
    }
    return list;
  }
  function getOppositePlacement(placement) {
    const side = getSide(placement);
    return oppositeSideMap[side] + placement.slice(side.length);
  }
  function expandPaddingObject(padding) {
    return {
      top: 0,
      right: 0,
      bottom: 0,
      left: 0,
      ...padding
    };
  }
  function getPaddingObject(padding) {
    return typeof padding !== "number" ? expandPaddingObject(padding) : {
      top: padding,
      right: padding,
      bottom: padding,
      left: padding
    };
  }
  function rectToClientRect(rect) {
    const {
      x: x2,
      y: y2,
      width,
      height
    } = rect;
    return {
      width,
      height,
      top: y2,
      left: x2,
      right: x2 + width,
      bottom: y2 + height,
      x: x2,
      y: y2
    };
  }

  // node_modules/@base-ui/react/floating-ui-react/utils/composite.mjs
  function isHiddenByStyles(styles) {
    return styles.visibility === "hidden" || styles.visibility === "collapse";
  }
  function isElementVisible(element, styles = element ? getComputedStyle2(element) : null) {
    if (!element || !element.isConnected || !styles || isHiddenByStyles(styles)) {
      return false;
    }
    if (typeof element.checkVisibility === "function") {
      return element.checkVisibility();
    }
    return styles.display !== "none" && styles.display !== "contents";
  }

  // node_modules/@base-ui/react/floating-ui-react/utils/tabbable.mjs
  var CANDIDATE_SELECTOR = 'a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]';
  function getParentElement(element) {
    const assignedSlot = element.assignedSlot;
    if (assignedSlot) {
      return assignedSlot;
    }
    if (element.parentElement) {
      return element.parentElement;
    }
    const rootNode = element.getRootNode();
    return isShadowRoot(rootNode) ? rootNode.host : null;
  }
  function getDetailsSummary(details) {
    for (const child of Array.from(details.children)) {
      if (getNodeName(child) === "summary") {
        return child;
      }
    }
    return null;
  }
  function isWithinOpenDetailsSummary(element, details) {
    const summary = getDetailsSummary(details);
    return !!summary && (element === summary || contains(summary, element));
  }
  function isFocusableCandidate(element) {
    const nodeName = element ? getNodeName(element) : "";
    return element != null && element.matches(CANDIDATE_SELECTOR) && (nodeName !== "summary" || element.parentElement != null && getNodeName(element.parentElement) === "details" && getDetailsSummary(element.parentElement) === element) && (nodeName !== "details" || getDetailsSummary(element) == null) && (nodeName !== "input" || element.type !== "hidden");
  }
  function isFocusableElement(element) {
    if (!isFocusableCandidate(element) || !element.isConnected || element.matches(":disabled")) {
      return false;
    }
    for (let current = element; current; current = getParentElement(current)) {
      const isAncestor = current !== element;
      const isSlot = getNodeName(current) === "slot";
      if (current.hasAttribute("inert")) {
        return false;
      }
      if (isAncestor && getNodeName(current) === "details" && !current.open && !isWithinOpenDetailsSummary(element, current) || current.hasAttribute("hidden") || !isSlot && !isVisibleInTabbableTree(current, isAncestor)) {
        return false;
      }
    }
    return true;
  }
  function isVisibleInTabbableTree(element, isAncestor) {
    const styles = getComputedStyle2(element);
    if (!isAncestor) {
      return isElementVisible(element, styles);
    }
    return styles.display !== "none";
  }
  function getTabIndex(element) {
    const tabIndex = element.tabIndex;
    if (tabIndex < 0) {
      const nodeName = getNodeName(element);
      if (nodeName === "details" || nodeName === "audio" || nodeName === "video" || isHTMLElement(element) && element.isContentEditable) {
        return 0;
      }
    }
    return tabIndex;
  }
  function getNamedRadioInput(element) {
    if (getNodeName(element) !== "input") {
      return null;
    }
    const input = element;
    return input.type === "radio" && input.name !== "" ? input : null;
  }
  function isTabbableRadio(element, candidates) {
    const input = getNamedRadioInput(element);
    if (!input) {
      return true;
    }
    const checkedRadio = candidates.find((candidate) => {
      const radio = getNamedRadioInput(candidate);
      return radio?.name === input.name && radio.form === input.form && radio.checked;
    });
    if (checkedRadio) {
      return checkedRadio === input;
    }
    return candidates.find((candidate) => {
      const radio = getNamedRadioInput(candidate);
      return radio?.name === input.name && radio.form === input.form;
    }) === input;
  }
  function getComposedChildren(container) {
    if (isHTMLElement(container) && getNodeName(container) === "slot") {
      const assignedElements = container.assignedElements({
        flatten: true
      });
      if (assignedElements.length > 0) {
        return assignedElements;
      }
    }
    if (isHTMLElement(container) && container.shadowRoot) {
      return Array.from(container.shadowRoot.children);
    }
    return Array.from(container.children);
  }
  function appendCandidates(container, list) {
    getComposedChildren(container).forEach((child) => {
      if (isFocusableCandidate(child)) {
        list.push(child);
      }
      appendCandidates(child, list);
    });
  }
  function appendMatchingElements(container, selector2, list) {
    getComposedChildren(container).forEach((child) => {
      if (isHTMLElement(child) && child.matches(selector2)) {
        list.push(child);
      }
      appendMatchingElements(child, selector2, list);
    });
  }
  function focusable(container) {
    const candidates = [];
    appendCandidates(container, candidates);
    return candidates.filter(isFocusableElement);
  }
  function tabbable(container) {
    const candidates = focusable(container);
    return candidates.filter((element) => getTabIndex(element) >= 0 && isTabbableRadio(element, candidates));
  }
  function getTabbableIn(container, dir) {
    const list = tabbable(container);
    const len = list.length;
    if (len === 0) {
      return void 0;
    }
    const active = activeElement(ownerDocument(container));
    const index2 = list.indexOf(active);
    const nextIndex = index2 === -1 ? dir === 1 ? 0 : len - 1 : index2 + dir;
    return list[nextIndex];
  }
  function getNextTabbable(referenceElement) {
    return getTabbableIn(ownerDocument(referenceElement).body, 1) || referenceElement;
  }
  function getPreviousTabbable(referenceElement) {
    return getTabbableIn(ownerDocument(referenceElement).body, -1) || referenceElement;
  }
  function isOutsideEvent(event, container) {
    const containerElement = container || event.currentTarget;
    const relatedTarget = event.relatedTarget;
    return !relatedTarget || !contains(containerElement, relatedTarget);
  }
  function disableFocusInside(container) {
    const tabbableElements = tabbable(container);
    tabbableElements.forEach((element) => {
      element.dataset.tabindex = element.getAttribute("tabindex") || "";
      element.setAttribute("tabindex", "-1");
    });
  }
  function enableFocusInside(container) {
    const elements2 = [];
    appendMatchingElements(container, "[data-tabindex]", elements2);
    elements2.forEach((element) => {
      const tabindex = element.dataset.tabindex;
      delete element.dataset.tabindex;
      if (tabindex) {
        element.setAttribute("tabindex", tabindex);
      } else {
        element.removeAttribute("tabindex");
      }
    });
  }

  // node_modules/@base-ui/react/floating-ui-react/utils/nodes.mjs
  function getNodeChildren(nodes, id, onlyOpenChildren = true) {
    const directChildren = nodes.filter((node) => node.parentId === id);
    return directChildren.flatMap((child) => [...!onlyOpenChildren || child.context?.open ? [child] : [], ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);
  }

  // node_modules/@base-ui/react/floating-ui-react/utils/createAttribute.mjs
  function createAttribute(name2) {
    return `data-base-ui-${name2}`;
  }

  // node_modules/@base-ui/react/floating-ui-react/components/FloatingPortal.mjs
  var React22 = __toESM(require_react(), 1);
  var ReactDOM2 = __toESM(require_react_dom(), 1);

  // node_modules/@base-ui/react/internals/constants.mjs
  var DISABLED_TRANSITIONS_STYLE = {
    style: {
      transition: "none"
    }
  };
  var BASE_UI_SWIPE_IGNORE_ATTRIBUTE = "data-base-ui-swipe-ignore";
  var LEGACY_SWIPE_IGNORE_ATTRIBUTE = "data-swipe-ignore";
  var BASE_UI_SWIPE_IGNORE_SELECTOR = `[${BASE_UI_SWIPE_IGNORE_ATTRIBUTE}]`;
  var LEGACY_SWIPE_IGNORE_SELECTOR = `[${LEGACY_SWIPE_IGNORE_ATTRIBUTE}]`;
  var POPUP_COLLISION_AVOIDANCE = {
    fallbackAxisSide: "end"
  };
  var ownerVisuallyHidden = {
    clipPath: "inset(50%)",
    position: "fixed",
    top: 0,
    left: 0
  };

  // node_modules/@base-ui/react/floating-ui-react/components/FloatingPortal.mjs
  var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
  var PortalContext = /* @__PURE__ */ React22.createContext(null);
  if (true) PortalContext.displayName = "PortalContext";
  var usePortalContext = () => React22.useContext(PortalContext);
  var attr = createAttribute("portal");
  function useFloatingPortalNode(props = {}) {
    const {
      ref,
      container: containerProp,
      componentProps = EMPTY_OBJECT,
      elementProps
    } = props;
    const uniqueId = useId();
    const portalContext = usePortalContext();
    const parentPortalNode = portalContext?.portalNode;
    const [containerElement, setContainerElement] = React22.useState(null);
    const [portalNode, setPortalNode] = React22.useState(null);
    const setPortalNodeRef = useStableCallback((node) => {
      if (node !== null) {
        setPortalNode(node);
      }
    });
    const containerRef = React22.useRef(null);
    useIsoLayoutEffect(() => {
      if (containerProp === null) {
        if (containerRef.current) {
          containerRef.current = null;
          setPortalNode(null);
          setContainerElement(null);
        }
        return;
      }
      if (uniqueId == null) {
        return;
      }
      const resolvedContainer = (containerProp && (isNode(containerProp) ? containerProp : containerProp.current)) ?? parentPortalNode ?? document.body;
      if (resolvedContainer == null) {
        if (containerRef.current) {
          containerRef.current = null;
          setPortalNode(null);
          setContainerElement(null);
        }
        return;
      }
      if (containerRef.current !== resolvedContainer) {
        containerRef.current = resolvedContainer;
        setPortalNode(null);
        setContainerElement(resolvedContainer);
      }
    }, [containerProp, parentPortalNode, uniqueId]);
    const portalElement = useRenderElement("div", componentProps, {
      ref: [ref, setPortalNodeRef],
      props: [{
        id: uniqueId,
        [attr]: ""
      }, elementProps]
    });
    const portalSubtree = containerElement && portalElement ? /* @__PURE__ */ ReactDOM2.createPortal(portalElement, containerElement) : null;
    return {
      portalNode,
      portalSubtree
    };
  }
  var FloatingPortal = /* @__PURE__ */ React22.forwardRef(function FloatingPortal2(componentProps, forwardedRef) {
    const {
      render: render4,
      className,
      style,
      children,
      container,
      renderGuards,
      ...elementProps
    } = componentProps;
    const {
      portalNode,
      portalSubtree
    } = useFloatingPortalNode({
      container,
      ref: forwardedRef,
      componentProps,
      elementProps
    });
    const beforeOutsideRef = React22.useRef(null);
    const afterOutsideRef = React22.useRef(null);
    const beforeInsideRef = React22.useRef(null);
    const afterInsideRef = React22.useRef(null);
    const [focusManagerState, setFocusManagerState] = React22.useState(null);
    const focusInsideDisabledRef = React22.useRef(false);
    const modal = focusManagerState?.modal;
    const open = focusManagerState?.open;
    const shouldRenderGuards = typeof renderGuards === "boolean" ? renderGuards : !!focusManagerState && !focusManagerState.modal && focusManagerState.open && !!portalNode;
    React22.useEffect(() => {
      if (!portalNode || modal) {
        return void 0;
      }
      function onFocus(event) {
        if (portalNode && event.relatedTarget && isOutsideEvent(event)) {
          if (event.type === "focusin") {
            if (focusInsideDisabledRef.current) {
              enableFocusInside(portalNode);
              focusInsideDisabledRef.current = false;
            }
          } else {
            disableFocusInside(portalNode);
            focusInsideDisabledRef.current = true;
          }
        }
      }
      return mergeCleanups(addEventListener(portalNode, "focusin", onFocus, true), addEventListener(portalNode, "focusout", onFocus, true));
    }, [portalNode, modal]);
    useIsoLayoutEffect(() => {
      if (!portalNode || open !== true || !focusInsideDisabledRef.current) {
        return;
      }
      enableFocusInside(portalNode);
      focusInsideDisabledRef.current = false;
    }, [open, portalNode]);
    const portalContextValue = React22.useMemo(() => ({
      beforeOutsideRef,
      afterOutsideRef,
      beforeInsideRef,
      afterInsideRef,
      portalNode,
      setFocusManagerState
    }), [portalNode]);
    return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(React22.Fragment, {
      children: [portalSubtree, /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(PortalContext.Provider, {
        value: portalContextValue,
        children: [shouldRenderGuards && portalNode && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(FocusGuard, {
          "data-type": "outside",
          ref: beforeOutsideRef,
          onFocus: (event) => {
            if (isOutsideEvent(event, portalNode)) {
              beforeInsideRef.current?.focus();
            } else {
              const domReference = focusManagerState ? focusManagerState.domReference : null;
              const prevTabbable = getPreviousTabbable(domReference);
              prevTabbable?.focus();
            }
          }
        }), shouldRenderGuards && portalNode && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", {
          "aria-owns": portalNode.id,
          style: ownerVisuallyHidden
        }), portalNode && /* @__PURE__ */ ReactDOM2.createPortal(children, portalNode), shouldRenderGuards && portalNode && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(FocusGuard, {
          "data-type": "outside",
          ref: afterOutsideRef,
          onFocus: (event) => {
            if (isOutsideEvent(event, portalNode)) {
              afterInsideRef.current?.focus();
            } else {
              const domReference = focusManagerState ? focusManagerState.domReference : null;
              const nextTabbable = getNextTabbable(domReference);
              nextTabbable?.focus();
              if (focusManagerState?.closeOnFocusOut) {
                focusManagerState?.onOpenChange(false, createChangeEventDetails(reason_parts_exports.focusOut, event.nativeEvent));
              }
            }
          }
        })]
      })]
    });
  });
  if (true) FloatingPortal.displayName = "FloatingPortal";

  // node_modules/@base-ui/react/floating-ui-react/components/FloatingTree.mjs
  var React23 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/floating-ui-react/utils/createEventEmitter.mjs
  function createEventEmitter() {
    const map = /* @__PURE__ */ new Map();
    return {
      emit(event, data) {
        map.get(event)?.forEach((listener) => listener(data));
      },
      on(event, listener) {
        if (!map.has(event)) {
          map.set(event, /* @__PURE__ */ new Set());
        }
        map.get(event).add(listener);
      },
      off(event, listener) {
        map.get(event)?.delete(listener);
      }
    };
  }

  // node_modules/@base-ui/react/floating-ui-react/components/FloatingTree.mjs
  var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
  var FloatingNodeContext = /* @__PURE__ */ React23.createContext(null);
  if (true) FloatingNodeContext.displayName = "FloatingNodeContext";
  var FloatingTreeContext = /* @__PURE__ */ React23.createContext(null);
  if (true) FloatingTreeContext.displayName = "FloatingTreeContext";
  var useFloatingParentNodeId = () => React23.useContext(FloatingNodeContext)?.id || null;
  var useFloatingTree = (externalTree) => {
    const contextTree = React23.useContext(FloatingTreeContext);
    return externalTree ?? contextTree;
  };

  // node_modules/@base-ui/react/floating-ui-react/hooks/useClientPoint.mjs
  var React24 = __toESM(require_react(), 1);
  function createVirtualElement(domElement, data) {
    let offsetX = null;
    let offsetY = null;
    let isAutoUpdateEvent = false;
    return {
      contextElement: domElement || void 0,
      getBoundingClientRect() {
        const domRect = domElement?.getBoundingClientRect() || {
          width: 0,
          height: 0,
          x: 0,
          y: 0
        };
        const isXAxis = data.axis === "x" || data.axis === "both";
        const isYAxis = data.axis === "y" || data.axis === "both";
        const canTrackCursorOnAutoUpdate = ["mouseenter", "mousemove"].includes(data.dataRef.current.openEvent?.type || "") && data.pointerType !== "touch";
        let width = domRect.width;
        let height = domRect.height;
        let x2 = domRect.x;
        let y2 = domRect.y;
        if (offsetX == null && data.x && isXAxis) {
          offsetX = domRect.x - data.x;
        }
        if (offsetY == null && data.y && isYAxis) {
          offsetY = domRect.y - data.y;
        }
        x2 -= offsetX || 0;
        y2 -= offsetY || 0;
        width = 0;
        height = 0;
        if (!isAutoUpdateEvent || canTrackCursorOnAutoUpdate) {
          width = data.axis === "y" ? domRect.width : 0;
          height = data.axis === "x" ? domRect.height : 0;
          x2 = isXAxis && data.x != null ? data.x : x2;
          y2 = isYAxis && data.y != null ? data.y : y2;
        } else if (isAutoUpdateEvent && !canTrackCursorOnAutoUpdate) {
          height = data.axis === "x" ? domRect.height : height;
          width = data.axis === "y" ? domRect.width : width;
        }
        isAutoUpdateEvent = true;
        return {
          width,
          height,
          x: x2,
          y: y2,
          top: y2,
          right: x2 + width,
          bottom: y2 + height,
          left: x2
        };
      }
    };
  }
  function isMouseBasedEvent(event) {
    return event != null && event.clientX != null;
  }
  function useClientPoint(context, props = {}) {
    const {
      enabled = true,
      axis = "both"
    } = props;
    const store2 = "rootStore" in context ? context.rootStore : context;
    const open = store2.useState("open");
    const floating = store2.useState("floatingElement");
    const domReference = store2.useState("domReferenceElement");
    const dataRef = store2.context.dataRef;
    const initialRef = React24.useRef(false);
    const cleanupListenerRef = React24.useRef(null);
    const [pointerType, setPointerType] = React24.useState();
    const [reactive, setReactive] = React24.useState([]);
    const resetReference = useStableCallback((reference2) => {
      store2.set("positionReference", reference2);
    });
    const setReference = useStableCallback((newX, newY, referenceElement) => {
      if (initialRef.current) {
        return;
      }
      if (dataRef.current.openEvent && !isMouseBasedEvent(dataRef.current.openEvent)) {
        return;
      }
      store2.set("positionReference", createVirtualElement(referenceElement ?? domReference, {
        x: newX,
        y: newY,
        axis,
        dataRef,
        pointerType
      }));
    });
    const handleReferenceEnterOrMove = useStableCallback((event) => {
      if (!open) {
        setReference(event.clientX, event.clientY, event.currentTarget);
      } else if (!cleanupListenerRef.current) {
        setReference(event.clientX, event.clientY, event.currentTarget);
        setReactive([]);
      }
    });
    const openCheck = isMouseLikePointerType(pointerType) ? floating : open;
    React24.useEffect(() => {
      if (!enabled) {
        resetReference(domReference);
        return void 0;
      }
      if (!openCheck) {
        return void 0;
      }
      function cleanupListener() {
        cleanupListenerRef.current?.();
        cleanupListenerRef.current = null;
      }
      const win = getWindow(floating);
      function handleMouseMove(event) {
        const target = getTarget(event);
        if (!contains(floating, target)) {
          setReference(event.clientX, event.clientY);
        } else {
          cleanupListener();
        }
      }
      if (!dataRef.current.openEvent || isMouseBasedEvent(dataRef.current.openEvent)) {
        cleanupListenerRef.current = addEventListener(win, "mousemove", handleMouseMove);
      } else {
        resetReference(domReference);
      }
      return cleanupListener;
    }, [openCheck, enabled, floating, dataRef, domReference, store2, setReference, resetReference, reactive]);
    React24.useEffect(() => () => {
      store2.set("positionReference", null);
    }, [store2]);
    React24.useEffect(() => {
      if (enabled && !floating) {
        initialRef.current = false;
      }
    }, [enabled, floating]);
    React24.useEffect(() => {
      if (!enabled && open) {
        initialRef.current = true;
      }
    }, [enabled, open]);
    const reference = React24.useMemo(() => {
      function setPointerTypeRef(event) {
        setPointerType(event.pointerType);
      }
      return {
        onPointerDown: setPointerTypeRef,
        onPointerEnter: setPointerTypeRef,
        onMouseMove: handleReferenceEnterOrMove,
        onMouseEnter: handleReferenceEnterOrMove
      };
    }, [handleReferenceEnterOrMove]);
    return React24.useMemo(() => enabled ? {
      reference,
      trigger: reference
    } : {}, [enabled, reference]);
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useDismiss.mjs
  var React25 = __toESM(require_react(), 1);
  function alwaysFalse() {
    return false;
  }
  function normalizeProp(normalizable) {
    return {
      escapeKey: typeof normalizable === "boolean" ? normalizable : normalizable?.escapeKey ?? false,
      outsidePress: typeof normalizable === "boolean" ? normalizable : normalizable?.outsidePress ?? true
    };
  }
  function useDismiss(context, props = {}) {
    const {
      enabled = true,
      escapeKey: escapeKey2 = true,
      outsidePress: outsidePressProp = true,
      outsidePressEvent = "sloppy",
      referencePress = alwaysFalse,
      bubbles,
      externalTree
    } = props;
    const store2 = "rootStore" in context ? context.rootStore : context;
    const open = store2.useState("open");
    const floatingElement = store2.useState("floatingElement");
    const {
      dataRef
    } = store2.context;
    const tree = useFloatingTree(externalTree);
    const outsidePressFn = useStableCallback(typeof outsidePressProp === "function" ? outsidePressProp : () => false);
    const outsidePress2 = typeof outsidePressProp === "function" ? outsidePressFn : outsidePressProp;
    const outsidePressEnabled = outsidePress2 !== false;
    const getOutsidePressEventProp = useStableCallback(() => outsidePressEvent);
    const {
      escapeKey: escapeKeyBubbles,
      outsidePress: outsidePressBubbles
    } = normalizeProp(bubbles);
    const pressStartedInsideRef = React25.useRef(false);
    const pressStartPreventedRef = React25.useRef(false);
    const suppressNextOutsideClickRef = React25.useRef(false);
    const isComposingRef = React25.useRef(false);
    const currentPointerTypeRef = React25.useRef("");
    const touchStateRef = React25.useRef(null);
    const cancelDismissOnEndTimeout = useTimeout();
    const clearInsideReactTreeTimeout = useTimeout();
    const clearInsideReactTree = useStableCallback(() => {
      clearInsideReactTreeTimeout.clear();
      dataRef.current.insideReactTree = false;
    });
    const hasBlockingChild = useStableCallback((bubbleKey) => {
      const nodeId = dataRef.current.floatingContext?.nodeId;
      const children = tree ? getNodeChildren(tree.nodesRef.current, nodeId) : [];
      return children.some((child) => child.context?.open && !child.context.dataRef.current[bubbleKey]);
    });
    const isEventWithinOwnElements = useStableCallback((event) => {
      return isEventTargetWithin(event, store2.select("floatingElement")) || isEventTargetWithin(event, store2.select("domReferenceElement"));
    });
    const closeOnReferencePress = useStableCallback((event) => {
      if (!referencePress()) {
        return;
      }
      store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerPress, event.nativeEvent));
    });
    const closeOnEscapeKeyDown = useStableCallback((event) => {
      if (!open || !enabled || !escapeKey2 || event.key !== "Escape") {
        return;
      }
      if (isComposingRef.current) {
        return;
      }
      if (!escapeKeyBubbles && hasBlockingChild("__escapeKeyBubbles")) {
        return;
      }
      const native = isReactEvent(event) ? event.nativeEvent : event;
      const eventDetails = createChangeEventDetails(reason_parts_exports.escapeKey, native);
      store2.setOpen(false, eventDetails);
      if (!eventDetails.isCanceled) {
        event.preventDefault();
      }
      if (!escapeKeyBubbles && !eventDetails.isPropagationAllowed) {
        event.stopPropagation();
      }
    });
    const markInsideReactTree = useStableCallback(() => {
      dataRef.current.insideReactTree = true;
      clearInsideReactTreeTimeout.start(0, clearInsideReactTree);
    });
    const markPressStartedInsideReactTree = useStableCallback((event) => {
      if (!open || !enabled || event.button !== 0) {
        return;
      }
      const target = getTarget(event.nativeEvent);
      if (!contains(store2.select("floatingElement"), target)) {
        return;
      }
      if (!pressStartedInsideRef.current) {
        pressStartedInsideRef.current = true;
        pressStartPreventedRef.current = false;
      }
    });
    const markInsidePressStartPrevented = useStableCallback((event) => {
      if (!open || !enabled) {
        return;
      }
      if (!(event.defaultPrevented || event.nativeEvent.defaultPrevented)) {
        return;
      }
      if (pressStartedInsideRef.current) {
        pressStartPreventedRef.current = true;
      }
    });
    React25.useEffect(() => {
      if (!open || !enabled) {
        return void 0;
      }
      dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;
      dataRef.current.__outsidePressBubbles = outsidePressBubbles;
      const compositionTimeout = new Timeout();
      const preventedPressSuppressionTimeout = new Timeout();
      function handleCompositionStart() {
        compositionTimeout.clear();
        isComposingRef.current = true;
      }
      function handleCompositionEnd() {
        compositionTimeout.start(
          // 0ms or 1ms don't work in Safari. 5ms appears to consistently work.
          // Only apply to WebKit for the test to remain 0ms.
          parts_exports.engine.webkit ? 5 : 0,
          () => {
            isComposingRef.current = false;
          }
        );
      }
      function suppressImmediateOutsideClickAfterPreventedStart() {
        suppressNextOutsideClickRef.current = true;
        preventedPressSuppressionTimeout.start(0, () => {
          suppressNextOutsideClickRef.current = false;
        });
      }
      function resetPressStartState() {
        pressStartedInsideRef.current = false;
        pressStartPreventedRef.current = false;
      }
      function getOutsidePressEvent() {
        const type = currentPointerTypeRef.current;
        const computedType = type === "pen" || !type ? "mouse" : type;
        const outsidePressEventValue = getOutsidePressEventProp();
        const resolved = typeof outsidePressEventValue === "function" ? outsidePressEventValue() : outsidePressEventValue;
        if (typeof resolved === "string") {
          return resolved;
        }
        return resolved[computedType];
      }
      function shouldIgnoreEvent(event) {
        const computedOutsidePressEvent = getOutsidePressEvent();
        return computedOutsidePressEvent === "intentional" && event.type !== "click" || computedOutsidePressEvent === "sloppy" && event.type === "click";
      }
      function isEventWithinFloatingTree(event) {
        const nodeId = dataRef.current.floatingContext?.nodeId;
        const targetIsInsideChildren = tree && getNodeChildren(tree.nodesRef.current, nodeId).some((node) => isEventTargetWithin(event, node.context?.elements.floating));
        return isEventWithinOwnElements(event) || targetIsInsideChildren;
      }
      function closeOnPressOutside(event) {
        if (shouldIgnoreEvent(event)) {
          if (event.type !== "click" && !isEventWithinOwnElements(event)) {
            preventedPressSuppressionTimeout.clear();
            suppressNextOutsideClickRef.current = false;
          }
          clearInsideReactTree();
          return;
        }
        if (dataRef.current.insideReactTree) {
          clearInsideReactTree();
          return;
        }
        const target = getTarget(event);
        const inertSelector = `[${createAttribute("inert")}]`;
        const targetRoot = isElement(target) ? target.getRootNode() : null;
        const markers = Array.from((isShadowRoot(targetRoot) ? targetRoot : ownerDocument(store2.select("floatingElement"))).querySelectorAll(inertSelector));
        const triggers = store2.context.triggerElements;
        if (target && (triggers.hasElement(target) || triggers.hasMatchingElement((trigger) => contains(trigger, target)))) {
          return;
        }
        let targetRootAncestor = isElement(target) ? target : null;
        while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {
          const nextParent = getParentNode(targetRootAncestor);
          if (isLastTraversableNode(nextParent) || !isElement(nextParent)) {
            break;
          }
          targetRootAncestor = nextParent;
        }
        if (markers.length && isElement(target) && !isRootElement(target) && // Clicked on a direct ancestor (e.g. FloatingOverlay).
        !contains(target, store2.select("floatingElement")) && // If the target root element contains none of the markers, then the
        // element was injected after the floating element rendered.
        markers.every((marker) => !contains(targetRootAncestor, marker))) {
          return;
        }
        if (isHTMLElement(target) && !("touches" in event)) {
          const lastTraversableNode = isLastTraversableNode(target);
          const style = getComputedStyle2(target);
          const scrollRe = /auto|scroll/;
          const isScrollableX = lastTraversableNode || scrollRe.test(style.overflowX);
          const isScrollableY = lastTraversableNode || scrollRe.test(style.overflowY);
          const canScrollX = isScrollableX && target.clientWidth > 0 && target.scrollWidth > target.clientWidth;
          const canScrollY = isScrollableY && target.clientHeight > 0 && target.scrollHeight > target.clientHeight;
          const isRTL23 = style.direction === "rtl";
          const pressedVerticalScrollbar = canScrollY && (isRTL23 ? event.offsetX <= target.offsetWidth - target.clientWidth : event.offsetX > target.clientWidth);
          const pressedHorizontalScrollbar = canScrollX && event.offsetY > target.clientHeight;
          if (pressedVerticalScrollbar || pressedHorizontalScrollbar) {
            return;
          }
        }
        if (isEventWithinFloatingTree(event)) {
          return;
        }
        if (getOutsidePressEvent() === "intentional" && suppressNextOutsideClickRef.current) {
          preventedPressSuppressionTimeout.clear();
          suppressNextOutsideClickRef.current = false;
          return;
        }
        if (typeof outsidePress2 === "function" && !outsidePress2(event)) {
          return;
        }
        if (hasBlockingChild("__outsidePressBubbles")) {
          return;
        }
        store2.setOpen(false, createChangeEventDetails(reason_parts_exports.outsidePress, event));
        clearInsideReactTree();
      }
      function handlePointerDown(event) {
        if (getOutsidePressEvent() !== "sloppy" || event.pointerType === "touch" || !store2.select("open") || !enabled || isEventWithinOwnElements(event)) {
          return;
        }
        closeOnPressOutside(event);
      }
      function handleTouchStart(event) {
        if (getOutsidePressEvent() !== "sloppy" || !store2.select("open") || !enabled || isEventWithinOwnElements(event)) {
          return;
        }
        const touch = event.touches[0];
        if (touch) {
          touchStateRef.current = {
            startTime: Date.now(),
            startX: touch.clientX,
            startY: touch.clientY,
            dismissOnTouchEnd: false,
            dismissOnMouseDown: true
          };
          cancelDismissOnEndTimeout.start(1e3, () => {
            if (touchStateRef.current) {
              touchStateRef.current.dismissOnTouchEnd = false;
              touchStateRef.current.dismissOnMouseDown = false;
            }
          });
        }
      }
      function addTargetEventListenerOnce(event, listener) {
        const target = getTarget(event);
        if (!target) {
          return;
        }
        const unsubscribe2 = addEventListener(target, event.type, () => {
          listener(event);
          unsubscribe2();
        });
      }
      function handleTouchStartCapture(event) {
        currentPointerTypeRef.current = "touch";
        addTargetEventListenerOnce(event, handleTouchStart);
      }
      function closeOnPressOutsideCapture(event) {
        cancelDismissOnEndTimeout.clear();
        if (event.type === "pointerdown") {
          currentPointerTypeRef.current = event.pointerType;
        }
        if (event.type === "mousedown" && touchStateRef.current && !touchStateRef.current.dismissOnMouseDown) {
          return;
        }
        addTargetEventListenerOnce(event, (targetEvent) => {
          if (targetEvent.type === "pointerdown") {
            handlePointerDown(targetEvent);
          } else {
            closeOnPressOutside(targetEvent);
          }
        });
      }
      function handlePressEndCapture(event) {
        if (!pressStartedInsideRef.current) {
          return;
        }
        const pressStartedInsideDefaultPrevented = pressStartPreventedRef.current;
        resetPressStartState();
        if (getOutsidePressEvent() !== "intentional") {
          return;
        }
        if (event.type === "pointercancel") {
          if (pressStartedInsideDefaultPrevented) {
            suppressImmediateOutsideClickAfterPreventedStart();
          }
          return;
        }
        if (isEventWithinFloatingTree(event)) {
          return;
        }
        if (pressStartedInsideDefaultPrevented) {
          suppressImmediateOutsideClickAfterPreventedStart();
          return;
        }
        if (typeof outsidePress2 === "function" && !outsidePress2(event)) {
          return;
        }
        preventedPressSuppressionTimeout.clear();
        suppressNextOutsideClickRef.current = true;
        clearInsideReactTree();
      }
      function handleTouchMove(event) {
        if (getOutsidePressEvent() !== "sloppy" || !touchStateRef.current || isEventWithinOwnElements(event)) {
          return;
        }
        const touch = event.touches[0];
        if (!touch) {
          return;
        }
        const deltaX = Math.abs(touch.clientX - touchStateRef.current.startX);
        const deltaY = Math.abs(touch.clientY - touchStateRef.current.startY);
        const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
        if (distance > 5) {
          touchStateRef.current.dismissOnTouchEnd = true;
        }
        if (distance > 10) {
          closeOnPressOutside(event);
          cancelDismissOnEndTimeout.clear();
          touchStateRef.current = null;
        }
      }
      function handleTouchMoveCapture(event) {
        addTargetEventListenerOnce(event, handleTouchMove);
      }
      function handleTouchEnd(event) {
        if (getOutsidePressEvent() !== "sloppy" || !touchStateRef.current || isEventWithinOwnElements(event)) {
          return;
        }
        if (touchStateRef.current.dismissOnTouchEnd) {
          closeOnPressOutside(event);
        }
        cancelDismissOnEndTimeout.clear();
        touchStateRef.current = null;
      }
      function handleTouchEndCapture(event) {
        addTargetEventListenerOnce(event, handleTouchEnd);
      }
      const doc = ownerDocument(floatingElement);
      const unsubscribe = mergeCleanups(escapeKey2 && mergeCleanups(addEventListener(doc, "keydown", closeOnEscapeKeyDown), addEventListener(doc, "compositionstart", handleCompositionStart), addEventListener(doc, "compositionend", handleCompositionEnd)), outsidePressEnabled && mergeCleanups(addEventListener(doc, "click", closeOnPressOutsideCapture, true), addEventListener(doc, "pointerdown", closeOnPressOutsideCapture, true), addEventListener(doc, "pointerup", handlePressEndCapture, true), addEventListener(doc, "pointercancel", handlePressEndCapture, true), addEventListener(doc, "mousedown", closeOnPressOutsideCapture, true), addEventListener(doc, "mouseup", handlePressEndCapture, true), addEventListener(doc, "touchstart", handleTouchStartCapture, true), addEventListener(doc, "touchmove", handleTouchMoveCapture, true), addEventListener(doc, "touchend", handleTouchEndCapture, true)));
      return () => {
        unsubscribe();
        compositionTimeout.clear();
        preventedPressSuppressionTimeout.clear();
        resetPressStartState();
        suppressNextOutsideClickRef.current = false;
      };
    }, [dataRef, floatingElement, escapeKey2, outsidePressEnabled, outsidePress2, open, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, clearInsideReactTree, getOutsidePressEventProp, hasBlockingChild, isEventWithinOwnElements, tree, store2, cancelDismissOnEndTimeout]);
    React25.useEffect(clearInsideReactTree, [outsidePress2, clearInsideReactTree]);
    const reference = React25.useMemo(() => ({
      onKeyDown: closeOnEscapeKeyDown,
      onPointerDown: closeOnReferencePress,
      onClick: closeOnReferencePress
    }), [closeOnEscapeKeyDown, closeOnReferencePress]);
    const floating = React25.useMemo(() => ({
      onKeyDown: closeOnEscapeKeyDown,
      // `onMouseDown` may be blocked if `event.preventDefault()` is called in
      // `onPointerDown`, such as with <NumberField.ScrubArea>.
      // See https://github.com/mui/base-ui/pull/3379
      onPointerDown: markInsidePressStartPrevented,
      onMouseDown: markInsidePressStartPrevented,
      onClickCapture: markInsideReactTree,
      onMouseDownCapture(event) {
        markInsideReactTree();
        markPressStartedInsideReactTree(event);
      },
      onPointerDownCapture(event) {
        markInsideReactTree();
        markPressStartedInsideReactTree(event);
      },
      onMouseUpCapture: markInsideReactTree,
      onTouchEndCapture: markInsideReactTree,
      onTouchMoveCapture: markInsideReactTree
    }), [closeOnEscapeKeyDown, markInsideReactTree, markPressStartedInsideReactTree, markInsidePressStartPrevented]);
    return React25.useMemo(() => enabled ? {
      reference,
      floating,
      trigger: reference
    } : {}, [enabled, reference, floating]);
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useFloating.mjs
  var React32 = __toESM(require_react(), 1);

  // node_modules/@floating-ui/core/dist/floating-ui.core.mjs
  function computeCoordsFromPlacement(_ref, placement, rtl) {
    let {
      reference,
      floating
    } = _ref;
    const sideAxis = getSideAxis(placement);
    const alignmentAxis = getAlignmentAxis(placement);
    const alignLength = getAxisLength(alignmentAxis);
    const side = getSide(placement);
    const isVertical = sideAxis === "y";
    const commonX = reference.x + reference.width / 2 - floating.width / 2;
    const commonY = reference.y + reference.height / 2 - floating.height / 2;
    const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
    let coords;
    switch (side) {
      case "top":
        coords = {
          x: commonX,
          y: reference.y - floating.height
        };
        break;
      case "bottom":
        coords = {
          x: commonX,
          y: reference.y + reference.height
        };
        break;
      case "right":
        coords = {
          x: reference.x + reference.width,
          y: commonY
        };
        break;
      case "left":
        coords = {
          x: reference.x - floating.width,
          y: commonY
        };
        break;
      default:
        coords = {
          x: reference.x,
          y: reference.y
        };
    }
    switch (getAlignment(placement)) {
      case "start":
        coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
        break;
      case "end":
        coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
        break;
    }
    return coords;
  }
  async function detectOverflow(state, options) {
    var _await$platform$isEle;
    if (options === void 0) {
      options = {};
    }
    const {
      x: x2,
      y: y2,
      platform: platform3,
      rects,
      elements: elements2,
      strategy
    } = state;
    const {
      boundary = "clippingAncestors",
      rootBoundary = "viewport",
      elementContext = "floating",
      altBoundary = false,
      padding = 0
    } = evaluate(options, state);
    const paddingObject = getPaddingObject(padding);
    const altContext = elementContext === "floating" ? "reference" : "floating";
    const element = elements2[altBoundary ? altContext : elementContext];
    const clippingClientRect = rectToClientRect(await platform3.getClippingRect({
      element: ((_await$platform$isEle = await (platform3.isElement == null ? void 0 : platform3.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || await (platform3.getDocumentElement == null ? void 0 : platform3.getDocumentElement(elements2.floating)),
      boundary,
      rootBoundary,
      strategy
    }));
    const rect = elementContext === "floating" ? {
      x: x2,
      y: y2,
      width: rects.floating.width,
      height: rects.floating.height
    } : rects.reference;
    const offsetParent = await (platform3.getOffsetParent == null ? void 0 : platform3.getOffsetParent(elements2.floating));
    const offsetScale = await (platform3.isElement == null ? void 0 : platform3.isElement(offsetParent)) ? await (platform3.getScale == null ? void 0 : platform3.getScale(offsetParent)) || {
      x: 1,
      y: 1
    } : {
      x: 1,
      y: 1
    };
    const elementClientRect = rectToClientRect(platform3.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform3.convertOffsetParentRelativeRectToViewportRelativeRect({
      elements: elements2,
      rect,
      offsetParent,
      strategy
    }) : rect);
    return {
      top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
      bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
      left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
      right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
    };
  }
  var MAX_RESET_COUNT = 50;
  var computePosition = async (reference, floating, config2) => {
    const {
      placement = "bottom",
      strategy = "absolute",
      middleware = [],
      platform: platform3
    } = config2;
    const platformWithDetectOverflow = platform3.detectOverflow ? platform3 : {
      ...platform3,
      detectOverflow
    };
    const rtl = await (platform3.isRTL == null ? void 0 : platform3.isRTL(floating));
    let rects = await platform3.getElementRects({
      reference,
      floating,
      strategy
    });
    let {
      x: x2,
      y: y2
    } = computeCoordsFromPlacement(rects, placement, rtl);
    let statefulPlacement = placement;
    let resetCount = 0;
    const middlewareData = {};
    for (let i2 = 0; i2 < middleware.length; i2++) {
      const currentMiddleware = middleware[i2];
      if (!currentMiddleware) {
        continue;
      }
      const {
        name: name2,
        fn
      } = currentMiddleware;
      const {
        x: nextX,
        y: nextY,
        data,
        reset
      } = await fn({
        x: x2,
        y: y2,
        initialPlacement: placement,
        placement: statefulPlacement,
        strategy,
        middlewareData,
        rects,
        platform: platformWithDetectOverflow,
        elements: {
          reference,
          floating
        }
      });
      x2 = nextX != null ? nextX : x2;
      y2 = nextY != null ? nextY : y2;
      middlewareData[name2] = {
        ...middlewareData[name2],
        ...data
      };
      if (reset && resetCount < MAX_RESET_COUNT) {
        resetCount++;
        if (typeof reset === "object") {
          if (reset.placement) {
            statefulPlacement = reset.placement;
          }
          if (reset.rects) {
            rects = reset.rects === true ? await platform3.getElementRects({
              reference,
              floating,
              strategy
            }) : reset.rects;
          }
          ({
            x: x2,
            y: y2
          } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
        }
        i2 = -1;
      }
    }
    return {
      x: x2,
      y: y2,
      placement: statefulPlacement,
      strategy,
      middlewareData
    };
  };
  var flip = function(options) {
    if (options === void 0) {
      options = {};
    }
    return {
      name: "flip",
      options,
      async fn(state) {
        var _middlewareData$arrow, _middlewareData$flip;
        const {
          placement,
          middlewareData,
          rects,
          initialPlacement,
          platform: platform3,
          elements: elements2
        } = state;
        const {
          mainAxis: checkMainAxis = true,
          crossAxis: checkCrossAxis = true,
          fallbackPlacements: specifiedFallbackPlacements,
          fallbackStrategy = "bestFit",
          fallbackAxisSideDirection = "none",
          flipAlignment = true,
          ...detectOverflowOptions
        } = evaluate(options, state);
        if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
          return {};
        }
        const side = getSide(placement);
        const initialSideAxis = getSideAxis(initialPlacement);
        const isBasePlacement = getSide(initialPlacement) === initialPlacement;
        const rtl = await (platform3.isRTL == null ? void 0 : platform3.isRTL(elements2.floating));
        const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
        const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== "none";
        if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {
          fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
        }
        const placements2 = [initialPlacement, ...fallbackPlacements];
        const overflow = await platform3.detectOverflow(state, detectOverflowOptions);
        const overflows = [];
        let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
        if (checkMainAxis) {
          overflows.push(overflow[side]);
        }
        if (checkCrossAxis) {
          const sides2 = getAlignmentSides(placement, rects, rtl);
          overflows.push(overflow[sides2[0]], overflow[sides2[1]]);
        }
        overflowsData = [...overflowsData, {
          placement,
          overflows
        }];
        if (!overflows.every((side2) => side2 <= 0)) {
          var _middlewareData$flip2, _overflowsData$filter;
          const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
          const nextPlacement = placements2[nextIndex];
          if (nextPlacement) {
            const ignoreCrossAxisOverflow = checkCrossAxis === "alignment" ? initialSideAxis !== getSideAxis(nextPlacement) : false;
            if (!ignoreCrossAxisOverflow || // We leave the current main axis only if every placement on that axis
            // overflows the main axis.
            overflowsData.every((d2) => getSideAxis(d2.placement) === initialSideAxis ? d2.overflows[0] > 0 : true)) {
              return {
                data: {
                  index: nextIndex,
                  overflows: overflowsData
                },
                reset: {
                  placement: nextPlacement
                }
              };
            }
          }
          let resetPlacement = (_overflowsData$filter = overflowsData.filter((d2) => d2.overflows[0] <= 0).sort((a2, b2) => a2.overflows[1] - b2.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
          if (!resetPlacement) {
            switch (fallbackStrategy) {
              case "bestFit": {
                var _overflowsData$filter2;
                const placement2 = (_overflowsData$filter2 = overflowsData.filter((d2) => {
                  if (hasFallbackAxisSideDirection) {
                    const currentSideAxis = getSideAxis(d2.placement);
                    return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal
                    // reading directions favoring greater width.
                    currentSideAxis === "y";
                  }
                  return true;
                }).map((d2) => [d2.placement, d2.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a2, b2) => a2[1] - b2[1])[0]) == null ? void 0 : _overflowsData$filter2[0];
                if (placement2) {
                  resetPlacement = placement2;
                }
                break;
              }
              case "initialPlacement":
                resetPlacement = initialPlacement;
                break;
            }
          }
          if (placement !== resetPlacement) {
            return {
              reset: {
                placement: resetPlacement
              }
            };
          }
        }
        return {};
      }
    };
  };
  function getSideOffsets(overflow, rect) {
    return {
      top: overflow.top - rect.height,
      right: overflow.right - rect.width,
      bottom: overflow.bottom - rect.height,
      left: overflow.left - rect.width
    };
  }
  function isAnySideFullyClipped(overflow) {
    return sides.some((side) => overflow[side] >= 0);
  }
  var hide = function(options) {
    if (options === void 0) {
      options = {};
    }
    return {
      name: "hide",
      options,
      async fn(state) {
        const {
          rects,
          platform: platform3
        } = state;
        const {
          strategy = "referenceHidden",
          ...detectOverflowOptions
        } = evaluate(options, state);
        switch (strategy) {
          case "referenceHidden": {
            const overflow = await platform3.detectOverflow(state, {
              ...detectOverflowOptions,
              elementContext: "reference"
            });
            const offsets = getSideOffsets(overflow, rects.reference);
            return {
              data: {
                referenceHiddenOffsets: offsets,
                referenceHidden: isAnySideFullyClipped(offsets)
              }
            };
          }
          case "escaped": {
            const overflow = await platform3.detectOverflow(state, {
              ...detectOverflowOptions,
              altBoundary: true
            });
            const offsets = getSideOffsets(overflow, rects.floating);
            return {
              data: {
                escapedOffsets: offsets,
                escaped: isAnySideFullyClipped(offsets)
              }
            };
          }
          default: {
            return {};
          }
        }
      }
    };
  };
  var originSides = /* @__PURE__ */ new Set(["left", "top"]);
  async function convertValueToCoords(state, options) {
    const {
      placement,
      platform: platform3,
      elements: elements2
    } = state;
    const rtl = await (platform3.isRTL == null ? void 0 : platform3.isRTL(elements2.floating));
    const side = getSide(placement);
    const alignment = getAlignment(placement);
    const isVertical = getSideAxis(placement) === "y";
    const mainAxisMulti = originSides.has(side) ? -1 : 1;
    const crossAxisMulti = rtl && isVertical ? -1 : 1;
    const rawValue = evaluate(options, state);
    let {
      mainAxis,
      crossAxis,
      alignmentAxis
    } = typeof rawValue === "number" ? {
      mainAxis: rawValue,
      crossAxis: 0,
      alignmentAxis: null
    } : {
      mainAxis: rawValue.mainAxis || 0,
      crossAxis: rawValue.crossAxis || 0,
      alignmentAxis: rawValue.alignmentAxis
    };
    if (alignment && typeof alignmentAxis === "number") {
      crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis;
    }
    return isVertical ? {
      x: crossAxis * crossAxisMulti,
      y: mainAxis * mainAxisMulti
    } : {
      x: mainAxis * mainAxisMulti,
      y: crossAxis * crossAxisMulti
    };
  }
  var offset = function(options) {
    if (options === void 0) {
      options = 0;
    }
    return {
      name: "offset",
      options,
      async fn(state) {
        var _middlewareData$offse, _middlewareData$arrow;
        const {
          x: x2,
          y: y2,
          placement,
          middlewareData
        } = state;
        const diffCoords = await convertValueToCoords(state, options);
        if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
          return {};
        }
        return {
          x: x2 + diffCoords.x,
          y: y2 + diffCoords.y,
          data: {
            ...diffCoords,
            placement
          }
        };
      }
    };
  };
  var shift = function(options) {
    if (options === void 0) {
      options = {};
    }
    return {
      name: "shift",
      options,
      async fn(state) {
        const {
          x: x2,
          y: y2,
          placement,
          platform: platform3
        } = state;
        const {
          mainAxis: checkMainAxis = true,
          crossAxis: checkCrossAxis = false,
          limiter = {
            fn: (_ref) => {
              let {
                x: x3,
                y: y3
              } = _ref;
              return {
                x: x3,
                y: y3
              };
            }
          },
          ...detectOverflowOptions
        } = evaluate(options, state);
        const coords = {
          x: x2,
          y: y2
        };
        const overflow = await platform3.detectOverflow(state, detectOverflowOptions);
        const crossAxis = getSideAxis(getSide(placement));
        const mainAxis = getOppositeAxis(crossAxis);
        let mainAxisCoord = coords[mainAxis];
        let crossAxisCoord = coords[crossAxis];
        if (checkMainAxis) {
          const minSide = mainAxis === "y" ? "top" : "left";
          const maxSide = mainAxis === "y" ? "bottom" : "right";
          const min2 = mainAxisCoord + overflow[minSide];
          const max2 = mainAxisCoord - overflow[maxSide];
          mainAxisCoord = clamp(min2, mainAxisCoord, max2);
        }
        if (checkCrossAxis) {
          const minSide = crossAxis === "y" ? "top" : "left";
          const maxSide = crossAxis === "y" ? "bottom" : "right";
          const min2 = crossAxisCoord + overflow[minSide];
          const max2 = crossAxisCoord - overflow[maxSide];
          crossAxisCoord = clamp(min2, crossAxisCoord, max2);
        }
        const limitedCoords = limiter.fn({
          ...state,
          [mainAxis]: mainAxisCoord,
          [crossAxis]: crossAxisCoord
        });
        return {
          ...limitedCoords,
          data: {
            x: limitedCoords.x - x2,
            y: limitedCoords.y - y2,
            enabled: {
              [mainAxis]: checkMainAxis,
              [crossAxis]: checkCrossAxis
            }
          }
        };
      }
    };
  };
  var limitShift = function(options) {
    if (options === void 0) {
      options = {};
    }
    return {
      options,
      fn(state) {
        const {
          x: x2,
          y: y2,
          placement,
          rects,
          middlewareData
        } = state;
        const {
          offset: offset4 = 0,
          mainAxis: checkMainAxis = true,
          crossAxis: checkCrossAxis = true
        } = evaluate(options, state);
        const coords = {
          x: x2,
          y: y2
        };
        const crossAxis = getSideAxis(placement);
        const mainAxis = getOppositeAxis(crossAxis);
        let mainAxisCoord = coords[mainAxis];
        let crossAxisCoord = coords[crossAxis];
        const rawOffset = evaluate(offset4, state);
        const computedOffset = typeof rawOffset === "number" ? {
          mainAxis: rawOffset,
          crossAxis: 0
        } : {
          mainAxis: 0,
          crossAxis: 0,
          ...rawOffset
        };
        if (checkMainAxis) {
          const len = mainAxis === "y" ? "height" : "width";
          const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;
          const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;
          if (mainAxisCoord < limitMin) {
            mainAxisCoord = limitMin;
          } else if (mainAxisCoord > limitMax) {
            mainAxisCoord = limitMax;
          }
        }
        if (checkCrossAxis) {
          var _middlewareData$offse, _middlewareData$offse2;
          const len = mainAxis === "y" ? "width" : "height";
          const isOriginSide = originSides.has(getSide(placement));
          const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);
          const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);
          if (crossAxisCoord < limitMin) {
            crossAxisCoord = limitMin;
          } else if (crossAxisCoord > limitMax) {
            crossAxisCoord = limitMax;
          }
        }
        return {
          [mainAxis]: mainAxisCoord,
          [crossAxis]: crossAxisCoord
        };
      }
    };
  };
  var size = function(options) {
    if (options === void 0) {
      options = {};
    }
    return {
      name: "size",
      options,
      async fn(state) {
        var _state$middlewareData, _state$middlewareData2;
        const {
          placement,
          rects,
          platform: platform3,
          elements: elements2
        } = state;
        const {
          apply = () => {
          },
          ...detectOverflowOptions
        } = evaluate(options, state);
        const overflow = await platform3.detectOverflow(state, detectOverflowOptions);
        const side = getSide(placement);
        const alignment = getAlignment(placement);
        const isYAxis = getSideAxis(placement) === "y";
        const {
          width,
          height
        } = rects.floating;
        let heightSide;
        let widthSide;
        if (side === "top" || side === "bottom") {
          heightSide = side;
          widthSide = alignment === (await (platform3.isRTL == null ? void 0 : platform3.isRTL(elements2.floating)) ? "start" : "end") ? "left" : "right";
        } else {
          widthSide = side;
          heightSide = alignment === "end" ? "top" : "bottom";
        }
        const maximumClippingHeight = height - overflow.top - overflow.bottom;
        const maximumClippingWidth = width - overflow.left - overflow.right;
        const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);
        const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);
        const noShift = !state.middlewareData.shift;
        let availableHeight = overflowAvailableHeight;
        let availableWidth = overflowAvailableWidth;
        if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {
          availableWidth = maximumClippingWidth;
        }
        if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {
          availableHeight = maximumClippingHeight;
        }
        if (noShift && !alignment) {
          const xMin = max(overflow.left, 0);
          const xMax = max(overflow.right, 0);
          const yMin = max(overflow.top, 0);
          const yMax = max(overflow.bottom, 0);
          if (isYAxis) {
            availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));
          } else {
            availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));
          }
        }
        await apply({
          ...state,
          availableWidth,
          availableHeight
        });
        const nextDimensions = await platform3.getDimensions(elements2.floating);
        if (width !== nextDimensions.width || height !== nextDimensions.height) {
          return {
            reset: {
              rects: true
            }
          };
        }
        return {};
      }
    };
  };

  // node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs
  function getCssDimensions(element) {
    const css = getComputedStyle2(element);
    let width = parseFloat(css.width) || 0;
    let height = parseFloat(css.height) || 0;
    const hasOffset = isHTMLElement(element);
    const offsetWidth = hasOffset ? element.offsetWidth : width;
    const offsetHeight = hasOffset ? element.offsetHeight : height;
    const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
    if (shouldFallback) {
      width = offsetWidth;
      height = offsetHeight;
    }
    return {
      width,
      height,
      $: shouldFallback
    };
  }
  function unwrapElement(element) {
    return !isElement(element) ? element.contextElement : element;
  }
  function getScale(element) {
    const domElement = unwrapElement(element);
    if (!isHTMLElement(domElement)) {
      return createCoords(1);
    }
    const rect = domElement.getBoundingClientRect();
    const {
      width,
      height,
      $: $2
    } = getCssDimensions(domElement);
    let x2 = ($2 ? round(rect.width) : rect.width) / width;
    let y2 = ($2 ? round(rect.height) : rect.height) / height;
    if (!x2 || !Number.isFinite(x2)) {
      x2 = 1;
    }
    if (!y2 || !Number.isFinite(y2)) {
      y2 = 1;
    }
    return {
      x: x2,
      y: y2
    };
  }
  var noOffsets = /* @__PURE__ */ createCoords(0);
  function getVisualOffsets(element) {
    const win = getWindow(element);
    if (!isWebKit() || !win.visualViewport) {
      return noOffsets;
    }
    return {
      x: win.visualViewport.offsetLeft,
      y: win.visualViewport.offsetTop
    };
  }
  function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
    if (isFixed === void 0) {
      isFixed = false;
    }
    if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {
      return false;
    }
    return isFixed;
  }
  function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
    if (includeScale === void 0) {
      includeScale = false;
    }
    if (isFixedStrategy === void 0) {
      isFixedStrategy = false;
    }
    const clientRect = element.getBoundingClientRect();
    const domElement = unwrapElement(element);
    let scale = createCoords(1);
    if (includeScale) {
      if (offsetParent) {
        if (isElement(offsetParent)) {
          scale = getScale(offsetParent);
        }
      } else {
        scale = getScale(element);
      }
    }
    const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
    let x2 = (clientRect.left + visualOffsets.x) / scale.x;
    let y2 = (clientRect.top + visualOffsets.y) / scale.y;
    let width = clientRect.width / scale.x;
    let height = clientRect.height / scale.y;
    if (domElement) {
      const win = getWindow(domElement);
      const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
      let currentWin = win;
      let currentIFrame = getFrameElement(currentWin);
      while (currentIFrame && offsetParent && offsetWin !== currentWin) {
        const iframeScale = getScale(currentIFrame);
        const iframeRect = currentIFrame.getBoundingClientRect();
        const css = getComputedStyle2(currentIFrame);
        const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
        const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
        x2 *= iframeScale.x;
        y2 *= iframeScale.y;
        width *= iframeScale.x;
        height *= iframeScale.y;
        x2 += left;
        y2 += top;
        currentWin = getWindow(currentIFrame);
        currentIFrame = getFrameElement(currentWin);
      }
    }
    return rectToClientRect({
      width,
      height,
      x: x2,
      y: y2
    });
  }
  function getWindowScrollBarX(element, rect) {
    const leftScroll = getNodeScroll(element).scrollLeft;
    if (!rect) {
      return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;
    }
    return rect.left + leftScroll;
  }
  function getHTMLOffset(documentElement, scroll) {
    const htmlRect = documentElement.getBoundingClientRect();
    const x2 = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);
    const y2 = htmlRect.top + scroll.scrollTop;
    return {
      x: x2,
      y: y2
    };
  }
  function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
    let {
      elements: elements2,
      rect,
      offsetParent,
      strategy
    } = _ref;
    const isFixed = strategy === "fixed";
    const documentElement = getDocumentElement(offsetParent);
    const topLayer = elements2 ? isTopLayer(elements2.floating) : false;
    if (offsetParent === documentElement || topLayer && isFixed) {
      return rect;
    }
    let scroll = {
      scrollLeft: 0,
      scrollTop: 0
    };
    let scale = createCoords(1);
    const offsets = createCoords(0);
    const isOffsetParentAnElement = isHTMLElement(offsetParent);
    if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
      if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
        scroll = getNodeScroll(offsetParent);
      }
      if (isOffsetParentAnElement) {
        const offsetRect = getBoundingClientRect(offsetParent);
        scale = getScale(offsetParent);
        offsets.x = offsetRect.x + offsetParent.clientLeft;
        offsets.y = offsetRect.y + offsetParent.clientTop;
      }
    }
    const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
    return {
      width: rect.width * scale.x,
      height: rect.height * scale.y,
      x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,
      y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y
    };
  }
  function getClientRects(element) {
    return Array.from(element.getClientRects());
  }
  function getDocumentRect(element) {
    const html = getDocumentElement(element);
    const scroll = getNodeScroll(element);
    const body = element.ownerDocument.body;
    const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
    const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
    let x2 = -scroll.scrollLeft + getWindowScrollBarX(element);
    const y2 = -scroll.scrollTop;
    if (getComputedStyle2(body).direction === "rtl") {
      x2 += max(html.clientWidth, body.clientWidth) - width;
    }
    return {
      width,
      height,
      x: x2,
      y: y2
    };
  }
  var SCROLLBAR_MAX = 25;
  function getViewportRect(element, strategy) {
    const win = getWindow(element);
    const html = getDocumentElement(element);
    const visualViewport = win.visualViewport;
    let width = html.clientWidth;
    let height = html.clientHeight;
    let x2 = 0;
    let y2 = 0;
    if (visualViewport) {
      width = visualViewport.width;
      height = visualViewport.height;
      const visualViewportBased = isWebKit();
      if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
        x2 = visualViewport.offsetLeft;
        y2 = visualViewport.offsetTop;
      }
    }
    const windowScrollbarX = getWindowScrollBarX(html);
    if (windowScrollbarX <= 0) {
      const doc = html.ownerDocument;
      const body = doc.body;
      const bodyStyles = getComputedStyle(body);
      const bodyMarginInline = doc.compatMode === "CSS1Compat" ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;
      const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);
      if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {
        width -= clippingStableScrollbarWidth;
      }
    } else if (windowScrollbarX <= SCROLLBAR_MAX) {
      width += windowScrollbarX;
    }
    return {
      width,
      height,
      x: x2,
      y: y2
    };
  }
  function getInnerBoundingClientRect(element, strategy) {
    const clientRect = getBoundingClientRect(element, true, strategy === "fixed");
    const top = clientRect.top + element.clientTop;
    const left = clientRect.left + element.clientLeft;
    const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
    const width = element.clientWidth * scale.x;
    const height = element.clientHeight * scale.y;
    const x2 = left * scale.x;
    const y2 = top * scale.y;
    return {
      width,
      height,
      x: x2,
      y: y2
    };
  }
  function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
    let rect;
    if (clippingAncestor === "viewport") {
      rect = getViewportRect(element, strategy);
    } else if (clippingAncestor === "document") {
      rect = getDocumentRect(getDocumentElement(element));
    } else if (isElement(clippingAncestor)) {
      rect = getInnerBoundingClientRect(clippingAncestor, strategy);
    } else {
      const visualOffsets = getVisualOffsets(element);
      rect = {
        x: clippingAncestor.x - visualOffsets.x,
        y: clippingAncestor.y - visualOffsets.y,
        width: clippingAncestor.width,
        height: clippingAncestor.height
      };
    }
    return rectToClientRect(rect);
  }
  function hasFixedPositionAncestor(element, stopNode) {
    const parentNode = getParentNode(element);
    if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
      return false;
    }
    return getComputedStyle2(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode);
  }
  function getClippingElementAncestors(element, cache) {
    const cachedResult = cache.get(element);
    if (cachedResult) {
      return cachedResult;
    }
    let result = getOverflowAncestors(element, [], false).filter((el) => isElement(el) && getNodeName(el) !== "body");
    let currentContainingBlockComputedStyle = null;
    const elementIsFixed = getComputedStyle2(element).position === "fixed";
    let currentNode = elementIsFixed ? getParentNode(element) : element;
    while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
      const computedStyle = getComputedStyle2(currentNode);
      const currentNodeIsContaining = isContainingBlock(currentNode);
      if (!currentNodeIsContaining && computedStyle.position === "fixed") {
        currentContainingBlockComputedStyle = null;
      }
      const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && (currentContainingBlockComputedStyle.position === "absolute" || currentContainingBlockComputedStyle.position === "fixed") || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
      if (shouldDropCurrentNode) {
        result = result.filter((ancestor) => ancestor !== currentNode);
      } else {
        currentContainingBlockComputedStyle = computedStyle;
      }
      currentNode = getParentNode(currentNode);
    }
    cache.set(element, result);
    return result;
  }
  function getClippingRect(_ref) {
    let {
      element,
      boundary,
      rootBoundary,
      strategy
    } = _ref;
    const elementClippingAncestors = boundary === "clippingAncestors" ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);
    const clippingAncestors = [...elementClippingAncestors, rootBoundary];
    const firstRect = getClientRectFromClippingAncestor(element, clippingAncestors[0], strategy);
    let top = firstRect.top;
    let right = firstRect.right;
    let bottom = firstRect.bottom;
    let left = firstRect.left;
    for (let i2 = 1; i2 < clippingAncestors.length; i2++) {
      const rect = getClientRectFromClippingAncestor(element, clippingAncestors[i2], strategy);
      top = max(rect.top, top);
      right = min(rect.right, right);
      bottom = min(rect.bottom, bottom);
      left = max(rect.left, left);
    }
    return {
      width: right - left,
      height: bottom - top,
      x: left,
      y: top
    };
  }
  function getDimensions2(element) {
    const {
      width,
      height
    } = getCssDimensions(element);
    return {
      width,
      height
    };
  }
  function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
    const isOffsetParentAnElement = isHTMLElement(offsetParent);
    const documentElement = getDocumentElement(offsetParent);
    const isFixed = strategy === "fixed";
    const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
    let scroll = {
      scrollLeft: 0,
      scrollTop: 0
    };
    const offsets = createCoords(0);
    function setLeftRTLScrollbarOffset() {
      offsets.x = getWindowScrollBarX(documentElement);
    }
    if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
      if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
        scroll = getNodeScroll(offsetParent);
      }
      if (isOffsetParentAnElement) {
        const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
        offsets.x = offsetRect.x + offsetParent.clientLeft;
        offsets.y = offsetRect.y + offsetParent.clientTop;
      } else if (documentElement) {
        setLeftRTLScrollbarOffset();
      }
    }
    if (isFixed && !isOffsetParentAnElement && documentElement) {
      setLeftRTLScrollbarOffset();
    }
    const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
    const x2 = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;
    const y2 = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;
    return {
      x: x2,
      y: y2,
      width: rect.width,
      height: rect.height
    };
  }
  function isStaticPositioned(element) {
    return getComputedStyle2(element).position === "static";
  }
  function getTrueOffsetParent(element, polyfill) {
    if (!isHTMLElement(element) || getComputedStyle2(element).position === "fixed") {
      return null;
    }
    if (polyfill) {
      return polyfill(element);
    }
    let rawOffsetParent = element.offsetParent;
    if (getDocumentElement(element) === rawOffsetParent) {
      rawOffsetParent = rawOffsetParent.ownerDocument.body;
    }
    return rawOffsetParent;
  }
  function getOffsetParent(element, polyfill) {
    const win = getWindow(element);
    if (isTopLayer(element)) {
      return win;
    }
    if (!isHTMLElement(element)) {
      let svgOffsetParent = getParentNode(element);
      while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
        if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
          return svgOffsetParent;
        }
        svgOffsetParent = getParentNode(svgOffsetParent);
      }
      return win;
    }
    let offsetParent = getTrueOffsetParent(element, polyfill);
    while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
      offsetParent = getTrueOffsetParent(offsetParent, polyfill);
    }
    if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
      return win;
    }
    return offsetParent || getContainingBlock(element) || win;
  }
  var getElementRects = async function(data) {
    const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
    const getDimensionsFn = this.getDimensions;
    const floatingDimensions = await getDimensionsFn(data.floating);
    return {
      reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
      floating: {
        x: 0,
        y: 0,
        width: floatingDimensions.width,
        height: floatingDimensions.height
      }
    };
  };
  function isRTL(element) {
    return getComputedStyle2(element).direction === "rtl";
  }
  var platform2 = {
    convertOffsetParentRelativeRectToViewportRelativeRect,
    getDocumentElement,
    getClippingRect,
    getOffsetParent,
    getElementRects,
    getClientRects,
    getDimensions: getDimensions2,
    getScale,
    isElement,
    isRTL
  };
  function rectsAreEqual(a2, b2) {
    return a2.x === b2.x && a2.y === b2.y && a2.width === b2.width && a2.height === b2.height;
  }
  function observeMove(element, onMove) {
    let io = null;
    let timeoutId;
    const root = getDocumentElement(element);
    function cleanup() {
      var _io;
      clearTimeout(timeoutId);
      (_io = io) == null || _io.disconnect();
      io = null;
    }
    function refresh(skip, threshold) {
      if (skip === void 0) {
        skip = false;
      }
      if (threshold === void 0) {
        threshold = 1;
      }
      cleanup();
      const elementRectForRootMargin = element.getBoundingClientRect();
      const {
        left,
        top,
        width,
        height
      } = elementRectForRootMargin;
      if (!skip) {
        onMove();
      }
      if (!width || !height) {
        return;
      }
      const insetTop = floor(top);
      const insetRight = floor(root.clientWidth - (left + width));
      const insetBottom = floor(root.clientHeight - (top + height));
      const insetLeft = floor(left);
      const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
      const options = {
        rootMargin,
        threshold: max(0, min(1, threshold)) || 1
      };
      let isFirstUpdate = true;
      function handleObserve(entries) {
        const ratio = entries[0].intersectionRatio;
        if (ratio !== threshold) {
          if (!isFirstUpdate) {
            return refresh();
          }
          if (!ratio) {
            timeoutId = setTimeout(() => {
              refresh(false, 1e-7);
            }, 1e3);
          } else {
            refresh(false, ratio);
          }
        }
        if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) {
          refresh();
        }
        isFirstUpdate = false;
      }
      try {
        io = new IntersectionObserver(handleObserve, {
          ...options,
          // Handle <iframe>s
          root: root.ownerDocument
        });
      } catch (_e) {
        io = new IntersectionObserver(handleObserve, options);
      }
      io.observe(element);
    }
    refresh(true);
    return cleanup;
  }
  function autoUpdate(reference, floating, update4, options) {
    if (options === void 0) {
      options = {};
    }
    const {
      ancestorScroll = true,
      ancestorResize = true,
      elementResize = typeof ResizeObserver === "function",
      layoutShift = typeof IntersectionObserver === "function",
      animationFrame = false
    } = options;
    const referenceEl = unwrapElement(reference);
    const ancestors = ancestorScroll || ancestorResize ? [...referenceEl ? getOverflowAncestors(referenceEl) : [], ...floating ? getOverflowAncestors(floating) : []] : [];
    ancestors.forEach((ancestor) => {
      ancestorScroll && ancestor.addEventListener("scroll", update4, {
        passive: true
      });
      ancestorResize && ancestor.addEventListener("resize", update4);
    });
    const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update4) : null;
    let reobserveFrame = -1;
    let resizeObserver = null;
    if (elementResize) {
      resizeObserver = new ResizeObserver((_ref) => {
        let [firstEntry] = _ref;
        if (firstEntry && firstEntry.target === referenceEl && resizeObserver && floating) {
          resizeObserver.unobserve(floating);
          cancelAnimationFrame(reobserveFrame);
          reobserveFrame = requestAnimationFrame(() => {
            var _resizeObserver;
            (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
          });
        }
        update4();
      });
      if (referenceEl && !animationFrame) {
        resizeObserver.observe(referenceEl);
      }
      if (floating) {
        resizeObserver.observe(floating);
      }
    }
    let frameId;
    let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
    if (animationFrame) {
      frameLoop2();
    }
    function frameLoop2() {
      const nextRefRect = getBoundingClientRect(reference);
      if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {
        update4();
      }
      prevRefRect = nextRefRect;
      frameId = requestAnimationFrame(frameLoop2);
    }
    update4();
    return () => {
      var _resizeObserver2;
      ancestors.forEach((ancestor) => {
        ancestorScroll && ancestor.removeEventListener("scroll", update4);
        ancestorResize && ancestor.removeEventListener("resize", update4);
      });
      cleanupIo == null || cleanupIo();
      (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
      resizeObserver = null;
      if (animationFrame) {
        cancelAnimationFrame(frameId);
      }
    };
  }
  var offset2 = offset;
  var shift2 = shift;
  var flip2 = flip;
  var size2 = size;
  var hide2 = hide;
  var limitShift2 = limitShift;
  var computePosition2 = (reference, floating, options) => {
    const cache = /* @__PURE__ */ new Map();
    const mergedOptions = {
      platform: platform2,
      ...options
    };
    const platformWithCache = {
      ...mergedOptions.platform,
      _c: cache
    };
    return computePosition(reference, floating, {
      ...mergedOptions,
      platform: platformWithCache
    });
  };

  // node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs
  var React26 = __toESM(require_react(), 1);
  var import_react2 = __toESM(require_react(), 1);
  var ReactDOM3 = __toESM(require_react_dom(), 1);
  var isClient = typeof document !== "undefined";
  var noop2 = function noop3() {
  };
  var index = isClient ? import_react2.useLayoutEffect : noop2;
  function deepEqual(a2, b2) {
    if (a2 === b2) {
      return true;
    }
    if (typeof a2 !== typeof b2) {
      return false;
    }
    if (typeof a2 === "function" && a2.toString() === b2.toString()) {
      return true;
    }
    let length;
    let i2;
    let keys;
    if (a2 && b2 && typeof a2 === "object") {
      if (Array.isArray(a2)) {
        length = a2.length;
        if (length !== b2.length) return false;
        for (i2 = length; i2-- !== 0; ) {
          if (!deepEqual(a2[i2], b2[i2])) {
            return false;
          }
        }
        return true;
      }
      keys = Object.keys(a2);
      length = keys.length;
      if (length !== Object.keys(b2).length) {
        return false;
      }
      for (i2 = length; i2-- !== 0; ) {
        if (!{}.hasOwnProperty.call(b2, keys[i2])) {
          return false;
        }
      }
      for (i2 = length; i2-- !== 0; ) {
        const key = keys[i2];
        if (key === "_owner" && a2.$$typeof) {
          continue;
        }
        if (!deepEqual(a2[key], b2[key])) {
          return false;
        }
      }
      return true;
    }
    return a2 !== a2 && b2 !== b2;
  }
  function getDPR(element) {
    if (typeof window === "undefined") {
      return 1;
    }
    const win = element.ownerDocument.defaultView || window;
    return win.devicePixelRatio || 1;
  }
  function roundByDPR(element, value) {
    const dpr = getDPR(element);
    return Math.round(value * dpr) / dpr;
  }
  function useLatestRef(value) {
    const ref = React26.useRef(value);
    index(() => {
      ref.current = value;
    });
    return ref;
  }
  function useFloating(options) {
    if (options === void 0) {
      options = {};
    }
    const {
      placement = "bottom",
      strategy = "absolute",
      middleware = [],
      platform: platform3,
      elements: {
        reference: externalReference,
        floating: externalFloating
      } = {},
      transform = true,
      whileElementsMounted,
      open
    } = options;
    const [data, setData] = React26.useState({
      x: 0,
      y: 0,
      strategy,
      placement,
      middlewareData: {},
      isPositioned: false
    });
    const [latestMiddleware, setLatestMiddleware] = React26.useState(middleware);
    if (!deepEqual(latestMiddleware, middleware)) {
      setLatestMiddleware(middleware);
    }
    const [_reference, _setReference] = React26.useState(null);
    const [_floating, _setFloating] = React26.useState(null);
    const setReference = React26.useCallback((node) => {
      if (node !== referenceRef.current) {
        referenceRef.current = node;
        _setReference(node);
      }
    }, []);
    const setFloating = React26.useCallback((node) => {
      if (node !== floatingRef.current) {
        floatingRef.current = node;
        _setFloating(node);
      }
    }, []);
    const referenceEl = externalReference || _reference;
    const floatingEl = externalFloating || _floating;
    const referenceRef = React26.useRef(null);
    const floatingRef = React26.useRef(null);
    const dataRef = React26.useRef(data);
    const hasWhileElementsMounted = whileElementsMounted != null;
    const whileElementsMountedRef = useLatestRef(whileElementsMounted);
    const platformRef = useLatestRef(platform3);
    const openRef = useLatestRef(open);
    const update4 = React26.useCallback(() => {
      if (!referenceRef.current || !floatingRef.current) {
        return;
      }
      const config2 = {
        placement,
        strategy,
        middleware: latestMiddleware
      };
      if (platformRef.current) {
        config2.platform = platformRef.current;
      }
      computePosition2(referenceRef.current, floatingRef.current, config2).then((data2) => {
        const fullData = {
          ...data2,
          // The floating element's position may be recomputed while it's closed
          // but still mounted (such as when transitioning out). To ensure
          // `isPositioned` will be `false` initially on the next open, avoid
          // setting it to `true` when `open === false` (must be specified).
          isPositioned: openRef.current !== false
        };
        if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
          dataRef.current = fullData;
          ReactDOM3.flushSync(() => {
            setData(fullData);
          });
        }
      });
    }, [latestMiddleware, placement, strategy, platformRef, openRef]);
    index(() => {
      if (open === false && dataRef.current.isPositioned) {
        dataRef.current.isPositioned = false;
        setData((data2) => ({
          ...data2,
          isPositioned: false
        }));
      }
    }, [open]);
    const isMountedRef = React26.useRef(false);
    index(() => {
      isMountedRef.current = true;
      return () => {
        isMountedRef.current = false;
      };
    }, []);
    index(() => {
      if (referenceEl) referenceRef.current = referenceEl;
      if (floatingEl) floatingRef.current = floatingEl;
      if (referenceEl && floatingEl) {
        if (whileElementsMountedRef.current) {
          return whileElementsMountedRef.current(referenceEl, floatingEl, update4);
        }
        update4();
      }
    }, [referenceEl, floatingEl, update4, whileElementsMountedRef, hasWhileElementsMounted]);
    const refs = React26.useMemo(() => ({
      reference: referenceRef,
      floating: floatingRef,
      setReference,
      setFloating
    }), [setReference, setFloating]);
    const elements2 = React26.useMemo(() => ({
      reference: referenceEl,
      floating: floatingEl
    }), [referenceEl, floatingEl]);
    const floatingStyles = React26.useMemo(() => {
      const initialStyles = {
        position: strategy,
        left: 0,
        top: 0
      };
      if (!elements2.floating) {
        return initialStyles;
      }
      const x2 = roundByDPR(elements2.floating, data.x);
      const y2 = roundByDPR(elements2.floating, data.y);
      if (transform) {
        return {
          ...initialStyles,
          transform: "translate(" + x2 + "px, " + y2 + "px)",
          ...getDPR(elements2.floating) >= 1.5 && {
            willChange: "transform"
          }
        };
      }
      return {
        position: strategy,
        left: x2,
        top: y2
      };
    }, [strategy, transform, elements2.floating, data.x, data.y]);
    return React26.useMemo(() => ({
      ...data,
      update: update4,
      refs,
      elements: elements2,
      floatingStyles
    }), [data, update4, refs, elements2, floatingStyles]);
  }
  var offset3 = (options, deps) => {
    const result = offset2(options);
    return {
      name: result.name,
      fn: result.fn,
      options: [options, deps]
    };
  };
  var shift3 = (options, deps) => {
    const result = shift2(options);
    return {
      name: result.name,
      fn: result.fn,
      options: [options, deps]
    };
  };
  var limitShift3 = (options, deps) => {
    const result = limitShift2(options);
    return {
      fn: result.fn,
      options: [options, deps]
    };
  };
  var flip3 = (options, deps) => {
    const result = flip2(options);
    return {
      name: result.name,
      fn: result.fn,
      options: [options, deps]
    };
  };
  var size3 = (options, deps) => {
    const result = size2(options);
    return {
      name: result.name,
      fn: result.fn,
      options: [options, deps]
    };
  };
  var hide3 = (options, deps) => {
    const result = hide2(options);
    return {
      name: result.name,
      fn: result.fn,
      options: [options, deps]
    };
  };

  // node_modules/@base-ui/react/utils/popups/popupStoreUtils.mjs
  var React31 = __toESM(require_react(), 1);
  var ReactDOM4 = __toESM(require_react_dom(), 1);

  // node_modules/@base-ui/react/floating-ui-react/hooks/useSyncedFloatingRootContext.mjs
  var React30 = __toESM(require_react(), 1);

  // node_modules/@base-ui/utils/store/createSelector.mjs
  var createSelector2 = (a2, b2, c6, d2, e2, f2, ...other) => {
    if (other.length > 0) {
      throw new Error(true ? "Unsupported number of selectors" : formatErrorMessage_default(1));
    }
    let selector2;
    if (a2 && b2 && c6 && d2 && e2 && f2) {
      selector2 = (state, a1, a22, a3) => {
        const va = a2(state, a1, a22, a3);
        const vb = b2(state, a1, a22, a3);
        const vc = c6(state, a1, a22, a3);
        const vd = d2(state, a1, a22, a3);
        const ve = e2(state, a1, a22, a3);
        return f2(va, vb, vc, vd, ve, a1, a22, a3);
      };
    } else if (a2 && b2 && c6 && d2 && e2) {
      selector2 = (state, a1, a22, a3) => {
        const va = a2(state, a1, a22, a3);
        const vb = b2(state, a1, a22, a3);
        const vc = c6(state, a1, a22, a3);
        const vd = d2(state, a1, a22, a3);
        return e2(va, vb, vc, vd, a1, a22, a3);
      };
    } else if (a2 && b2 && c6 && d2) {
      selector2 = (state, a1, a22, a3) => {
        const va = a2(state, a1, a22, a3);
        const vb = b2(state, a1, a22, a3);
        const vc = c6(state, a1, a22, a3);
        return d2(va, vb, vc, a1, a22, a3);
      };
    } else if (a2 && b2 && c6) {
      selector2 = (state, a1, a22, a3) => {
        const va = a2(state, a1, a22, a3);
        const vb = b2(state, a1, a22, a3);
        return c6(va, vb, a1, a22, a3);
      };
    } else if (a2 && b2) {
      selector2 = (state, a1, a22, a3) => {
        const va = a2(state, a1, a22, a3);
        return b2(va, a1, a22, a3);
      };
    } else if (a2) {
      selector2 = a2;
    } else {
      throw (
        /* minify-error-disabled */
        new Error("Missing arguments")
      );
    }
    return selector2;
  };

  // node_modules/@base-ui/utils/store/useStore.mjs
  var React28 = __toESM(require_react(), 1);
  var import_shim = __toESM(require_shim(), 1);
  var import_with_selector = __toESM(require_with_selector(), 1);

  // node_modules/@base-ui/utils/fastHooks.mjs
  var React27 = __toESM(require_react(), 1);
  var hooks = [];
  var currentInstance = void 0;
  function getInstance() {
    return currentInstance;
  }
  function register2(hook) {
    hooks.push(hook);
  }
  function fastComponent(fn) {
    const FastComponent = (props, forwardedRef) => {
      const instance = useRefWithInit(createInstance).current;
      let result;
      try {
        currentInstance = instance;
        for (const hook of hooks) {
          hook.before(instance);
        }
        result = fn(props, forwardedRef);
        for (const hook of hooks) {
          hook.after(instance);
        }
        instance.didInitialize = true;
      } finally {
        currentInstance = void 0;
      }
      return result;
    };
    FastComponent.displayName = fn.displayName || fn.name;
    return FastComponent;
  }
  function fastComponentRef(fn) {
    return /* @__PURE__ */ React27.forwardRef(fastComponent(fn));
  }
  function createInstance() {
    return {
      didInitialize: false
    };
  }

  // node_modules/@base-ui/utils/store/useStore.mjs
  var canUseRawUseSyncExternalStore = isReactVersionAtLeast(19);
  var useStoreImplementation = canUseRawUseSyncExternalStore ? useStoreFast : useStoreLegacy;
  function useStore(store2, selector2, a1, a2, a3) {
    return useStoreImplementation(store2, selector2, a1, a2, a3);
  }
  function useStoreR19(store2, selector2, a1, a2, a3) {
    const getSelection = React28.useCallback(() => selector2(store2.getSnapshot(), a1, a2, a3), [store2, selector2, a1, a2, a3]);
    return (0, import_shim.useSyncExternalStore)(store2.subscribe, getSelection, getSelection);
  }
  register2({
    before(instance) {
      instance.syncIndex = 0;
      if (!instance.didInitialize) {
        instance.syncTick = 1;
        instance.syncHooks = [];
        instance.didChangeStore = true;
        instance.getSnapshot = () => {
          let didChange2 = false;
          for (let i2 = 0; i2 < instance.syncHooks.length; i2 += 1) {
            const hook = instance.syncHooks[i2];
            const value = hook.selector(hook.store.state, hook.a1, hook.a2, hook.a3);
            if (!Object.is(hook.value, value)) {
              didChange2 = true;
              hook.value = value;
            }
          }
          if (didChange2) {
            instance.syncTick += 1;
          }
          return instance.syncTick;
        };
      }
    },
    after(instance) {
      if (instance.syncHooks.length > 0) {
        if (instance.didChangeStore) {
          instance.didChangeStore = false;
          instance.subscribe = (onStoreChange) => {
            const stores = /* @__PURE__ */ new Set();
            for (const hook of instance.syncHooks) {
              stores.add(hook.store);
            }
            const unsubscribes = [];
            for (const store2 of stores) {
              unsubscribes.push(store2.subscribe(onStoreChange));
            }
            return () => {
              for (const unsubscribe of unsubscribes) {
                unsubscribe();
              }
            };
          };
        }
        (0, import_shim.useSyncExternalStore)(instance.subscribe, instance.getSnapshot, instance.getSnapshot);
      }
    }
  });
  function useStoreFast(store2, selector2, a1, a2, a3) {
    const instance = getInstance();
    if (!instance) {
      return useStoreR19(store2, selector2, a1, a2, a3);
    }
    const index2 = instance.syncIndex;
    instance.syncIndex += 1;
    let hook;
    if (!instance.didInitialize) {
      hook = {
        store: store2,
        selector: selector2,
        a1,
        a2,
        a3,
        value: selector2(store2.getSnapshot(), a1, a2, a3)
      };
      instance.syncHooks.push(hook);
    } else {
      hook = instance.syncHooks[index2];
      if (hook.store !== store2 || hook.selector !== selector2 || !Object.is(hook.a1, a1) || !Object.is(hook.a2, a2) || !Object.is(hook.a3, a3)) {
        if (hook.store !== store2) {
          instance.didChangeStore = true;
        }
        hook.store = store2;
        hook.selector = selector2;
        hook.a1 = a1;
        hook.a2 = a2;
        hook.a3 = a3;
        hook.value = selector2(store2.getSnapshot(), a1, a2, a3);
      }
    }
    return hook.value;
  }
  function useStoreLegacy(store2, selector2, a1, a2, a3) {
    return (0, import_with_selector.useSyncExternalStoreWithSelector)(store2.subscribe, store2.getSnapshot, store2.getSnapshot, (state) => selector2(state, a1, a2, a3));
  }

  // node_modules/@base-ui/utils/store/Store.mjs
  var Store = class {
    /**
     * The current state of the store.
     * This property is updated immediately when the state changes as a result of calling {@link setState}, {@link update}, or {@link set}.
     * To subscribe to state changes, use the {@link useState} method. The value returned by {@link useState} is updated after the component renders (similarly to React's useState).
     * The values can be used directly (to avoid subscribing to the store) in effects or event handlers.
     *
     * Do not modify properties in state directly. Instead, use the provided methods to ensure proper state management and listener notification.
     */
    // Internal state to handle recursive `setState()` calls
    constructor(state) {
      this.state = state;
      this.listeners = /* @__PURE__ */ new Set();
      this.updateTick = 0;
    }
    /**
     * Registers a listener that will be called whenever the store's state changes.
     *
     * @param fn The listener function to be called on state changes.
     * @returns A function to unsubscribe the listener.
     */
    subscribe = (fn) => {
      this.listeners.add(fn);
      return () => {
        this.listeners.delete(fn);
      };
    };
    /**
     * Returns the current state of the store.
     */
    getSnapshot = () => {
      return this.state;
    };
    /**
     * Updates the entire store's state and notifies all registered listeners.
     *
     * @param newState The new state to set for the store.
     */
    setState(newState) {
      if (this.state === newState) {
        return;
      }
      this.state = newState;
      this.updateTick += 1;
      const currentTick = this.updateTick;
      for (const listener of this.listeners) {
        if (currentTick !== this.updateTick) {
          return;
        }
        listener(newState);
      }
    }
    /**
     * Merges the provided changes into the current state and notifies listeners if there are changes.
     *
     * @param changes An object containing the changes to apply to the current state.
     */
    update(changes) {
      for (const key in changes) {
        if (!Object.is(this.state[key], changes[key])) {
          this.setState({
            ...this.state,
            ...changes
          });
          return;
        }
      }
    }
    /**
     * Sets a specific key in the store's state to a new value and notifies listeners if the value has changed.
     *
     * @param key The key in the store's state to update.
     * @param value The new value to set for the specified key.
     */
    set(key, value) {
      if (!Object.is(this.state[key], value)) {
        this.setState({
          ...this.state,
          [key]: value
        });
      }
    }
    /**
     * Gives the state a new reference and updates all registered listeners.
     */
    notifyAll() {
      const newState = {
        ...this.state
      };
      this.setState(newState);
    }
    use(selector2, a1, a2, a3) {
      return useStore(this, selector2, a1, a2, a3);
    }
  };

  // node_modules/@base-ui/utils/store/ReactStore.mjs
  var React29 = __toESM(require_react(), 1);
  var ReactStore = class extends Store {
    /**
     * Creates a new ReactStore instance.
     *
     * @param state Initial state of the store.
     * @param context Non-reactive context values.
     * @param selectors Optional selectors for use with `useState`.
     */
    constructor(state, context = {}, selectors3) {
      super(state);
      this.context = context;
      this.selectors = selectors3;
    }
    /**
     * Non-reactive values such as refs, callbacks, etc.
     */
    /**
     * Synchronizes a single external value into the store.
     *
     * Note that the while the value in `state` is updated immediately, the value returned
     * by `useState` is updated before the next render (similarly to React's `useState`).
     */
    useSyncedValue(key, value) {
      React29.useDebugValue(key);
      const store2 = this;
      useIsoLayoutEffect(() => {
        if (store2.state[key] !== value) {
          store2.set(key, value);
        }
      }, [store2, key, value]);
    }
    /**
     * Synchronizes a single external value into the store and
     * cleans it up (sets to `undefined`) on unmount.
     *
     * Note that the while the value in `state` is updated immediately, the value returned
     * by `useState` is updated before the next render (similarly to React's `useState`).
     */
    useSyncedValueWithCleanup(key, value) {
      const store2 = this;
      useIsoLayoutEffect(() => {
        if (store2.state[key] !== value) {
          store2.set(key, value);
        }
        return () => {
          store2.set(key, void 0);
        };
      }, [store2, key, value]);
    }
    /**
     * Synchronizes multiple external values into the store.
     *
     * Note that the while the values in `state` are updated immediately, the values returned
     * by `useState` are updated before the next render (similarly to React's `useState`).
     */
    useSyncedValues(statePart) {
      const store2 = this;
      if (true) {
        React29.useDebugValue(statePart, (p3) => Object.keys(p3));
        const keys = React29.useRef(Object.keys(statePart)).current;
        const nextKeys = Object.keys(statePart);
        if (keys.length !== nextKeys.length || keys.some((key, index2) => key !== nextKeys[index2])) {
          console.error("ReactStore.useSyncedValues expects the same prop keys on every render. Keys should be stable.");
        }
      }
      const dependencies = Object.values(statePart);
      useIsoLayoutEffect(() => {
        store2.update(statePart);
      }, [store2, ...dependencies]);
    }
    /**
     * Registers a controllable prop pair (`controlled`, `defaultValue`) for a specific key. If `controlled`
     * is non-undefined, the store's state at `key` is updated to match `controlled`.
     */
    useControlledProp(key, controlled) {
      React29.useDebugValue(key);
      const store2 = this;
      const isControlled = controlled !== void 0;
      useIsoLayoutEffect(() => {
        if (isControlled && !Object.is(store2.state[key], controlled)) {
          store2.setState({
            ...store2.state,
            [key]: controlled
          });
        }
      }, [store2, key, controlled, isControlled]);
      if (true) {
        const cache = this.controlledValues ??= /* @__PURE__ */ new Map();
        if (!cache.has(key)) {
          cache.set(key, isControlled);
        }
        const previouslyControlled = cache.get(key);
        if (previouslyControlled !== void 0 && previouslyControlled !== isControlled) {
          console.error(`A component is changing the ${isControlled ? "" : "un"}controlled state of ${key.toString()} to be ${isControlled ? "un" : ""}controlled. Elements should not switch from uncontrolled to controlled (or vice versa).`);
        }
      }
    }
    /** Gets the current value from the store using a selector with the provided key.
     *
     * @param key Key of the selector to use.
     */
    select(key, a1, a2, a3) {
      const selector2 = this.selectors[key];
      return selector2(this.state, a1, a2, a3);
    }
    /**
     * Returns a value from the store's state using a selector function.
     * Used to subscribe to specific parts of the state.
     * This methods causes a rerender whenever the selected state changes.
     *
     * @param key Key of the selector to use.
     */
    useState(key, a1, a2, a3) {
      React29.useDebugValue(key);
      return useStore(this, this.selectors[key], a1, a2, a3);
    }
    /**
     * Wraps a function with `useStableCallback` to ensure it has a stable reference
     * and assigns it to the context.
     *
     * @param key Key of the event callback. Must be a function in the context.
     * @param fn Function to assign.
     */
    useContextCallback(key, fn) {
      React29.useDebugValue(key);
      const stableFunction = useStableCallback(fn ?? NOOP);
      this.context[key] = stableFunction;
    }
    /**
     * Returns a stable setter function for a specific key in the store's state.
     * It's commonly used to pass as a ref callback to React elements.
     *
     * @param key Key of the state to set.
     */
    useStateSetter(key) {
      const ref = React29.useRef(void 0);
      if (ref.current === void 0) {
        ref.current = (value) => {
          this.set(key, value);
        };
      }
      return ref.current;
    }
    /**
     * Observes changes derived from the store's selectors and calls the listener when the selected value changes.
     *
     * @param key Key of the selector to observe.
     * @param listener Listener function called when the selector result changes.
     */
    observe(selector2, listener) {
      let selectFn;
      if (typeof selector2 === "function") {
        selectFn = selector2;
      } else {
        selectFn = this.selectors[selector2];
      }
      let prevValue = selectFn(this.state);
      listener(prevValue, prevValue, this);
      return this.subscribe((nextState) => {
        const nextValue = selectFn(nextState);
        if (!Object.is(prevValue, nextValue)) {
          const oldValue = prevValue;
          prevValue = nextValue;
          listener(nextValue, oldValue, this);
        }
      });
    }
  };

  // node_modules/@base-ui/react/floating-ui-react/components/FloatingRootStore.mjs
  var selectors = {
    open: createSelector2((state) => state.open),
    transitionStatus: createSelector2((state) => state.transitionStatus),
    domReferenceElement: createSelector2((state) => state.domReferenceElement),
    referenceElement: createSelector2((state) => state.positionReference ?? state.referenceElement),
    floatingElement: createSelector2((state) => state.floatingElement),
    floatingId: createSelector2((state) => state.floatingId)
  };
  var FloatingRootStore = class extends ReactStore {
    constructor(options) {
      const {
        syncOnly,
        nested,
        onOpenChange,
        triggerElements,
        ...initialState
      } = options;
      super({
        ...initialState,
        positionReference: initialState.referenceElement,
        domReferenceElement: initialState.referenceElement
      }, {
        onOpenChange,
        dataRef: {
          current: {}
        },
        events: createEventEmitter(),
        nested,
        triggerElements
      }, selectors);
      this.syncOnly = syncOnly;
    }
    /**
     * Syncs the event used by hover logic to distinguish hover-open from click-like interaction.
     */
    syncOpenEvent = (newOpen, event) => {
      if (!newOpen || !this.state.open || // Prevent a pending hover-open from overwriting a click-open event, while allowing
      // click events to upgrade a hover-open.
      event != null && isClickLikeEvent(event)) {
        this.context.dataRef.current.openEvent = newOpen ? event : void 0;
      }
    };
    /**
     * Runs the root-owned side effects for an open state change.
     */
    dispatchOpenChange = (newOpen, eventDetails) => {
      this.syncOpenEvent(newOpen, eventDetails.event);
      const details = {
        open: newOpen,
        reason: eventDetails.reason,
        nativeEvent: eventDetails.event,
        nested: this.context.nested,
        triggerElement: eventDetails.trigger
      };
      this.context.events.emit("openchange", details);
    };
    /**
     * Emits the `openchange` event through the internal event emitter and calls the `onOpenChange` handler with the provided arguments.
     *
     * @param newOpen The new open state.
     * @param eventDetails Details about the event that triggered the open state change.
     */
    setOpen = (newOpen, eventDetails) => {
      if (this.syncOnly) {
        this.context.onOpenChange?.(newOpen, eventDetails);
        return;
      }
      this.dispatchOpenChange(newOpen, eventDetails);
      this.context.onOpenChange?.(newOpen, eventDetails);
    };
  };

  // node_modules/@base-ui/react/floating-ui-react/hooks/useSyncedFloatingRootContext.mjs
  function useSyncedFloatingRootContext(options) {
    const {
      popupStore,
      treatPopupAsFloatingElement = false,
      floatingRootContext: floatingRootContextProp,
      floatingId,
      nested,
      onOpenChange
    } = options;
    const open = popupStore.useState("open");
    const referenceElement = popupStore.useState("activeTriggerElement");
    const floatingElement = popupStore.useState(treatPopupAsFloatingElement ? "popupElement" : "positionerElement");
    const triggerElements = popupStore.context.triggerElements;
    const handleOpenChange = onOpenChange;
    const internalStoreRef = React30.useRef(null);
    if (floatingRootContextProp === void 0 && internalStoreRef.current === null) {
      internalStoreRef.current = new FloatingRootStore({
        open,
        transitionStatus: void 0,
        referenceElement,
        floatingElement,
        triggerElements,
        onOpenChange: handleOpenChange,
        floatingId,
        syncOnly: true,
        nested
      });
    }
    const store2 = floatingRootContextProp ?? internalStoreRef.current;
    popupStore.useSyncedValue("floatingId", floatingId);
    useIsoLayoutEffect(() => {
      const valuesToSync = {
        open,
        floatingId,
        referenceElement,
        floatingElement
      };
      if (isElement(referenceElement)) {
        valuesToSync.domReferenceElement = referenceElement;
      }
      if (store2.state.positionReference === store2.state.referenceElement) {
        valuesToSync.positionReference = referenceElement;
      }
      store2.update(valuesToSync);
    }, [open, floatingId, referenceElement, floatingElement, store2]);
    store2.context.onOpenChange = handleOpenChange;
    store2.context.nested = nested;
    return store2;
  }

  // node_modules/@base-ui/react/utils/popups/popupStoreUtils.mjs
  var FOCUSABLE_POPUP_PROPS = {
    tabIndex: -1,
    [FOCUSABLE_ATTRIBUTE]: ""
  };
  function usePopupStore(externalStore, createStore2, treatPopupAsFloatingElement = false) {
    const floatingId = useId();
    const nested = useFloatingParentNodeId() != null;
    const internalStoreRef = React31.useRef(null);
    if (externalStore === void 0 && internalStoreRef.current === null) {
      internalStoreRef.current = createStore2(floatingId, nested);
    }
    const store2 = externalStore ?? internalStoreRef.current;
    useSyncedFloatingRootContext({
      popupStore: store2,
      treatPopupAsFloatingElement,
      floatingRootContext: store2.state.floatingRootContext,
      floatingId,
      nested,
      onOpenChange: store2.setOpen
    });
    return {
      store: store2,
      internalStore: internalStoreRef.current
    };
  }
  function useTriggerRegistration(id, store2) {
    const registeredElementIdRef = React31.useRef(null);
    const registeredElementRef = React31.useRef(null);
    return React31.useCallback((element) => {
      if (id === void 0) {
        return;
      }
      let shouldSyncTriggerCount = false;
      if (registeredElementIdRef.current !== null) {
        const registeredId = registeredElementIdRef.current;
        const registeredElement = registeredElementRef.current;
        const currentElement = store2.context.triggerElements.getById(registeredId);
        if (registeredElement && currentElement === registeredElement) {
          store2.context.triggerElements.delete(registeredId);
          shouldSyncTriggerCount = true;
        }
        registeredElementIdRef.current = null;
        registeredElementRef.current = null;
      }
      if (element !== null) {
        registeredElementIdRef.current = id;
        registeredElementRef.current = element;
        store2.context.triggerElements.add(id, element);
        shouldSyncTriggerCount = true;
      }
      if (shouldSyncTriggerCount) {
        const triggerCount = store2.context.triggerElements.size;
        if (store2.select("open") && store2.state.triggerCount !== triggerCount) {
          store2.set("triggerCount", triggerCount);
        }
      }
    }, [store2, id]);
  }
  function setPopupOpenState(state, open, trigger, preventUnmountOnClose = false) {
    if (open) {
      state.preventUnmountingOnClose = false;
    } else if (preventUnmountOnClose) {
      state.preventUnmountingOnClose = true;
    }
    const triggerId = trigger?.id ?? null;
    if (triggerId || open) {
      state.activeTriggerId = triggerId;
      state.activeTriggerElement = trigger ?? null;
    }
  }
  function attachPreventUnmountOnClose(eventDetails) {
    let preventUnmountOnClose = false;
    eventDetails.preventUnmountOnClose = () => {
      preventUnmountOnClose = true;
    };
    return () => preventUnmountOnClose;
  }
  function applyPopupOpenChange(store2, nextOpen, eventDetails, options = {}) {
    const reason = eventDetails.reason;
    const isHover = reason === reason_parts_exports.triggerHover;
    const isFocusOpen = nextOpen && reason === reason_parts_exports.triggerFocus;
    const isDismissClose = !nextOpen && (reason === reason_parts_exports.triggerPress || reason === reason_parts_exports.escapeKey);
    const shouldPreventUnmountOnClose = attachPreventUnmountOnClose(eventDetails);
    store2.context.onOpenChange?.(nextOpen, eventDetails);
    if (eventDetails.isCanceled) {
      return;
    }
    options.onBeforeDispatch?.();
    store2.state.floatingRootContext.dispatchOpenChange(nextOpen, eventDetails);
    const changeState = () => {
      const updatedState = {
        ...options.extraState,
        open: nextOpen
      };
      if (isFocusOpen) {
        updatedState.instantType = "focus";
      } else if (isDismissClose) {
        updatedState.instantType = "dismiss";
      } else if (isHover) {
        updatedState.instantType = void 0;
      }
      setPopupOpenState(updatedState, nextOpen, eventDetails.trigger, shouldPreventUnmountOnClose());
      store2.update(updatedState);
    };
    if (isHover) {
      ReactDOM4.flushSync(changeState);
    } else {
      changeState();
    }
  }
  function useInitialOpenSync(store2, openProp, defaultOpen, defaultTriggerId) {
    useOnFirstRender(() => {
      if (openProp === void 0 && store2.state.open === false && defaultOpen) {
        store2.state = {
          ...store2.state,
          open: true,
          activeTriggerId: defaultTriggerId,
          preventUnmountingOnClose: false
        };
      }
    });
  }
  function useTriggerDataForwarding(triggerId, triggerElementRef, store2, stateUpdates) {
    const isMountedByThisTrigger = store2.useState("isMountedByTrigger", triggerId);
    const baseRegisterTrigger = useTriggerRegistration(triggerId, store2);
    const registerTrigger = useStableCallback((element) => {
      baseRegisterTrigger(element);
      if (!element) {
        return;
      }
      const open = store2.select("open");
      const activeTriggerId = store2.select("activeTriggerId");
      if (activeTriggerId === triggerId) {
        store2.update({
          activeTriggerElement: element,
          ...open ? stateUpdates : null
        });
        return;
      }
      if (activeTriggerId == null && open) {
        store2.update({
          activeTriggerId: triggerId,
          activeTriggerElement: element,
          ...stateUpdates
        });
      }
    });
    useIsoLayoutEffect(() => {
      if (isMountedByThisTrigger) {
        store2.update({
          activeTriggerElement: triggerElementRef.current,
          ...stateUpdates
        });
      }
    }, [isMountedByThisTrigger, store2, triggerElementRef, ...Object.values(stateUpdates)]);
    return {
      registerTrigger,
      isMountedByThisTrigger
    };
  }
  function useImplicitActiveTrigger(store2, options = {}) {
    const {
      closeOnActiveTriggerUnmount = false
    } = options;
    const open = store2.useState("open");
    const reactiveTriggerCount = store2.useState("triggerCount");
    useIsoLayoutEffect(() => {
      if (!open) {
        if (store2.state.triggerCount !== 0) {
          store2.set("triggerCount", 0);
        }
        return;
      }
      const triggerCount = store2.context.triggerElements.size;
      const stateUpdates = {};
      if (store2.state.triggerCount !== triggerCount) {
        stateUpdates.triggerCount = triggerCount;
      }
      const activeTriggerId = store2.select("activeTriggerId");
      let lostActiveTriggerId = null;
      if (activeTriggerId) {
        const activeTriggerElement = store2.context.triggerElements.getById(activeTriggerId);
        if (!activeTriggerElement) {
          lostActiveTriggerId = activeTriggerId;
        } else if (activeTriggerElement !== store2.state.activeTriggerElement) {
          stateUpdates.activeTriggerElement = activeTriggerElement;
        }
      }
      if (!lostActiveTriggerId && !activeTriggerId && triggerCount === 1) {
        const iteratorResult = store2.context.triggerElements.entries().next();
        if (!iteratorResult.done) {
          const [implicitTriggerId, implicitTriggerElement] = iteratorResult.value;
          stateUpdates.activeTriggerId = implicitTriggerId;
          stateUpdates.activeTriggerElement = implicitTriggerElement;
        }
      }
      if (stateUpdates.triggerCount !== void 0 || stateUpdates.activeTriggerId !== void 0 || stateUpdates.activeTriggerElement !== void 0) {
        store2.update(stateUpdates);
      }
      if (lostActiveTriggerId) {
        if (closeOnActiveTriggerUnmount) {
          queueMicrotask(() => {
            if (store2.select("open") && store2.select("activeTriggerId") === lostActiveTriggerId && !store2.context.triggerElements.getById(lostActiveTriggerId)) {
              const eventDetails = createChangeEventDetails(reason_parts_exports.none);
              store2.setOpen(false, eventDetails);
              if (!eventDetails.isCanceled) {
                store2.update({
                  activeTriggerId: null,
                  activeTriggerElement: null
                });
              }
            }
          });
        }
      }
    }, [open, store2, reactiveTriggerCount, closeOnActiveTriggerUnmount]);
  }
  function useOpenStateTransitions(open, store2, onUnmount) {
    const {
      mounted,
      setMounted,
      transitionStatus
    } = useTransitionStatus(open);
    const preventUnmountingOnClose = store2.useState("preventUnmountingOnClose");
    const syncedPreventUnmountingOnClose = open ? false : preventUnmountingOnClose;
    store2.useSyncedValues({
      mounted,
      transitionStatus,
      preventUnmountingOnClose: syncedPreventUnmountingOnClose
    });
    const forceUnmount = useStableCallback(() => {
      setMounted(false);
      store2.update({
        activeTriggerId: null,
        activeTriggerElement: null,
        mounted: false,
        preventUnmountingOnClose: false
      });
      onUnmount?.();
      store2.context.onOpenChangeComplete?.(false);
    });
    useOpenChangeComplete({
      enabled: mounted && !open && !syncedPreventUnmountingOnClose,
      open,
      ref: store2.context.popupRef,
      onComplete() {
        if (!open) {
          forceUnmount();
        }
      }
    });
    return {
      forceUnmount,
      transitionStatus
    };
  }
  function usePopupInteractionProps(store2, statePart) {
    store2.useSyncedValues(statePart);
    useIsoLayoutEffect(() => () => {
      store2.update({
        activeTriggerProps: EMPTY_OBJECT,
        inactiveTriggerProps: EMPTY_OBJECT,
        popupProps: EMPTY_OBJECT
      });
    }, [store2]);
  }

  // node_modules/@base-ui/react/utils/popups/popupTriggerMap.mjs
  var PopupTriggerMap = class {
    constructor() {
      this.elementsSet = /* @__PURE__ */ new Set();
      this.idMap = /* @__PURE__ */ new Map();
    }
    /**
     * Adds a trigger element with the given ID.
     *
     * Note: The provided element is assumed to not be registered under multiple IDs.
     */
    add(id, element) {
      const existingElement = this.idMap.get(id);
      if (existingElement === element) {
        return;
      }
      if (existingElement !== void 0) {
        this.elementsSet.delete(existingElement);
      }
      this.elementsSet.add(element);
      this.idMap.set(id, element);
      if (true) {
        if (this.elementsSet.size !== this.idMap.size) {
          throw new Error("Base UI: A trigger element cannot be registered under multiple IDs in PopupTriggerMap.");
        }
      }
    }
    /**
     * Removes the trigger element with the given ID.
     */
    delete(id) {
      const element = this.idMap.get(id);
      if (element) {
        this.elementsSet.delete(element);
        this.idMap.delete(id);
      }
    }
    /**
     * Whether the given element is registered as a trigger.
     */
    hasElement(element) {
      return this.elementsSet.has(element);
    }
    /**
     * Whether there is a registered trigger element matching the given predicate.
     */
    hasMatchingElement(predicate) {
      for (const element of this.elementsSet) {
        if (predicate(element)) {
          return true;
        }
      }
      return false;
    }
    /**
     * Returns the trigger element associated with the given ID, or undefined if no such element exists.
     */
    getById(id) {
      return this.idMap.get(id);
    }
    /**
     * Returns an iterable of all registered trigger entries, where each entry is a tuple of [id, element].
     */
    entries() {
      return this.idMap.entries();
    }
    /**
     * Returns an iterable of all registered trigger elements.
     */
    elements() {
      return this.elementsSet.values();
    }
    /**
     * Returns the number of registered trigger elements.
     */
    get size() {
      return this.idMap.size;
    }
  };

  // node_modules/@base-ui/react/floating-ui-react/utils/getEmptyRootContext.mjs
  function getEmptyRootContext() {
    return new FloatingRootStore({
      open: false,
      transitionStatus: void 0,
      floatingElement: null,
      referenceElement: null,
      triggerElements: new PopupTriggerMap(),
      floatingId: void 0,
      syncOnly: false,
      nested: false,
      onOpenChange: void 0
    });
  }

  // node_modules/@base-ui/react/utils/popups/store.mjs
  function createInitialPopupStoreState() {
    return {
      open: false,
      openProp: void 0,
      mounted: false,
      transitionStatus: void 0,
      floatingRootContext: getEmptyRootContext(),
      floatingId: void 0,
      triggerCount: 0,
      preventUnmountingOnClose: false,
      payload: void 0,
      activeTriggerId: null,
      activeTriggerElement: null,
      triggerIdProp: void 0,
      popupElement: null,
      positionerElement: null,
      activeTriggerProps: EMPTY_OBJECT,
      inactiveTriggerProps: EMPTY_OBJECT,
      popupProps: EMPTY_OBJECT
    };
  }
  function createPopupFloatingRootContext(triggerElements, floatingId, nested = false) {
    return new FloatingRootStore({
      open: false,
      transitionStatus: void 0,
      floatingElement: null,
      referenceElement: null,
      triggerElements,
      floatingId,
      syncOnly: true,
      nested,
      onOpenChange: void 0
    });
  }
  var activeTriggerIdSelector = createSelector2((state) => state.triggerIdProp ?? state.activeTriggerId);
  var openSelector = createSelector2((state) => state.openProp ?? state.open);
  var popupIdSelector = createSelector2((state) => {
    const popupId = state.popupElement?.id ?? state.floatingId;
    return popupId || void 0;
  });
  function triggerOwnsOpenPopup(state, triggerId) {
    return triggerId !== void 0 && openSelector(state) && activeTriggerIdSelector(state) === triggerId;
  }
  function triggerOwnsOpenPopupOrIsOnlyTrigger(state, triggerId) {
    if (triggerOwnsOpenPopup(state, triggerId)) {
      return true;
    }
    return triggerId !== void 0 && openSelector(state) && activeTriggerIdSelector(state) == null && state.triggerCount === 1;
  }
  var popupStoreSelectors = {
    open: openSelector,
    mounted: createSelector2((state) => state.mounted),
    transitionStatus: createSelector2((state) => state.transitionStatus),
    floatingRootContext: createSelector2((state) => state.floatingRootContext),
    triggerCount: createSelector2((state) => state.triggerCount),
    preventUnmountingOnClose: createSelector2((state) => state.preventUnmountingOnClose),
    payload: createSelector2((state) => state.payload),
    activeTriggerId: activeTriggerIdSelector,
    activeTriggerElement: createSelector2((state) => state.mounted ? state.activeTriggerElement : null),
    popupId: popupIdSelector,
    /**
     * Whether the trigger with the given ID was used to open the popup.
     */
    isTriggerActive: createSelector2((state, triggerId) => triggerId !== void 0 && activeTriggerIdSelector(state) === triggerId),
    /**
     * Whether the popup is open and was activated by a trigger with the given ID.
     */
    isOpenedByTrigger: createSelector2((state, triggerId) => triggerOwnsOpenPopup(state, triggerId)),
    /**
     * Whether the popup is mounted and was activated by a trigger with the given ID.
     */
    isMountedByTrigger: createSelector2((state, triggerId) => triggerId !== void 0 && activeTriggerIdSelector(state) === triggerId && state.mounted),
    triggerProps: createSelector2((state, isActive) => isActive ? state.activeTriggerProps : state.inactiveTriggerProps),
    /**
     * Popup id for the trigger that currently owns the open popup.
     */
    triggerPopupId: createSelector2((state, triggerId) => triggerOwnsOpenPopupOrIsOnlyTrigger(state, triggerId) ? popupIdSelector(state) : void 0),
    popupProps: createSelector2((state) => state.popupProps),
    popupElement: createSelector2((state) => state.popupElement),
    positionerElement: createSelector2((state) => state.positionerElement)
  };

  // node_modules/@base-ui/react/floating-ui-react/hooks/useFloatingRootContext.mjs
  function useFloatingRootContext(options) {
    const {
      open = false,
      onOpenChange,
      elements: elements2 = {}
    } = options;
    const floatingId = useId();
    const nested = useFloatingParentNodeId() != null;
    if (true) {
      const optionDomReference = elements2.reference;
      if (optionDomReference && !isElement(optionDomReference)) {
        console.error("Cannot pass a virtual element to the `elements.reference` option,", "as it must be a real DOM element. Use `context.setPositionReference()`", "instead.");
      }
    }
    const store2 = useRefWithInit(() => new FloatingRootStore({
      open,
      transitionStatus: void 0,
      onOpenChange,
      referenceElement: elements2.reference ?? null,
      floatingElement: elements2.floating ?? null,
      triggerElements: new PopupTriggerMap(),
      floatingId,
      syncOnly: false,
      nested
    })).current;
    useIsoLayoutEffect(() => {
      const valuesToSync = {
        open,
        floatingId
      };
      if (elements2.reference !== void 0) {
        valuesToSync.referenceElement = elements2.reference;
        valuesToSync.domReferenceElement = isElement(elements2.reference) ? elements2.reference : null;
      }
      if (elements2.floating !== void 0) {
        valuesToSync.floatingElement = elements2.floating;
      }
      store2.update(valuesToSync);
    }, [open, floatingId, elements2.reference, elements2.floating, store2]);
    store2.context.onOpenChange = onOpenChange;
    store2.context.nested = nested;
    return store2;
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useFloating.mjs
  function useFloating2(options = {}) {
    const {
      nodeId,
      externalTree
    } = options;
    const internalStore = useFloatingRootContext(options);
    const store2 = options.rootContext || internalStore;
    const referenceElement = store2.useState("referenceElement");
    const floatingElement = store2.useState("floatingElement");
    const domReferenceElement = store2.useState("domReferenceElement");
    const open = store2.useState("open");
    const floatingId = store2.useState("floatingId");
    const [positionReference, setPositionReferenceRaw] = React32.useState(null);
    const [localDomReference, setLocalDomReference] = React32.useState(void 0);
    const [localFloatingElement, setLocalFloatingElement] = React32.useState(void 0);
    const domReferenceRef = React32.useRef(null);
    const tree = useFloatingTree(externalTree);
    const storeElements = React32.useMemo(() => ({
      reference: referenceElement,
      floating: floatingElement,
      domReference: domReferenceElement
    }), [referenceElement, floatingElement, domReferenceElement]);
    const position = useFloating({
      ...options,
      elements: {
        ...storeElements,
        ...positionReference && {
          reference: positionReference
        }
      }
    });
    const localDomReferenceElement = isElement(localDomReference) ? localDomReference : null;
    const syncedFloatingElement = localFloatingElement === void 0 ? store2.state.floatingElement : localFloatingElement;
    store2.useSyncedValue("referenceElement", localDomReference ?? null);
    store2.useSyncedValue("domReferenceElement", localDomReference === void 0 ? domReferenceElement : localDomReferenceElement);
    store2.useSyncedValue("floatingElement", syncedFloatingElement);
    const setPositionReference = React32.useCallback((node) => {
      const computedPositionReference = isElement(node) ? {
        getBoundingClientRect: () => node.getBoundingClientRect(),
        getClientRects: () => node.getClientRects(),
        contextElement: node
      } : node;
      setPositionReferenceRaw(computedPositionReference);
      position.refs.setReference(computedPositionReference);
    }, [position.refs]);
    const setReference = React32.useCallback((node) => {
      if (isElement(node) || node === null) {
        domReferenceRef.current = node;
        setLocalDomReference(node);
      }
      if (isElement(position.refs.reference.current) || position.refs.reference.current === null || // Don't allow setting virtual elements using the old technique back to
      // `null` to support `positionReference` + an unstable `reference`
      // callback ref.
      node !== null && !isElement(node)) {
        position.refs.setReference(node);
      }
    }, [position.refs, setLocalDomReference]);
    const setFloating = React32.useCallback((node) => {
      setLocalFloatingElement(node);
      position.refs.setFloating(node);
    }, [position.refs]);
    const refs = React32.useMemo(() => ({
      ...position.refs,
      setReference,
      setFloating,
      setPositionReference,
      domReference: domReferenceRef
    }), [position.refs, setReference, setFloating, setPositionReference]);
    const elements2 = React32.useMemo(() => ({
      ...position.elements,
      domReference: domReferenceElement
    }), [position.elements, domReferenceElement]);
    const context = React32.useMemo(() => ({
      ...position,
      dataRef: store2.context.dataRef,
      open,
      onOpenChange: store2.setOpen,
      events: store2.context.events,
      floatingId,
      refs,
      elements: elements2,
      nodeId,
      rootStore: store2
    }), [position, refs, elements2, nodeId, store2, open, floatingId]);
    useIsoLayoutEffect(() => {
      if (domReferenceElement) {
        domReferenceRef.current = domReferenceElement;
      }
    }, [domReferenceElement]);
    useIsoLayoutEffect(() => {
      store2.context.dataRef.current.floatingContext = context;
      const node = tree?.nodesRef.current.find((n2) => n2.id === nodeId);
      if (node) {
        node.context = context;
      }
    });
    return React32.useMemo(() => ({
      ...position,
      context,
      refs,
      elements: elements2,
      rootStore: store2
    }), [position, refs, elements2, context, store2]);
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useFocus.mjs
  var React33 = __toESM(require_react(), 1);
  var isMacSafari = parts_exports.os.mac && parts_exports.engine.webkit;
  function useFocus(context, props = {}) {
    const {
      enabled = true,
      delay
    } = props;
    const store2 = "rootStore" in context ? context.rootStore : context;
    const {
      events,
      dataRef
    } = store2.context;
    const blockFocusRef = React33.useRef(false);
    const blockedReferenceRef = React33.useRef(null);
    const keyboardModalityRef = React33.useRef(true);
    const timeout = useTimeout();
    React33.useEffect(() => {
      const domReference = store2.select("domReferenceElement");
      if (!enabled) {
        return void 0;
      }
      const win = getWindow(domReference);
      function onBlur() {
        const currentDomReference = store2.select("domReferenceElement");
        if (!store2.select("open") && isHTMLElement(currentDomReference) && currentDomReference === activeElement(ownerDocument(currentDomReference))) {
          blockFocusRef.current = true;
        }
      }
      function onKeyDown() {
        keyboardModalityRef.current = true;
      }
      function onPointerDown() {
        keyboardModalityRef.current = false;
      }
      return mergeCleanups(addEventListener(win, "blur", onBlur), isMacSafari && addEventListener(win, "keydown", onKeyDown, true), isMacSafari && addEventListener(win, "pointerdown", onPointerDown, true));
    }, [store2, enabled]);
    React33.useEffect(() => {
      if (!enabled) {
        return void 0;
      }
      function onOpenChangeLocal(details) {
        if (details.reason === reason_parts_exports.triggerPress || details.reason === reason_parts_exports.escapeKey) {
          const referenceElement = store2.select("domReferenceElement");
          if (isElement(referenceElement)) {
            blockedReferenceRef.current = referenceElement;
            blockFocusRef.current = true;
          }
        }
      }
      events.on("openchange", onOpenChangeLocal);
      return () => {
        events.off("openchange", onOpenChangeLocal);
      };
    }, [events, enabled, store2]);
    const reference = React33.useMemo(() => {
      function resetBlockedFocus() {
        blockFocusRef.current = false;
        blockedReferenceRef.current = null;
      }
      return {
        onMouseLeave() {
          resetBlockedFocus();
        },
        onFocus(event) {
          const focusTarget = event.currentTarget;
          if (blockFocusRef.current) {
            if (blockedReferenceRef.current === focusTarget) {
              return;
            }
            resetBlockedFocus();
          }
          const target = getTarget(event.nativeEvent);
          if (isElement(target)) {
            if (isMacSafari && !event.relatedTarget) {
              if (!keyboardModalityRef.current && !isTypeableElement(target)) {
                return;
              }
            } else if (!matchesFocusVisible(target)) {
              return;
            }
          }
          const movedFromOtherEnabledTrigger = isTargetInsideEnabledTrigger(event.relatedTarget, store2.context.triggerElements);
          const {
            nativeEvent,
            currentTarget
          } = event;
          const delayValue = typeof delay === "function" ? delay() : delay;
          if (store2.select("open") && movedFromOtherEnabledTrigger || delayValue === 0 || delayValue === void 0) {
            store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerFocus, nativeEvent, currentTarget));
            return;
          }
          timeout.start(delayValue, () => {
            if (blockFocusRef.current) {
              return;
            }
            store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerFocus, nativeEvent, currentTarget));
          });
        },
        onBlur(event) {
          resetBlockedFocus();
          const relatedTarget = event.relatedTarget;
          const nativeEvent = event.nativeEvent;
          const movedToFocusGuard = isElement(relatedTarget) && relatedTarget.hasAttribute(createAttribute("focus-guard")) && relatedTarget.getAttribute("data-type") === "outside";
          timeout.start(0, () => {
            const domReference = store2.select("domReferenceElement");
            const activeEl = activeElement(ownerDocument(domReference));
            if (!relatedTarget && activeEl === domReference) {
              return;
            }
            if (contains(dataRef.current.floatingContext?.refs.floating.current, activeEl) || contains(domReference, activeEl) || movedToFocusGuard) {
              return;
            }
            const nextFocusedElement = relatedTarget ?? activeEl;
            if (isTargetInsideEnabledTrigger(nextFocusedElement, store2.context.triggerElements)) {
              return;
            }
            store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerFocus, nativeEvent));
          });
        }
      };
    }, [dataRef, delay, store2, timeout]);
    return React33.useMemo(() => enabled ? {
      reference,
      trigger: reference
    } : {}, [enabled, reference]);
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useHoverFloatingInteraction.mjs
  var React34 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/floating-ui-react/hooks/useHoverInteractionSharedState.mjs
  var HoverInteraction = class _HoverInteraction {
    constructor() {
      this.pointerType = void 0;
      this.interactedInside = false;
      this.handler = void 0;
      this.blockMouseMove = true;
      this.performedPointerEventsMutation = false;
      this.pointerEventsScopeElement = null;
      this.pointerEventsReferenceElement = null;
      this.pointerEventsFloatingElement = null;
      this.restTimeoutPending = false;
      this.openChangeTimeout = new Timeout();
      this.restTimeout = new Timeout();
      this.handleCloseOptions = void 0;
    }
    static create() {
      return new _HoverInteraction();
    }
    dispose = () => {
      this.openChangeTimeout.clear();
      this.restTimeout.clear();
    };
    disposeEffect = () => {
      return this.dispose;
    };
  };
  var pointerEventsMutationOwnerByScopeElement = /* @__PURE__ */ new WeakMap();
  function clearSafePolygonPointerEventsMutation(instance) {
    if (!instance.performedPointerEventsMutation) {
      return;
    }
    const scopeElement = instance.pointerEventsScopeElement;
    if (scopeElement && pointerEventsMutationOwnerByScopeElement.get(scopeElement) === instance) {
      instance.pointerEventsScopeElement?.style.removeProperty("pointer-events");
      instance.pointerEventsReferenceElement?.style.removeProperty("pointer-events");
      instance.pointerEventsFloatingElement?.style.removeProperty("pointer-events");
      pointerEventsMutationOwnerByScopeElement.delete(scopeElement);
    }
    instance.performedPointerEventsMutation = false;
    instance.pointerEventsScopeElement = null;
    instance.pointerEventsReferenceElement = null;
    instance.pointerEventsFloatingElement = null;
  }
  function applySafePolygonPointerEventsMutation(instance, options) {
    const {
      scopeElement,
      referenceElement,
      floatingElement
    } = options;
    const existingOwner = pointerEventsMutationOwnerByScopeElement.get(scopeElement);
    if (existingOwner && existingOwner !== instance) {
      clearSafePolygonPointerEventsMutation(existingOwner);
    }
    clearSafePolygonPointerEventsMutation(instance);
    instance.performedPointerEventsMutation = true;
    instance.pointerEventsScopeElement = scopeElement;
    instance.pointerEventsReferenceElement = referenceElement;
    instance.pointerEventsFloatingElement = floatingElement;
    pointerEventsMutationOwnerByScopeElement.set(scopeElement, instance);
    scopeElement.style.pointerEvents = "none";
    referenceElement.style.pointerEvents = "auto";
    floatingElement.style.pointerEvents = "auto";
  }
  function useHoverInteractionSharedState(store2) {
    const data = store2.context.dataRef.current;
    const instance = useRefWithInit(() => data.hoverInteractionState ?? HoverInteraction.create()).current;
    if (!data.hoverInteractionState) {
      data.hoverInteractionState = instance;
    }
    useOnMount(data.hoverInteractionState.disposeEffect);
    return data.hoverInteractionState;
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useHoverFloatingInteraction.mjs
  function useHoverFloatingInteraction(context, parameters = {}) {
    const {
      enabled = true,
      closeDelay: closeDelayProp = 0,
      nodeId: nodeIdProp
    } = parameters;
    const store2 = "rootStore" in context ? context.rootStore : context;
    const open = store2.useState("open");
    const floatingElement = store2.useState("floatingElement");
    const domReferenceElement = store2.useState("domReferenceElement");
    const {
      dataRef
    } = store2.context;
    const tree = useFloatingTree();
    const parentId = useFloatingParentNodeId();
    const instance = useHoverInteractionSharedState(store2);
    const childClosedTimeout = useTimeout();
    const isClickLikeOpenEvent2 = useStableCallback(() => {
      return isClickLikeOpenEvent(dataRef.current.openEvent?.type, instance.interactedInside);
    });
    const isHoverOpen = useStableCallback(() => {
      return isHoverOpenEvent(dataRef.current.openEvent?.type);
    });
    const clearPointerEvents = useStableCallback(() => {
      clearSafePolygonPointerEventsMutation(instance);
    });
    useIsoLayoutEffect(() => {
      if (!open) {
        instance.pointerType = void 0;
        instance.restTimeoutPending = false;
        instance.interactedInside = false;
        clearPointerEvents();
      }
    }, [open, instance, clearPointerEvents]);
    React34.useEffect(() => {
      return clearPointerEvents;
    }, [clearPointerEvents]);
    useIsoLayoutEffect(() => {
      if (!enabled) {
        return void 0;
      }
      if (open && instance.handleCloseOptions?.blockPointerEvents && isHoverOpen() && isElement(domReferenceElement) && floatingElement) {
        const ref = domReferenceElement;
        const floatingEl = floatingElement;
        const doc = ownerDocument(floatingElement);
        const parentFloating = tree?.nodesRef.current.find((node) => node.id === parentId)?.context?.elements.floating;
        if (parentFloating) {
          parentFloating.style.pointerEvents = "";
        }
        const cachedScopeElement = instance.pointerEventsScopeElement !== floatingEl ? instance.pointerEventsScopeElement : null;
        const parentScopeElement = parentFloating !== floatingEl ? parentFloating : null;
        const scopeElement = instance.handleCloseOptions?.getScope?.() ?? cachedScopeElement ?? parentScopeElement ?? ref.closest("[data-rootownerid]") ?? doc.body;
        applySafePolygonPointerEventsMutation(instance, {
          scopeElement,
          referenceElement: ref,
          floatingElement: floatingEl
        });
        return () => {
          clearPointerEvents();
        };
      }
      return void 0;
    }, [enabled, open, domReferenceElement, floatingElement, instance, isHoverOpen, tree, parentId, clearPointerEvents]);
    React34.useEffect(() => {
      if (!enabled) {
        return void 0;
      }
      function hasParentChildren() {
        return !!(tree && parentId && getNodeChildren(tree.nodesRef.current, parentId).length > 0);
      }
      function closeWithDelay(event) {
        const closeDelay = getDelay(closeDelayProp, "close", instance.pointerType);
        const close = () => {
          store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
          tree?.events.emit("floating.closed", event);
        };
        if (closeDelay) {
          instance.openChangeTimeout.start(closeDelay, close);
        } else {
          instance.openChangeTimeout.clear();
          close();
        }
      }
      function handleInteractInside(event) {
        const target = getTarget(event);
        if (!isInteractiveElement(target)) {
          instance.interactedInside = false;
          return;
        }
        instance.interactedInside = target?.closest("[aria-haspopup]") != null;
      }
      function onFloatingMouseEnter() {
        instance.openChangeTimeout.clear();
        childClosedTimeout.clear();
        tree?.events.off("floating.closed", onNodeClosed);
        clearPointerEvents();
      }
      function onFloatingMouseLeave(event) {
        if (hasParentChildren() && tree) {
          tree.events.on("floating.closed", onNodeClosed);
          return;
        }
        if (isTargetInsideEnabledTrigger(event.relatedTarget, store2.context.triggerElements)) {
          return;
        }
        const currentNodeId = dataRef.current.floatingContext?.nodeId ?? nodeIdProp;
        const relatedTarget = event.relatedTarget;
        const isMovingIntoDescendantFloating = tree && currentNodeId && isElement(relatedTarget) && getNodeChildren(tree.nodesRef.current, currentNodeId, false).some((node) => contains(node.context?.elements.floating, relatedTarget));
        if (isMovingIntoDescendantFloating) {
          return;
        }
        if (instance.handler) {
          instance.handler(event);
          return;
        }
        clearPointerEvents();
        if (isHoverOpen() && !isClickLikeOpenEvent2()) {
          closeWithDelay(event);
        }
      }
      function onNodeClosed(event) {
        if (!tree || !parentId || hasParentChildren()) {
          return;
        }
        childClosedTimeout.start(0, () => {
          tree.events.off("floating.closed", onNodeClosed);
          store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
          tree.events.emit("floating.closed", event);
        });
      }
      const floating = floatingElement;
      return mergeCleanups(floating && addEventListener(floating, "mouseenter", onFloatingMouseEnter), floating && addEventListener(floating, "mouseleave", onFloatingMouseLeave), floating && addEventListener(floating, "pointerdown", handleInteractInside, true), () => {
        tree?.events.off("floating.closed", onNodeClosed);
      });
    }, [enabled, floatingElement, store2, dataRef, closeDelayProp, nodeIdProp, isHoverOpen, isClickLikeOpenEvent2, clearPointerEvents, instance, tree, parentId, childClosedTimeout]);
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useHoverReferenceInteraction.mjs
  var React35 = __toESM(require_react(), 1);
  var ReactDOM5 = __toESM(require_react_dom(), 1);
  var EMPTY_REF = {
    current: null
  };
  function useHoverReferenceInteraction(context, props = {}) {
    const {
      enabled = true,
      delay = 0,
      handleClose = null,
      mouseOnly = false,
      restMs = 0,
      move = true,
      triggerElementRef = EMPTY_REF,
      externalTree,
      isActiveTrigger = true,
      getHandleCloseContext,
      isClosing,
      shouldOpen: shouldOpenProp
    } = props;
    const store2 = "rootStore" in context ? context.rootStore : context;
    const {
      dataRef,
      events
    } = store2.context;
    const tree = useFloatingTree(externalTree);
    const instance = useHoverInteractionSharedState(store2);
    const isHoverCloseActiveRef = React35.useRef(false);
    const handleCloseRef = useValueAsRef(handleClose);
    const delayRef = useValueAsRef(delay);
    const restMsRef = useValueAsRef(restMs);
    const enabledRef = useValueAsRef(enabled);
    const shouldOpenRef = useValueAsRef(shouldOpenProp);
    const isClosingRef = useValueAsRef(isClosing);
    const isClickLikeOpenEvent2 = useStableCallback(() => {
      return isClickLikeOpenEvent(dataRef.current.openEvent?.type, instance.interactedInside);
    });
    const checkShouldOpen = useStableCallback(() => {
      return shouldOpenRef.current?.() !== false;
    });
    const isOverInactiveTrigger = useStableCallback((currentDomReference, currentTarget, target) => {
      const allTriggers = store2.context.triggerElements;
      if (allTriggers.hasElement(currentTarget)) {
        return !currentDomReference || !contains(currentDomReference, currentTarget);
      }
      if (!isElement(target)) {
        return false;
      }
      const targetElement = target;
      return allTriggers.hasMatchingElement((trigger) => contains(trigger, targetElement)) && (!currentDomReference || !contains(currentDomReference, targetElement));
    });
    const cleanupMouseMoveHandler = useStableCallback(() => {
      if (!instance.handler) {
        return;
      }
      const doc = ownerDocument(store2.select("domReferenceElement"));
      doc.removeEventListener("mousemove", instance.handler);
      instance.handler = void 0;
    });
    const clearPointerEvents = useStableCallback(() => {
      clearSafePolygonPointerEventsMutation(instance);
    });
    if (isActiveTrigger) {
      instance.handleCloseOptions = handleCloseRef.current?.__options;
    }
    React35.useEffect(() => cleanupMouseMoveHandler, [cleanupMouseMoveHandler]);
    React35.useEffect(() => {
      if (!enabled) {
        return void 0;
      }
      function onOpenChangeLocal(details) {
        if (!details.open) {
          isHoverCloseActiveRef.current = details.reason === reason_parts_exports.triggerHover;
          cleanupMouseMoveHandler();
          instance.openChangeTimeout.clear();
          instance.restTimeout.clear();
          instance.blockMouseMove = true;
          instance.restTimeoutPending = false;
        } else {
          isHoverCloseActiveRef.current = false;
        }
      }
      events.on("openchange", onOpenChangeLocal);
      return () => {
        events.off("openchange", onOpenChangeLocal);
      };
    }, [enabled, events, instance, cleanupMouseMoveHandler]);
    React35.useEffect(() => {
      if (!enabled) {
        return void 0;
      }
      function closeWithDelay(event, runElseBranch = true) {
        const closeDelay = getDelay(delayRef.current, "close", instance.pointerType);
        if (closeDelay) {
          instance.openChangeTimeout.start(closeDelay, () => {
            store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
            tree?.events.emit("floating.closed", event);
          });
        } else if (runElseBranch) {
          instance.openChangeTimeout.clear();
          store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
          tree?.events.emit("floating.closed", event);
        }
      }
      const trigger = triggerElementRef.current ?? (isActiveTrigger ? store2.select("domReferenceElement") : null);
      if (!isElement(trigger)) {
        return void 0;
      }
      function onMouseEnter(event) {
        instance.openChangeTimeout.clear();
        instance.blockMouseMove = false;
        if (mouseOnly && !isMouseLikePointerType(instance.pointerType)) {
          return;
        }
        const restMsValue = getRestMs(restMsRef.current);
        const openDelay = getDelay(delayRef.current, "open", instance.pointerType);
        const eventTarget = getTarget(event);
        const currentTarget = event.currentTarget ?? null;
        const currentDomReference = store2.select("domReferenceElement");
        let triggerNode = currentTarget;
        if (isElement(eventTarget) && !store2.context.triggerElements.hasElement(eventTarget)) {
          for (const triggerElement of store2.context.triggerElements.elements()) {
            if (contains(triggerElement, eventTarget)) {
              triggerNode = triggerElement;
              break;
            }
          }
        }
        if (isElement(currentTarget) && isElement(currentDomReference) && !store2.context.triggerElements.hasElement(currentTarget) && contains(currentTarget, currentDomReference)) {
          triggerNode = currentDomReference;
        }
        const isOverInactive = triggerNode == null ? false : isOverInactiveTrigger(currentDomReference, triggerNode, eventTarget);
        const isOpen = store2.select("open");
        const isInClosingTransition = isClosingRef.current?.() ?? store2.select("transitionStatus") === "ending";
        const isHoverCloseTransition = !isOpen && isInClosingTransition && isHoverCloseActiveRef.current;
        const isReenteringSameTriggerDuringCloseTransition = !isOverInactive && isElement(triggerNode) && isElement(currentDomReference) && contains(currentDomReference, triggerNode) && isHoverCloseTransition;
        const isRestOnlyDelay = restMsValue > 0 && !openDelay;
        const shouldOpenImmediately = isOverInactive && (isOpen || isHoverCloseTransition) || isReenteringSameTriggerDuringCloseTransition;
        const shouldOpen = !isOpen || isOverInactive;
        if (shouldOpenImmediately) {
          if (checkShouldOpen()) {
            store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerNode));
          }
          return;
        }
        if (isRestOnlyDelay) {
          return;
        }
        if (openDelay) {
          instance.openChangeTimeout.start(openDelay, () => {
            if (shouldOpen && checkShouldOpen()) {
              store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerNode));
            }
          });
        } else if (shouldOpen) {
          if (checkShouldOpen()) {
            store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerNode));
          }
        }
      }
      function onMouseLeave(event) {
        if (isClickLikeOpenEvent2()) {
          clearPointerEvents();
          return;
        }
        cleanupMouseMoveHandler();
        const domReferenceElement = store2.select("domReferenceElement");
        const doc = ownerDocument(domReferenceElement);
        instance.restTimeout.clear();
        instance.restTimeoutPending = false;
        const handleCloseContextBase = dataRef.current.floatingContext ?? getHandleCloseContext?.();
        if (isTargetInsideEnabledTrigger(event.relatedTarget, store2.context.triggerElements)) {
          return;
        }
        if (handleCloseRef.current && handleCloseContextBase) {
          if (!store2.select("open")) {
            instance.openChangeTimeout.clear();
          }
          const currentTrigger = triggerElementRef.current;
          instance.handler = handleCloseRef.current({
            ...handleCloseContextBase,
            tree,
            x: event.clientX,
            y: event.clientY,
            onClose() {
              clearPointerEvents();
              cleanupMouseMoveHandler();
              if (enabledRef.current && !isClickLikeOpenEvent2() && currentTrigger === store2.select("domReferenceElement")) {
                closeWithDelay(event, true);
              }
            }
          });
          doc.addEventListener("mousemove", instance.handler);
          instance.handler(event);
          return;
        }
        const shouldClose = instance.pointerType === "touch" ? !contains(store2.select("floatingElement"), event.relatedTarget) : true;
        if (shouldClose) {
          closeWithDelay(event);
        }
      }
      if (move) {
        return mergeCleanups(addEventListener(trigger, "mousemove", onMouseEnter, {
          once: true
        }), addEventListener(trigger, "mouseenter", onMouseEnter), addEventListener(trigger, "mouseleave", onMouseLeave));
      }
      return mergeCleanups(addEventListener(trigger, "mouseenter", onMouseEnter), addEventListener(trigger, "mouseleave", onMouseLeave));
    }, [cleanupMouseMoveHandler, clearPointerEvents, dataRef, delayRef, store2, enabled, handleCloseRef, instance, isActiveTrigger, isOverInactiveTrigger, isClickLikeOpenEvent2, mouseOnly, move, restMsRef, triggerElementRef, tree, enabledRef, getHandleCloseContext, isClosingRef, checkShouldOpen]);
    return React35.useMemo(() => {
      if (!enabled) {
        return void 0;
      }
      function setPointerRef(event) {
        instance.pointerType = event.pointerType;
      }
      return {
        onPointerDown: setPointerRef,
        onPointerEnter: setPointerRef,
        onMouseMove(event) {
          const {
            nativeEvent
          } = event;
          const trigger = event.currentTarget;
          const currentDomReference = store2.select("domReferenceElement");
          const currentOpen = store2.select("open");
          const isOverInactive = isOverInactiveTrigger(currentDomReference, trigger, event.target);
          if (mouseOnly && !isMouseLikePointerType(instance.pointerType)) {
            return;
          }
          if (currentOpen && isOverInactive && instance.handleCloseOptions?.blockPointerEvents) {
            const floatingElement = store2.select("floatingElement");
            if (floatingElement) {
              const scopeElement = instance.handleCloseOptions?.getScope?.() ?? trigger.ownerDocument.body;
              applySafePolygonPointerEventsMutation(instance, {
                scopeElement,
                referenceElement: trigger,
                floatingElement
              });
            }
          }
          const restMsValue = getRestMs(restMsRef.current);
          if (currentOpen && !isOverInactive || restMsValue === 0) {
            return;
          }
          if (!isOverInactive && instance.restTimeoutPending && event.movementX ** 2 + event.movementY ** 2 < 2) {
            return;
          }
          instance.restTimeout.clear();
          function handleMouseMove() {
            instance.restTimeoutPending = false;
            if (isClickLikeOpenEvent2()) {
              return;
            }
            const latestOpen = store2.select("open");
            if (!instance.blockMouseMove && (!latestOpen || isOverInactive) && checkShouldOpen()) {
              store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, nativeEvent, trigger));
            }
          }
          if (instance.pointerType === "touch") {
            ReactDOM5.flushSync(() => {
              handleMouseMove();
            });
          } else if (isOverInactive && currentOpen) {
            handleMouseMove();
          } else {
            instance.restTimeoutPending = true;
            instance.restTimeout.start(restMsValue, handleMouseMove);
          }
        }
      };
    }, [enabled, instance, isClickLikeOpenEvent2, isOverInactiveTrigger, mouseOnly, store2, restMsRef, checkShouldOpen]);
  }

  // node_modules/@base-ui/react/floating-ui-react/safePolygon.mjs
  var CURSOR_SPEED_THRESHOLD = 0.1;
  var CURSOR_SPEED_THRESHOLD_SQUARED = CURSOR_SPEED_THRESHOLD * CURSOR_SPEED_THRESHOLD;
  var POLYGON_BUFFER = 0.5;
  function hasIntersectingEdge(pointX, pointY, xi, yi, xj, yj) {
    return yi >= pointY !== yj >= pointY && pointX <= (xj - xi) * (pointY - yi) / (yj - yi) + xi;
  }
  function isPointInQuadrilateral(pointX, pointY, x1, y1, x2, y2, x3, y3, x4, y4) {
    let isInsideValue = false;
    if (hasIntersectingEdge(pointX, pointY, x1, y1, x2, y2)) {
      isInsideValue = !isInsideValue;
    }
    if (hasIntersectingEdge(pointX, pointY, x2, y2, x3, y3)) {
      isInsideValue = !isInsideValue;
    }
    if (hasIntersectingEdge(pointX, pointY, x3, y3, x4, y4)) {
      isInsideValue = !isInsideValue;
    }
    if (hasIntersectingEdge(pointX, pointY, x4, y4, x1, y1)) {
      isInsideValue = !isInsideValue;
    }
    return isInsideValue;
  }
  function isInsideRect(pointX, pointY, rect) {
    return pointX >= rect.x && pointX <= rect.x + rect.width && pointY >= rect.y && pointY <= rect.y + rect.height;
  }
  function isInsideAxisAlignedRect(pointX, pointY, x1, y1, x2, y2) {
    const minX = Math.min(x1, x2);
    const maxX = Math.max(x1, x2);
    const minY = Math.min(y1, y2);
    const maxY = Math.max(y1, y2);
    return pointX >= minX && pointX <= maxX && pointY >= minY && pointY <= maxY;
  }
  function safePolygon(options = {}) {
    const {
      blockPointerEvents = false
    } = options;
    const timeout = new Timeout();
    const fn = ({
      x: x2,
      y: y2,
      placement,
      elements: elements2,
      onClose,
      nodeId,
      tree
    }) => {
      const side = placement?.split("-")[0];
      let hasLanded = false;
      let lastX = null;
      let lastY = null;
      let lastCursorTime = typeof performance !== "undefined" ? performance.now() : 0;
      function isCursorMovingSlowly(nextX, nextY) {
        const currentTime = performance.now();
        const elapsedTime = currentTime - lastCursorTime;
        if (lastX === null || lastY === null || elapsedTime === 0) {
          lastX = nextX;
          lastY = nextY;
          lastCursorTime = currentTime;
          return false;
        }
        const deltaX = nextX - lastX;
        const deltaY = nextY - lastY;
        const distanceSquared = deltaX * deltaX + deltaY * deltaY;
        const thresholdSquared = elapsedTime * elapsedTime * CURSOR_SPEED_THRESHOLD_SQUARED;
        lastX = nextX;
        lastY = nextY;
        lastCursorTime = currentTime;
        return distanceSquared < thresholdSquared;
      }
      function close() {
        timeout.clear();
        onClose();
      }
      return function onMouseMove(event) {
        timeout.clear();
        const domReference = elements2.domReference;
        const floating = elements2.floating;
        if (!domReference || !floating || side == null || x2 == null || y2 == null) {
          return void 0;
        }
        const {
          clientX,
          clientY
        } = event;
        const target = getTarget(event);
        const isLeave = event.type === "mouseleave";
        const isOverFloatingEl = contains(floating, target);
        const isOverReferenceEl = contains(domReference, target);
        if (isOverFloatingEl) {
          hasLanded = true;
          if (!isLeave) {
            return void 0;
          }
        }
        if (isOverReferenceEl) {
          hasLanded = false;
          if (!isLeave) {
            hasLanded = true;
            return void 0;
          }
        }
        if (isLeave && isElement(event.relatedTarget) && contains(floating, event.relatedTarget)) {
          return void 0;
        }
        function hasOpenChildNode() {
          return Boolean(tree && getNodeChildren(tree.nodesRef.current, nodeId).length > 0);
        }
        function closeIfNoOpenChild() {
          if (!hasOpenChildNode()) {
            close();
          }
        }
        if (hasOpenChildNode()) {
          return void 0;
        }
        const refRect = domReference.getBoundingClientRect();
        const rect = floating.getBoundingClientRect();
        const cursorLeaveFromRight = x2 > rect.right - rect.width / 2;
        const cursorLeaveFromBottom = y2 > rect.bottom - rect.height / 2;
        const isFloatingWider = rect.width > refRect.width;
        const isFloatingTaller = rect.height > refRect.height;
        const left = (isFloatingWider ? refRect : rect).left;
        const right = (isFloatingWider ? refRect : rect).right;
        const top = (isFloatingTaller ? refRect : rect).top;
        const bottom = (isFloatingTaller ? refRect : rect).bottom;
        if (side === "top" && y2 >= refRect.bottom - 1 || side === "bottom" && y2 <= refRect.top + 1 || side === "left" && x2 >= refRect.right - 1 || side === "right" && x2 <= refRect.left + 1) {
          closeIfNoOpenChild();
          return void 0;
        }
        let isInsideTroughRect = false;
        switch (side) {
          case "top":
            isInsideTroughRect = isInsideAxisAlignedRect(clientX, clientY, left, refRect.top + 1, right, rect.bottom - 1);
            break;
          case "bottom":
            isInsideTroughRect = isInsideAxisAlignedRect(clientX, clientY, left, rect.top + 1, right, refRect.bottom - 1);
            break;
          case "left":
            isInsideTroughRect = isInsideAxisAlignedRect(clientX, clientY, rect.right - 1, bottom, refRect.left + 1, top);
            break;
          case "right":
            isInsideTroughRect = isInsideAxisAlignedRect(clientX, clientY, refRect.right - 1, bottom, rect.left + 1, top);
            break;
          default:
        }
        if (isInsideTroughRect) {
          return void 0;
        }
        if (hasLanded && !isInsideRect(clientX, clientY, refRect)) {
          closeIfNoOpenChild();
          return void 0;
        }
        if (!isLeave && isCursorMovingSlowly(clientX, clientY)) {
          closeIfNoOpenChild();
          return void 0;
        }
        let isInsidePolygon = false;
        switch (side) {
          case "top": {
            const cursorXOffset = isFloatingWider ? POLYGON_BUFFER / 2 : POLYGON_BUFFER * 4;
            const cursorPointOneX = isFloatingWider ? x2 + cursorXOffset : cursorLeaveFromRight ? x2 + cursorXOffset : x2 - cursorXOffset;
            const cursorPointTwoX = isFloatingWider ? x2 - cursorXOffset : cursorLeaveFromRight ? x2 + cursorXOffset : x2 - cursorXOffset;
            const cursorPointY = y2 + POLYGON_BUFFER + 1;
            const commonYLeft = cursorLeaveFromRight ? rect.bottom - POLYGON_BUFFER : isFloatingWider ? rect.bottom - POLYGON_BUFFER : rect.top;
            const commonYRight = cursorLeaveFromRight ? isFloatingWider ? rect.bottom - POLYGON_BUFFER : rect.top : rect.bottom - POLYGON_BUFFER;
            isInsidePolygon = isPointInQuadrilateral(clientX, clientY, cursorPointOneX, cursorPointY, cursorPointTwoX, cursorPointY, rect.left, commonYLeft, rect.right, commonYRight);
            break;
          }
          case "bottom": {
            const cursorXOffset = isFloatingWider ? POLYGON_BUFFER / 2 : POLYGON_BUFFER * 4;
            const cursorPointOneX = isFloatingWider ? x2 + cursorXOffset : cursorLeaveFromRight ? x2 + cursorXOffset : x2 - cursorXOffset;
            const cursorPointTwoX = isFloatingWider ? x2 - cursorXOffset : cursorLeaveFromRight ? x2 + cursorXOffset : x2 - cursorXOffset;
            const cursorPointY = y2 - POLYGON_BUFFER;
            const commonYLeft = cursorLeaveFromRight ? rect.top + POLYGON_BUFFER : isFloatingWider ? rect.top + POLYGON_BUFFER : rect.bottom;
            const commonYRight = cursorLeaveFromRight ? isFloatingWider ? rect.top + POLYGON_BUFFER : rect.bottom : rect.top + POLYGON_BUFFER;
            isInsidePolygon = isPointInQuadrilateral(clientX, clientY, cursorPointOneX, cursorPointY, cursorPointTwoX, cursorPointY, rect.left, commonYLeft, rect.right, commonYRight);
            break;
          }
          case "left": {
            const cursorYOffset = isFloatingTaller ? POLYGON_BUFFER / 2 : POLYGON_BUFFER * 4;
            const cursorPointOneY = isFloatingTaller ? y2 + cursorYOffset : cursorLeaveFromBottom ? y2 + cursorYOffset : y2 - cursorYOffset;
            const cursorPointTwoY = isFloatingTaller ? y2 - cursorYOffset : cursorLeaveFromBottom ? y2 + cursorYOffset : y2 - cursorYOffset;
            const cursorPointX = x2 + POLYGON_BUFFER + 1;
            const commonXTop = cursorLeaveFromBottom ? rect.right - POLYGON_BUFFER : isFloatingTaller ? rect.right - POLYGON_BUFFER : rect.left;
            const commonXBottom = cursorLeaveFromBottom ? isFloatingTaller ? rect.right - POLYGON_BUFFER : rect.left : rect.right - POLYGON_BUFFER;
            isInsidePolygon = isPointInQuadrilateral(clientX, clientY, commonXTop, rect.top, commonXBottom, rect.bottom, cursorPointX, cursorPointOneY, cursorPointX, cursorPointTwoY);
            break;
          }
          case "right": {
            const cursorYOffset = isFloatingTaller ? POLYGON_BUFFER / 2 : POLYGON_BUFFER * 4;
            const cursorPointOneY = isFloatingTaller ? y2 + cursorYOffset : cursorLeaveFromBottom ? y2 + cursorYOffset : y2 - cursorYOffset;
            const cursorPointTwoY = isFloatingTaller ? y2 - cursorYOffset : cursorLeaveFromBottom ? y2 + cursorYOffset : y2 - cursorYOffset;
            const cursorPointX = x2 - POLYGON_BUFFER;
            const commonXTop = cursorLeaveFromBottom ? rect.left + POLYGON_BUFFER : isFloatingTaller ? rect.left + POLYGON_BUFFER : rect.right;
            const commonXBottom = cursorLeaveFromBottom ? isFloatingTaller ? rect.left + POLYGON_BUFFER : rect.right : rect.left + POLYGON_BUFFER;
            isInsidePolygon = isPointInQuadrilateral(clientX, clientY, cursorPointX, cursorPointOneY, cursorPointX, cursorPointTwoY, commonXTop, rect.top, commonXBottom, rect.bottom);
            break;
          }
          default:
        }
        if (!isInsidePolygon) {
          closeIfNoOpenChild();
        } else if (!hasLanded) {
          timeout.start(40, closeIfNoOpenChild);
        }
        return void 0;
      };
    };
    fn.__options = {
      ...options,
      blockPointerEvents
    };
    return fn;
  }

  // node_modules/@base-ui/react/utils/popupStateMapping.mjs
  var CommonPopupDataAttributes = (function(CommonPopupDataAttributes2) {
    CommonPopupDataAttributes2["open"] = "data-open";
    CommonPopupDataAttributes2["closed"] = "data-closed";
    CommonPopupDataAttributes2[CommonPopupDataAttributes2["startingStyle"] = TransitionStatusDataAttributes.startingStyle] = "startingStyle";
    CommonPopupDataAttributes2[CommonPopupDataAttributes2["endingStyle"] = TransitionStatusDataAttributes.endingStyle] = "endingStyle";
    CommonPopupDataAttributes2["anchorHidden"] = "data-anchor-hidden";
    CommonPopupDataAttributes2["side"] = "data-side";
    CommonPopupDataAttributes2["align"] = "data-align";
    return CommonPopupDataAttributes2;
  })({});
  var CommonTriggerDataAttributes = /* @__PURE__ */ (function(CommonTriggerDataAttributes2) {
    CommonTriggerDataAttributes2["popupOpen"] = "data-popup-open";
    CommonTriggerDataAttributes2["pressed"] = "data-pressed";
    return CommonTriggerDataAttributes2;
  })({});
  var TRIGGER_HOOK = {
    [CommonTriggerDataAttributes.popupOpen]: ""
  };
  var PRESSABLE_TRIGGER_HOOK = {
    [CommonTriggerDataAttributes.popupOpen]: "",
    [CommonTriggerDataAttributes.pressed]: ""
  };
  var POPUP_OPEN_HOOK = {
    [CommonPopupDataAttributes.open]: ""
  };
  var POPUP_CLOSED_HOOK = {
    [CommonPopupDataAttributes.closed]: ""
  };
  var ANCHOR_HIDDEN_HOOK = {
    [CommonPopupDataAttributes.anchorHidden]: ""
  };
  var triggerOpenStateMapping2 = {
    open(value) {
      if (value) {
        return TRIGGER_HOOK;
      }
      return null;
    }
  };
  var popupStateMapping = {
    open(value) {
      if (value) {
        return POPUP_OPEN_HOOK;
      }
      return POPUP_CLOSED_HOOK;
    },
    anchorHidden(value) {
      if (value) {
        return ANCHOR_HIDDEN_HOOK;
      }
      return null;
    }
  };

  // node_modules/@base-ui/utils/inertValue.mjs
  function inertValue(value) {
    if (isReactVersionAtLeast(19)) {
      return value;
    }
    return value ? "true" : void 0;
  }

  // node_modules/@base-ui/react/utils/useAnchorPositioning.mjs
  var React36 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/floating-ui-react/middleware/arrow.mjs
  var baseArrow = (options) => ({
    name: "arrow",
    options,
    async fn(state) {
      const {
        x: x2,
        y: y2,
        placement,
        rects,
        platform: platform3,
        elements: elements2,
        middlewareData
      } = state;
      const {
        element,
        padding = 0,
        offsetParent = "real"
      } = evaluate(options, state) || {};
      if (element == null) {
        return {};
      }
      const paddingObject = getPaddingObject(padding);
      const coords = {
        x: x2,
        y: y2
      };
      const axis = getAlignmentAxis(placement);
      const length = getAxisLength(axis);
      const arrowDimensions = await platform3.getDimensions(element);
      const isYAxis = axis === "y";
      const minProp = isYAxis ? "top" : "left";
      const maxProp = isYAxis ? "bottom" : "right";
      const clientProp = isYAxis ? "clientHeight" : "clientWidth";
      const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];
      const startDiff = coords[axis] - rects.reference[axis];
      const arrowOffsetParent = offsetParent === "real" ? await platform3.getOffsetParent?.(element) : elements2.floating;
      let clientSize = elements2.floating[clientProp] || rects.floating[length];
      if (!clientSize || !await platform3.isElement?.(arrowOffsetParent)) {
        clientSize = elements2.floating[clientProp] || rects.floating[length];
      }
      const centerToReference = endDiff / 2 - startDiff / 2;
      const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;
      const minPadding = Math.min(paddingObject[minProp], largestPossiblePadding);
      const maxPadding = Math.min(paddingObject[maxProp], largestPossiblePadding);
      const min2 = minPadding;
      const max2 = clientSize - arrowDimensions[length] - maxPadding;
      const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;
      const offset4 = clamp(min2, center, max2);
      const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset4 && rects.reference[length] / 2 - (center < min2 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;
      const alignmentOffset = shouldAddOffset ? center < min2 ? center - min2 : center - max2 : 0;
      return {
        [axis]: coords[axis] + alignmentOffset,
        data: {
          [axis]: offset4,
          centerOffset: center - offset4 - alignmentOffset,
          ...shouldAddOffset && {
            alignmentOffset
          }
        },
        reset: shouldAddOffset
      };
    }
  });
  var arrow4 = (options, deps) => ({
    ...baseArrow(options),
    options: [options, deps]
  });

  // node_modules/@base-ui/react/utils/hideMiddleware.mjs
  var nativeHideFn = hide3().fn;
  var hide4 = {
    name: "hide",
    async fn(state) {
      const {
        width,
        height,
        x: x2,
        y: y2
      } = state.rects.reference;
      const anchorHidden = width === 0 && height === 0 && x2 === 0 && y2 === 0;
      const nativeHideResult = await nativeHideFn(state);
      return {
        data: {
          referenceHidden: nativeHideResult.data?.referenceHidden || anchorHidden
        }
      };
    }
  };

  // node_modules/@base-ui/react/utils/adaptiveOriginMiddleware.mjs
  var DEFAULT_SIDES = {
    sideX: "left",
    sideY: "top"
  };
  var adaptiveOrigin = {
    name: "adaptiveOrigin",
    async fn(state) {
      const {
        x: rawX,
        y: rawY,
        rects: {
          floating: floatRect
        },
        elements: {
          floating
        },
        platform: platform3,
        strategy,
        placement
      } = state;
      const win = getWindow(floating);
      const styles = win.getComputedStyle(floating);
      const hasTransition = styles.transitionDuration !== "0s" && styles.transitionDuration !== "";
      if (!hasTransition) {
        return {
          x: rawX,
          y: rawY,
          data: DEFAULT_SIDES
        };
      }
      const offsetParent = await platform3.getOffsetParent?.(floating);
      let offsetDimensions = {
        width: 0,
        height: 0
      };
      if (strategy === "fixed" && win?.visualViewport) {
        offsetDimensions = {
          width: win.visualViewport.width,
          height: win.visualViewport.height
        };
      } else if (offsetParent === win) {
        const doc = ownerDocument(floating);
        offsetDimensions = {
          width: doc.documentElement.clientWidth,
          height: doc.documentElement.clientHeight
        };
      } else if (await platform3.isElement?.(offsetParent)) {
        offsetDimensions = await platform3.getDimensions(offsetParent);
      }
      const currentSide = getSide(placement);
      let x2 = rawX;
      let y2 = rawY;
      if (currentSide === "left") {
        x2 = offsetDimensions.width - (rawX + floatRect.width);
      }
      if (currentSide === "top") {
        y2 = offsetDimensions.height - (rawY + floatRect.height);
      }
      const sideX = currentSide === "left" ? "right" : DEFAULT_SIDES.sideX;
      const sideY = currentSide === "top" ? "bottom" : DEFAULT_SIDES.sideY;
      return {
        x: x2,
        y: y2,
        data: {
          sideX,
          sideY
        }
      };
    }
  };

  // node_modules/@base-ui/react/utils/useAnchorPositioning.mjs
  function getLogicalSide(sideParam, renderedSide, isRtl) {
    const isLogicalSideParam = sideParam === "inline-start" || sideParam === "inline-end";
    const logicalRight = isRtl ? "inline-start" : "inline-end";
    const logicalLeft = isRtl ? "inline-end" : "inline-start";
    return {
      top: "top",
      right: isLogicalSideParam ? logicalRight : "right",
      bottom: "bottom",
      left: isLogicalSideParam ? logicalLeft : "left"
    }[renderedSide];
  }
  function getOffsetData(state, sideParam, isRtl) {
    const {
      rects,
      placement
    } = state;
    const data = {
      side: getLogicalSide(sideParam, getSide(placement), isRtl),
      align: getAlignment(placement) || "center",
      anchor: {
        width: rects.reference.width,
        height: rects.reference.height
      },
      positioner: {
        width: rects.floating.width,
        height: rects.floating.height
      }
    };
    return data;
  }
  function useAnchorPositioning(params) {
    const {
      // Public parameters
      anchor,
      positionMethod = "absolute",
      side: sideParam = "bottom",
      sideOffset = 0,
      align = "center",
      alignOffset = 0,
      collisionBoundary,
      collisionPadding: collisionPaddingParam = 5,
      sticky = false,
      arrowPadding = 5,
      disableAnchorTracking = false,
      inline: inlineMiddleware,
      // Private parameters
      keepMounted = false,
      floatingRootContext,
      mounted,
      collisionAvoidance,
      shiftCrossAxis = false,
      nodeId,
      adaptiveOrigin: adaptiveOrigin2,
      lazyFlip = false,
      externalTree
    } = params;
    const [mountSide, setMountSide] = React36.useState(null);
    if (!mounted && mountSide !== null) {
      setMountSide(null);
    }
    const collisionAvoidanceSide = collisionAvoidance.side || "flip";
    const collisionAvoidanceAlign = collisionAvoidance.align || "flip";
    const collisionAvoidanceFallbackAxisSide = collisionAvoidance.fallbackAxisSide || "end";
    const anchorFn = typeof anchor === "function" ? anchor : void 0;
    const anchorFnCallback = useStableCallback(anchorFn);
    const anchorDep = anchorFn ? anchorFnCallback : anchor;
    const anchorValueRef = useValueAsRef(anchor);
    const mountedRef = useValueAsRef(mounted);
    const direction = useDirection();
    const isRtl = direction === "rtl";
    const side = mountSide || {
      top: "top",
      right: "right",
      bottom: "bottom",
      left: "left",
      "inline-end": isRtl ? "left" : "right",
      "inline-start": isRtl ? "right" : "left"
    }[sideParam];
    const placement = align === "center" ? side : `${side}-${align}`;
    let collisionPadding = collisionPaddingParam;
    const bias = 1;
    const biasTop = sideParam === "bottom" ? bias : 0;
    const biasBottom = sideParam === "top" ? bias : 0;
    const biasLeft = sideParam === "right" ? bias : 0;
    const biasRight = sideParam === "left" ? bias : 0;
    if (typeof collisionPadding === "number") {
      collisionPadding = {
        top: collisionPadding + biasTop,
        right: collisionPadding + biasRight,
        bottom: collisionPadding + biasBottom,
        left: collisionPadding + biasLeft
      };
    } else if (collisionPadding) {
      collisionPadding = {
        top: (collisionPadding.top || 0) + biasTop,
        right: (collisionPadding.right || 0) + biasRight,
        bottom: (collisionPadding.bottom || 0) + biasBottom,
        left: (collisionPadding.left || 0) + biasLeft
      };
    }
    const commonCollisionProps = {
      boundary: collisionBoundary === "clipping-ancestors" ? "clippingAncestors" : collisionBoundary,
      padding: collisionPadding
    };
    const arrowRef = React36.useRef(null);
    const sideOffsetRef = useValueAsRef(sideOffset);
    const alignOffsetRef = useValueAsRef(alignOffset);
    const sideOffsetDep = typeof sideOffset !== "function" ? sideOffset : 0;
    const alignOffsetDep = typeof alignOffset !== "function" ? alignOffset : 0;
    const middleware = [];
    if (inlineMiddleware) {
      middleware.push(inlineMiddleware);
    }
    middleware.push(offset3((state) => {
      const data = getOffsetData(state, sideParam, isRtl);
      const sideAxis = typeof sideOffsetRef.current === "function" ? sideOffsetRef.current(data) : sideOffsetRef.current;
      const alignAxis = typeof alignOffsetRef.current === "function" ? alignOffsetRef.current(data) : alignOffsetRef.current;
      return {
        mainAxis: sideAxis,
        crossAxis: alignAxis,
        alignmentAxis: alignAxis
      };
    }, [sideOffsetDep, alignOffsetDep, isRtl, sideParam]));
    const shiftDisabled = collisionAvoidanceAlign === "none" && collisionAvoidanceSide !== "shift";
    const crossAxisShiftEnabled = !shiftDisabled && (sticky || shiftCrossAxis || collisionAvoidanceSide === "shift");
    const flipMiddleware = collisionAvoidanceSide === "none" ? null : flip3({
      ...commonCollisionProps,
      // Ensure the popup flips if it's been limited by its --available-height and it resizes.
      // Since the size() padding is smaller than the flip() padding, flip() will take precedence.
      padding: {
        top: collisionPadding.top + bias,
        right: collisionPadding.right + bias,
        bottom: collisionPadding.bottom + bias,
        left: collisionPadding.left + bias
      },
      mainAxis: !shiftCrossAxis && collisionAvoidanceSide === "flip",
      crossAxis: collisionAvoidanceAlign === "flip" ? "alignment" : false,
      fallbackAxisSideDirection: collisionAvoidanceFallbackAxisSide
    });
    const shiftMiddleware = shiftDisabled ? null : shift3((data) => {
      const html = ownerDocument(data.elements.floating).documentElement;
      return {
        ...commonCollisionProps,
        // Use the Layout Viewport to avoid shifting around when pinch-zooming
        // for context menus.
        rootBoundary: shiftCrossAxis ? {
          x: 0,
          y: 0,
          width: html.clientWidth,
          height: html.clientHeight
        } : void 0,
        mainAxis: collisionAvoidanceAlign !== "none",
        crossAxis: crossAxisShiftEnabled,
        limiter: sticky || shiftCrossAxis ? void 0 : limitShift3((limitData) => {
          if (!arrowRef.current) {
            return {};
          }
          const {
            width,
            height
          } = arrowRef.current.getBoundingClientRect();
          const sideAxis = getSideAxis(getSide(limitData.placement));
          const arrowSize = sideAxis === "y" ? width : height;
          const offsetAmount = sideAxis === "y" ? collisionPadding.left + collisionPadding.right : collisionPadding.top + collisionPadding.bottom;
          return {
            offset: arrowSize / 2 + offsetAmount / 2
          };
        })
      };
    }, [commonCollisionProps, sticky, shiftCrossAxis, collisionPadding, collisionAvoidanceAlign]);
    if (collisionAvoidanceSide === "shift" || collisionAvoidanceAlign === "shift" || align === "center") {
      middleware.push(shiftMiddleware, flipMiddleware);
    } else {
      middleware.push(flipMiddleware, shiftMiddleware);
    }
    middleware.push(size3({
      ...commonCollisionProps,
      apply({
        elements: {
          floating
        },
        availableWidth,
        availableHeight,
        rects
      }) {
        if (!mountedRef.current) {
          return;
        }
        const floatingStyle = floating.style;
        floatingStyle.setProperty("--available-width", `${availableWidth}px`);
        floatingStyle.setProperty("--available-height", `${availableHeight}px`);
        const dpr = getWindow(floating).devicePixelRatio || 1;
        const {
          x: x3,
          y: y3,
          width,
          height
        } = rects.reference;
        const anchorWidth = (Math.round((x3 + width) * dpr) - Math.round(x3 * dpr)) / dpr;
        const anchorHeight = (Math.round((y3 + height) * dpr) - Math.round(y3 * dpr)) / dpr;
        floatingStyle.setProperty("--anchor-width", `${anchorWidth}px`);
        floatingStyle.setProperty("--anchor-height", `${anchorHeight}px`);
      }
    }), arrow4((state) => ({
      // `transform-origin` calculations rely on an element existing. If the arrow hasn't been set,
      // we'll create a fake element.
      element: arrowRef.current || ownerDocument(state.elements.floating).createElement("div"),
      padding: arrowPadding,
      offsetParent: "floating"
    }), [arrowPadding]), {
      name: "transformOrigin",
      fn(state) {
        const {
          elements: elements3,
          middlewareData: middlewareData2,
          placement: renderedPlacement2,
          rects,
          y: y3
        } = state;
        const currentRenderedSide = getSide(renderedPlacement2);
        const currentRenderedAxis = getSideAxis(currentRenderedSide);
        const arrowEl = arrowRef.current;
        const arrowX = middlewareData2.arrow?.x || 0;
        const arrowY = middlewareData2.arrow?.y || 0;
        const arrowWidth = arrowEl?.clientWidth || 0;
        const arrowHeight = arrowEl?.clientHeight || 0;
        const transformX = arrowX + arrowWidth / 2;
        const transformY = arrowY + arrowHeight / 2;
        const shiftY = Math.abs(middlewareData2.shift?.y || 0);
        const halfAnchorHeight = rects.reference.height / 2;
        const sideOffsetValue = typeof sideOffset === "function" ? sideOffset(getOffsetData(state, sideParam, isRtl)) : sideOffset;
        const isOverlappingAnchor = shiftY > sideOffsetValue;
        const adjacentTransformOrigin = {
          top: `${transformX}px calc(100% + ${sideOffsetValue}px)`,
          bottom: `${transformX}px ${-sideOffsetValue}px`,
          left: `calc(100% + ${sideOffsetValue}px) ${transformY}px`,
          right: `${-sideOffsetValue}px ${transformY}px`
        }[currentRenderedSide];
        const overlapTransformOrigin = `${transformX}px ${rects.reference.y + halfAnchorHeight - y3}px`;
        elements3.floating.style.setProperty("--transform-origin", crossAxisShiftEnabled && currentRenderedAxis === "y" && isOverlappingAnchor ? overlapTransformOrigin : adjacentTransformOrigin);
        return {};
      }
    }, hide4, adaptiveOrigin2);
    useIsoLayoutEffect(() => {
      if (!mounted && floatingRootContext) {
        floatingRootContext.update({
          referenceElement: null,
          floatingElement: null,
          domReferenceElement: null,
          positionReference: null
        });
      }
    }, [mounted, floatingRootContext]);
    const autoUpdateOptions = React36.useMemo(() => ({
      elementResize: !disableAnchorTracking && typeof ResizeObserver !== "undefined",
      layoutShift: !disableAnchorTracking && typeof IntersectionObserver !== "undefined"
    }), [disableAnchorTracking]);
    const {
      refs,
      elements: elements2,
      x: x2,
      y: y2,
      middlewareData,
      update: update4,
      placement: renderedPlacement,
      context,
      isPositioned,
      floatingStyles: originalFloatingStyles
    } = useFloating2({
      rootContext: floatingRootContext,
      open: keepMounted ? mounted : void 0,
      placement,
      middleware,
      strategy: positionMethod,
      whileElementsMounted: keepMounted ? void 0 : (...args) => autoUpdate(...args, autoUpdateOptions),
      nodeId,
      externalTree
    });
    const {
      sideX,
      sideY
    } = middlewareData.adaptiveOrigin || DEFAULT_SIDES;
    const resolvedPosition = isPositioned ? positionMethod : "fixed";
    const floatingStyles = React36.useMemo(() => {
      const base = adaptiveOrigin2 ? {
        position: resolvedPosition,
        [sideX]: x2,
        [sideY]: y2
      } : {
        position: resolvedPosition,
        ...originalFloatingStyles
      };
      if (!isPositioned) {
        base.opacity = 0;
      }
      return base;
    }, [adaptiveOrigin2, resolvedPosition, sideX, x2, sideY, y2, originalFloatingStyles, isPositioned]);
    const registeredPositionReferenceRef = React36.useRef(null);
    useIsoLayoutEffect(() => {
      if (!mounted) {
        return;
      }
      const anchorValue = anchorValueRef.current;
      const resolvedAnchor = typeof anchorValue === "function" ? anchorValue() : anchorValue;
      const unwrappedElement = (isRef(resolvedAnchor) ? resolvedAnchor.current : resolvedAnchor) || null;
      const finalAnchor = unwrappedElement || null;
      if (finalAnchor !== registeredPositionReferenceRef.current) {
        refs.setPositionReference(finalAnchor);
        registeredPositionReferenceRef.current = finalAnchor;
      }
    }, [mounted, refs, anchorDep, anchorValueRef]);
    React36.useEffect(() => {
      if (!mounted) {
        return;
      }
      const anchorValue = anchorValueRef.current;
      if (typeof anchorValue === "function") {
        return;
      }
      if (isRef(anchorValue) && anchorValue.current !== registeredPositionReferenceRef.current) {
        refs.setPositionReference(anchorValue.current);
        registeredPositionReferenceRef.current = anchorValue.current;
      }
    }, [mounted, refs, anchorDep, anchorValueRef]);
    React36.useEffect(() => {
      if (keepMounted && mounted && elements2.reference && elements2.floating) {
        return autoUpdate(elements2.reference, elements2.floating, update4, autoUpdateOptions);
      }
      return void 0;
    }, [keepMounted, mounted, elements2, update4, autoUpdateOptions]);
    const renderedSide = getSide(renderedPlacement);
    const logicalRenderedSide = getLogicalSide(sideParam, renderedSide, isRtl);
    const renderedAlign = getAlignment(renderedPlacement) || "center";
    const anchorHidden = Boolean(middlewareData.hide?.referenceHidden);
    useIsoLayoutEffect(() => {
      if (lazyFlip && mounted && isPositioned) {
        setMountSide(renderedSide);
      }
    }, [lazyFlip, mounted, isPositioned, renderedSide]);
    const arrowStyles = React36.useMemo(() => ({
      position: "absolute",
      top: middlewareData.arrow?.y,
      left: middlewareData.arrow?.x
    }), [middlewareData.arrow]);
    const arrowUncentered = middlewareData.arrow?.centerOffset !== 0;
    return React36.useMemo(() => ({
      positionerStyles: floatingStyles,
      arrowStyles,
      arrowRef,
      arrowUncentered,
      side: logicalRenderedSide,
      align: renderedAlign,
      physicalSide: renderedSide,
      anchorHidden,
      refs,
      context,
      isPositioned,
      update: update4
    }), [floatingStyles, arrowStyles, arrowRef, arrowUncentered, logicalRenderedSide, renderedAlign, renderedSide, anchorHidden, refs, context, isPositioned, update4]);
  }
  function isRef(param) {
    return param != null && "current" in param;
  }

  // node_modules/@base-ui/react/utils/getDisabledMountTransitionStyles.mjs
  function getDisabledMountTransitionStyles(transitionStatus) {
    return transitionStatus === "starting" ? DISABLED_TRANSITIONS_STYLE : EMPTY_OBJECT;
  }

  // node_modules/@base-ui/react/utils/usePositioner.mjs
  function usePositioner(componentProps, state, {
    styles,
    transitionStatus,
    props,
    refs,
    hidden,
    inert = false
  }) {
    const style = {
      ...styles
    };
    if (inert) {
      style.pointerEvents = "none";
    }
    return useRenderElement("div", componentProps, {
      state,
      ref: refs,
      props: [{
        role: "presentation",
        hidden,
        style
      }, getDisabledMountTransitionStyles(transitionStatus), props],
      stateAttributesMapping: popupStateMapping
    });
  }

  // node_modules/@base-ui/react/collapsible/index.parts.mjs
  var index_parts_exports = {};
  __export(index_parts_exports, {
    Panel: () => CollapsiblePanel,
    Root: () => CollapsibleRoot,
    Trigger: () => CollapsibleTrigger
  });

  // node_modules/@base-ui/react/collapsible/root/CollapsibleRoot.mjs
  var React37 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/collapsible/root/stateAttributesMapping.mjs
  var collapsibleStateAttributesMapping = {
    ...collapsibleOpenStateMapping,
    ...transitionStatusMapping
  };

  // node_modules/@base-ui/react/collapsible/root/CollapsibleRoot.mjs
  var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
  var CollapsibleRoot = /* @__PURE__ */ React37.forwardRef(function CollapsibleRoot2(componentProps, forwardedRef) {
    const {
      render: render4,
      className,
      defaultOpen = false,
      disabled: disabled2 = false,
      onOpenChange: onOpenChangeProp,
      open,
      style,
      ...elementProps
    } = componentProps;
    const onOpenChange = useStableCallback(onOpenChangeProp);
    const collapsible = useCollapsibleRoot({
      open,
      defaultOpen,
      onOpenChange,
      disabled: disabled2
    });
    const state = React37.useMemo(() => ({
      open: collapsible.open,
      disabled: collapsible.disabled,
      transitionStatus: collapsible.transitionStatus
    }), [collapsible.open, collapsible.disabled, collapsible.transitionStatus]);
    const contextValue = React37.useMemo(() => ({
      ...collapsible,
      onOpenChange,
      state
    }), [collapsible, onOpenChange, state]);
    const element = useRenderElement("div", componentProps, {
      state,
      ref: forwardedRef,
      props: elementProps,
      stateAttributesMapping: collapsibleStateAttributesMapping
    });
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(CollapsibleRootContext.Provider, {
      value: contextValue,
      children: element
    });
  });
  if (true) CollapsibleRoot.displayName = "CollapsibleRoot";

  // node_modules/@base-ui/react/collapsible/trigger/CollapsibleTrigger.mjs
  var React38 = __toESM(require_react(), 1);
  var stateAttributesMapping = {
    ...triggerOpenStateMapping,
    ...transitionStatusMapping
  };
  var CollapsibleTrigger = /* @__PURE__ */ React38.forwardRef(function CollapsibleTrigger2(componentProps, forwardedRef) {
    const {
      panelId,
      open,
      handleTrigger,
      state,
      disabled: contextDisabled
    } = useCollapsibleRootContext();
    const {
      className,
      disabled: disabled2 = contextDisabled,
      render: render4,
      nativeButton = true,
      style,
      ...elementProps
    } = componentProps;
    const {
      getButtonProps,
      buttonRef
    } = useButton({
      disabled: disabled2,
      focusableWhenDisabled: true,
      native: nativeButton
    });
    const element = useRenderElement("button", componentProps, {
      state,
      ref: [forwardedRef, buttonRef],
      props: [{
        "aria-controls": open ? panelId : void 0,
        "aria-expanded": open,
        onClick: handleTrigger
      }, elementProps, getButtonProps],
      stateAttributesMapping
    });
    return element;
  });
  if (true) CollapsibleTrigger.displayName = "CollapsibleTrigger";

  // node_modules/@base-ui/react/collapsible/panel/CollapsiblePanel.mjs
  var React39 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/collapsible/panel/CollapsiblePanelCssVars.mjs
  var CollapsiblePanelCssVars = /* @__PURE__ */ (function(CollapsiblePanelCssVars2) {
    CollapsiblePanelCssVars2["collapsiblePanelHeight"] = "--collapsible-panel-height";
    CollapsiblePanelCssVars2["collapsiblePanelWidth"] = "--collapsible-panel-width";
    return CollapsiblePanelCssVars2;
  })({});

  // node_modules/@base-ui/react/collapsible/panel/CollapsiblePanel.mjs
  var CollapsiblePanel = /* @__PURE__ */ React39.forwardRef(function CollapsiblePanel2(componentProps, forwardedRef) {
    const {
      className,
      hiddenUntilFound: hiddenUntilFoundProp,
      keepMounted: keepMountedProp,
      render: render4,
      id: idProp,
      style,
      ...elementProps
    } = componentProps;
    if (true) {
      useIsoLayoutEffect(() => {
        if (hiddenUntilFoundProp && keepMountedProp === false) {
          warn("The `keepMounted={false}` prop on `Collapsible.Panel` is ignored when `hiddenUntilFound` is enabled, since the panel must remain mounted while closed.");
        }
      }, [hiddenUntilFoundProp, keepMountedProp]);
    }
    const {
      mounted,
      onOpenChange,
      open,
      panelId,
      setMounted,
      setPanelIdState,
      setOpen,
      state,
      transitionStatus
    } = useCollapsibleRootContext();
    const hiddenUntilFound = hiddenUntilFoundProp ?? false;
    const keepMounted = keepMountedProp ?? false;
    useIsoLayoutEffect(() => {
      if (idProp) {
        setPanelIdState(idProp);
        return () => {
          setPanelIdState(void 0);
        };
      }
      return void 0;
    }, [idProp, setPanelIdState]);
    const {
      height,
      props,
      ref,
      shouldPreventOpenAnimation,
      shouldRender,
      transitionStatus: panelTransitionStatus,
      width
    } = useCollapsiblePanel({
      externalRef: forwardedRef,
      hiddenUntilFound,
      id: panelId,
      keepMounted,
      mounted,
      onOpenChange,
      open,
      setMounted,
      setOpen,
      transitionStatus
    });
    const panelState = {
      ...state,
      transitionStatus: panelTransitionStatus
    };
    const resolvedStyle = resolveStyle(style, panelState);
    const element = useRenderElement("div", {
      ...componentProps,
      style: void 0
    }, {
      state: panelState,
      ref,
      props: [
        props,
        {
          style: {
            [CollapsiblePanelCssVars.collapsiblePanelHeight]: height === void 0 ? "auto" : `${height}px`,
            [CollapsiblePanelCssVars.collapsiblePanelWidth]: width === void 0 ? "auto" : `${width}px`
          }
        },
        elementProps,
        resolvedStyle ? {
          style: resolvedStyle
        } : void 0,
        // Resolve the public `style` prop so temporary `animationName: 'none'`
        // can still win after user's inline styles have been merged.
        shouldPreventOpenAnimation ? {
          style: {
            animationName: "none"
          }
        } : void 0
      ],
      stateAttributesMapping: collapsibleStateAttributesMapping
    });
    if (!shouldRender) {
      return null;
    }
    return element;
  });
  if (true) CollapsiblePanel.displayName = "CollapsiblePanel";

  // node_modules/@base-ui/react/utils/usePopupViewport.mjs
  var React42 = __toESM(require_react(), 1);
  var ReactDOM6 = __toESM(require_react_dom(), 1);

  // node_modules/@base-ui/utils/usePreviousValue.mjs
  var React40 = __toESM(require_react(), 1);
  function usePreviousValue(value) {
    const [state, setState] = React40.useState({
      current: value,
      previous: null
    });
    if (value !== state.current) {
      setState({
        current: value,
        previous: state.current
      });
    }
    return state.previous;
  }

  // node_modules/@base-ui/react/utils/usePopupAutoResize.mjs
  var React41 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/utils/getCssDimensions.mjs
  function getCssDimensions2(element) {
    const css = getComputedStyle2(element);
    let width = parseFloat(css.width) || 0;
    let height = parseFloat(css.height) || 0;
    const hasOffset = isHTMLElement(element);
    const offsetWidth = hasOffset ? element.offsetWidth : width;
    const offsetHeight = hasOffset ? element.offsetHeight : height;
    const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
    if (shouldFallback) {
      width = offsetWidth;
      height = offsetHeight;
    }
    return {
      width,
      height
    };
  }

  // node_modules/@base-ui/react/utils/usePopupAutoResize.mjs
  function usePopupAutoResize(parameters) {
    const {
      popupElement,
      positionerElement,
      content,
      mounted,
      onMeasureLayout: onMeasureLayoutParam,
      onMeasureLayoutComplete: onMeasureLayoutCompleteParam,
      side,
      direction
    } = parameters;
    const runOnceAnimationsFinish = useAnimationsFinished(popupElement, true, false);
    const animationFrame = useAnimationFrame();
    const committedDimensionsRef = React41.useRef(null);
    const isInitialRenderRef = React41.useRef(true);
    const restoreAnchoringStylesRef = React41.useRef(NOOP);
    const onMeasureLayout = useStableCallback(onMeasureLayoutParam);
    const onMeasureLayoutComplete = useStableCallback(onMeasureLayoutCompleteParam);
    const anchoringStyles = React41.useMemo(() => {
      let isOriginSide = side === "top";
      let isPhysicalLeft = side === "left";
      if (direction === "rtl") {
        isOriginSide = isOriginSide || side === "inline-end";
        isPhysicalLeft = isPhysicalLeft || side === "inline-end";
      } else {
        isOriginSide = isOriginSide || side === "inline-start";
        isPhysicalLeft = isPhysicalLeft || side === "inline-start";
      }
      return isOriginSide ? {
        position: "absolute",
        [side === "top" ? "bottom" : "top"]: "0",
        [isPhysicalLeft ? "right" : "left"]: "0"
      } : EMPTY_OBJECT;
    }, [side, direction]);
    useIsoLayoutEffect(() => {
      if (!mounted) {
        restoreAnchoringStylesRef.current = NOOP;
        isInitialRenderRef.current = true;
        committedDimensionsRef.current = null;
        return void 0;
      }
      if (!popupElement || !positionerElement) {
        return void 0;
      }
      restoreAnchoringStylesRef.current = applyElementStyles(popupElement, anchoringStyles);
      setPopupCssSize(popupElement, "auto");
      const restorePopupPosition = overrideElementStyle(popupElement, "position", "static");
      const restorePopupTransform = overrideElementStyle(popupElement, "transform", "none");
      const restorePopupScale = overrideElementStyle(popupElement, "scale", "1");
      const restorePositionerAvailableSize = applyElementStyles(positionerElement, {
        "--available-width": "max-content",
        "--available-height": "max-content"
      });
      function restoreMeasurementOverrides() {
        restorePopupPosition();
        restorePopupTransform();
        restorePositionerAvailableSize();
      }
      function restoreMeasurementOverridesIncludingScale() {
        restoreMeasurementOverrides();
        restorePopupScale();
      }
      onMeasureLayout?.();
      if (isInitialRenderRef.current || committedDimensionsRef.current === null) {
        setPositionerCssSize(positionerElement, "max-content");
        const dimensions = getCssDimensions2(popupElement);
        committedDimensionsRef.current = dimensions;
        setPositionerCssSize(positionerElement, dimensions);
        restoreMeasurementOverridesIncludingScale();
        onMeasureLayoutComplete?.(null, dimensions);
        isInitialRenderRef.current = false;
        return () => {
          restoreAnchoringStylesRef.current();
          restoreAnchoringStylesRef.current = NOOP;
        };
      }
      setPositionerCssSize(positionerElement, "max-content");
      const previousDimensions = committedDimensionsRef.current;
      const newDimensions = getCssDimensions2(popupElement);
      committedDimensionsRef.current = newDimensions;
      setPopupCssSize(popupElement, previousDimensions);
      restoreMeasurementOverridesIncludingScale();
      onMeasureLayoutComplete?.(previousDimensions, newDimensions);
      setPositionerCssSize(positionerElement, newDimensions);
      const abortController = new AbortController();
      animationFrame.request(() => {
        setPopupCssSize(popupElement, newDimensions);
        runOnceAnimationsFinish(() => {
          popupElement.style.setProperty("--popup-width", "auto");
          popupElement.style.setProperty("--popup-height", "auto");
        }, abortController.signal);
      });
      return () => {
        abortController.abort();
        animationFrame.cancel();
        restoreAnchoringStylesRef.current();
        restoreAnchoringStylesRef.current = NOOP;
      };
    }, [content, popupElement, positionerElement, runOnceAnimationsFinish, animationFrame, mounted, onMeasureLayout, onMeasureLayoutComplete, anchoringStyles]);
  }
  function overrideElementStyle(element, property, value) {
    const originalValue = element.style.getPropertyValue(property);
    element.style.setProperty(property, value);
    return () => {
      element.style.setProperty(property, originalValue);
    };
  }
  function applyElementStyles(element, styles) {
    const restorers = [];
    for (const [key, value] of Object.entries(styles)) {
      restorers.push(overrideElementStyle(element, key, value));
    }
    return restorers.length ? () => {
      restorers.forEach((restore) => restore());
    } : NOOP;
  }
  function setPopupCssSize(popupElement, size4) {
    const width = size4 === "auto" ? "auto" : `${size4.width}px`;
    const height = size4 === "auto" ? "auto" : `${size4.height}px`;
    popupElement.style.setProperty("--popup-width", width);
    popupElement.style.setProperty("--popup-height", height);
  }
  function setPositionerCssSize(positionerElement, size4) {
    const width = size4 === "max-content" ? "max-content" : `${size4.width}px`;
    const height = size4 === "max-content" ? "max-content" : `${size4.height}px`;
    positionerElement.style.setProperty("--positioner-width", width);
    positionerElement.style.setProperty("--positioner-height", height);
  }

  // node_modules/@base-ui/react/utils/usePopupViewport.mjs
  var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
  function usePopupViewport(parameters) {
    const {
      store: store2,
      side,
      cssVars,
      children
    } = parameters;
    const direction = useDirection();
    const activeTrigger = store2.useState("activeTriggerElement");
    const activeTriggerId = store2.useState("activeTriggerId");
    const open = store2.useState("open");
    const payload = store2.useState("payload");
    const mounted = store2.useState("mounted");
    const popupElement = store2.useState("popupElement");
    const positionerElement = store2.useState("positionerElement");
    const previousActiveTrigger = usePreviousValue(open ? activeTrigger : null);
    const currentContentKey = usePopupContentKey(activeTriggerId, payload);
    const capturedNodeRef = React42.useRef(null);
    const [previousContentNode, setPreviousContentNode] = React42.useState(null);
    const [newTriggerOffset, setNewTriggerOffset] = React42.useState(null);
    const currentContainerRef = React42.useRef(null);
    const previousContainerRef = React42.useRef(null);
    const onAnimationsFinished = useAnimationsFinished(currentContainerRef, true, false);
    const cleanupFrame = useAnimationFrame();
    const [previousContentDimensions, setPreviousContentDimensions] = React42.useState(null);
    const [showStartingStyleAttribute, setShowStartingStyleAttribute] = React42.useState(false);
    useIsoLayoutEffect(() => {
      store2.set("hasViewport", true);
      return () => {
        store2.set("hasViewport", false);
      };
    }, [store2]);
    const handleMeasureLayout = useStableCallback(() => {
      currentContainerRef.current?.style.setProperty("animation", "none");
      currentContainerRef.current?.style.setProperty("transition", "none");
      previousContainerRef.current?.style.setProperty("display", "none");
    });
    const handleMeasureLayoutComplete = useStableCallback((previousDimensions) => {
      currentContainerRef.current?.style.removeProperty("animation");
      currentContainerRef.current?.style.removeProperty("transition");
      previousContainerRef.current?.style.removeProperty("display");
      if (previousDimensions) {
        setPreviousContentDimensions(previousDimensions);
      }
    });
    const lastHandledTriggerRef = React42.useRef(null);
    useIsoLayoutEffect(() => {
      if (!open || !mounted) {
        lastHandledTriggerRef.current = null;
      }
    }, [open, mounted]);
    useIsoLayoutEffect(() => {
      if (activeTrigger && previousActiveTrigger && activeTrigger !== previousActiveTrigger && lastHandledTriggerRef.current !== activeTrigger && capturedNodeRef.current) {
        setPreviousContentNode(capturedNodeRef.current);
        setShowStartingStyleAttribute(true);
        const offset4 = calculateRelativePosition(previousActiveTrigger, activeTrigger);
        setNewTriggerOffset(offset4);
        cleanupFrame.request(() => {
          ReactDOM6.flushSync(() => {
            setShowStartingStyleAttribute(false);
          });
          onAnimationsFinished(() => {
            setPreviousContentNode(null);
            setPreviousContentDimensions(null);
            capturedNodeRef.current = null;
          });
        });
        lastHandledTriggerRef.current = activeTrigger;
      }
    }, [activeTrigger, previousActiveTrigger, previousContentNode, onAnimationsFinished, cleanupFrame]);
    useIsoLayoutEffect(() => {
      const source = currentContainerRef.current;
      if (!source) {
        return;
      }
      const wrapper = ownerDocument(source).createElement("div");
      for (const child of Array.from(source.childNodes)) {
        wrapper.appendChild(child.cloneNode(true));
      }
      capturedNodeRef.current = wrapper;
    });
    const isTransitioning = previousContentNode != null;
    let childrenToRender;
    if (!isTransitioning) {
      childrenToRender = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("div", {
        "data-current": true,
        ref: currentContainerRef,
        children
      }, currentContentKey);
    } else {
      childrenToRender = /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(React42.Fragment, {
        children: [/* @__PURE__ */ (0, import_jsx_runtime6.jsx)("div", {
          "data-previous": true,
          inert: inertValue(true),
          ref: previousContainerRef,
          style: {
            ...previousContentDimensions ? {
              [cssVars.popupWidth]: `${previousContentDimensions.width}px`,
              [cssVars.popupHeight]: `${previousContentDimensions.height}px`
            } : null,
            position: "absolute"
          },
          "data-ending-style": showStartingStyleAttribute ? void 0 : ""
        }, "previous"), /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("div", {
          "data-current": true,
          ref: currentContainerRef,
          "data-starting-style": showStartingStyleAttribute ? "" : void 0,
          children
        }, currentContentKey)]
      });
    }
    useIsoLayoutEffect(() => {
      const container = previousContainerRef.current;
      if (!container || !previousContentNode) {
        return;
      }
      container.replaceChildren(...Array.from(previousContentNode.childNodes));
    }, [previousContentNode]);
    usePopupAutoResize({
      popupElement,
      positionerElement,
      mounted,
      content: payload,
      onMeasureLayout: handleMeasureLayout,
      onMeasureLayoutComplete: handleMeasureLayoutComplete,
      side,
      direction
    });
    const state = {
      activationDirection: getActivationDirection(newTriggerOffset),
      transitioning: isTransitioning
    };
    return {
      children: childrenToRender,
      state
    };
  }
  function getActivationDirection(offset4) {
    if (!offset4) {
      return void 0;
    }
    return `${getValueWithTolerance(offset4.horizontal, 5, "right", "left")} ${getValueWithTolerance(offset4.vertical, 5, "down", "up")}`;
  }
  function getValueWithTolerance(value, tolerance, positiveLabel, negativeLabel) {
    if (value > tolerance) {
      return positiveLabel;
    }
    if (value < -tolerance) {
      return negativeLabel;
    }
    return "";
  }
  function calculateRelativePosition(from, to2) {
    const fromRect = from.getBoundingClientRect();
    const toRect = to2.getBoundingClientRect();
    const fromCenter = {
      x: fromRect.left + fromRect.width / 2,
      y: fromRect.top + fromRect.height / 2
    };
    const toCenter = {
      x: toRect.left + toRect.width / 2,
      y: toRect.top + toRect.height / 2
    };
    return {
      horizontal: toCenter.x - fromCenter.x,
      vertical: toCenter.y - fromCenter.y
    };
  }
  function usePopupContentKey(activeTriggerId, payload) {
    const [contentKey, setContentKey] = React42.useState(0);
    const previousActiveTriggerIdRef = React42.useRef(activeTriggerId);
    const previousPayloadRef = React42.useRef(payload);
    const pendingPayloadUpdateRef = React42.useRef(false);
    useIsoLayoutEffect(() => {
      const previousActiveTriggerId = previousActiveTriggerIdRef.current;
      const previousPayload = previousPayloadRef.current;
      const triggerIdChanged = activeTriggerId !== previousActiveTriggerId;
      const payloadChanged = payload !== previousPayload;
      if (triggerIdChanged) {
        setContentKey((value) => value + 1);
        pendingPayloadUpdateRef.current = !payloadChanged;
      } else if (pendingPayloadUpdateRef.current && payloadChanged) {
        setContentKey((value) => value + 1);
        pendingPayloadUpdateRef.current = false;
      }
      previousActiveTriggerIdRef.current = activeTriggerId;
      previousPayloadRef.current = payload;
    }, [activeTriggerId, payload]);
    return `${activeTriggerId ?? "current"}-${contentKey}`;
  }

  // node_modules/@base-ui/react/utils/FloatingPortalLite.mjs
  var React43 = __toESM(require_react(), 1);
  var ReactDOM7 = __toESM(require_react_dom(), 1);
  var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
  var FloatingPortalLite = /* @__PURE__ */ React43.forwardRef(function FloatingPortalLite2(componentProps, forwardedRef) {
    const {
      children,
      container,
      className,
      render: render4,
      style,
      ...elementProps
    } = componentProps;
    const {
      portalNode,
      portalSubtree
    } = useFloatingPortalNode({
      container,
      ref: forwardedRef,
      componentProps,
      elementProps
    });
    if (!portalSubtree && !portalNode) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(React43.Fragment, {
      children: [portalSubtree, portalNode && /* @__PURE__ */ ReactDOM7.createPortal(children, portalNode)]
    });
  });
  if (true) FloatingPortalLite.displayName = "FloatingPortalLite";

  // node_modules/@base-ui/react/tooltip/index.parts.mjs
  var index_parts_exports2 = {};
  __export(index_parts_exports2, {
    Arrow: () => TooltipArrow,
    Handle: () => TooltipHandle,
    Popup: () => TooltipPopup,
    Portal: () => TooltipPortal,
    Positioner: () => TooltipPositioner,
    Provider: () => TooltipProvider,
    Root: () => TooltipRoot,
    Trigger: () => TooltipTrigger,
    Viewport: () => TooltipViewport,
    createHandle: () => createTooltipHandle
  });

  // node_modules/@base-ui/react/tooltip/root/TooltipRoot.mjs
  var React46 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/tooltip/root/TooltipRootContext.mjs
  var React44 = __toESM(require_react(), 1);
  var TooltipRootContext = /* @__PURE__ */ React44.createContext(void 0);
  if (true) TooltipRootContext.displayName = "TooltipRootContext";
  function useTooltipRootContext(optional) {
    const context = React44.useContext(TooltipRootContext);
    if (context === void 0 && !optional) {
      throw new Error(true ? "Base UI: TooltipRootContext is missing. Tooltip parts must be placed within <Tooltip.Root>." : formatErrorMessage_default(72));
    }
    return context;
  }

  // node_modules/@base-ui/react/tooltip/store/TooltipStore.mjs
  var React45 = __toESM(require_react(), 1);
  var selectors2 = {
    ...popupStoreSelectors,
    disabled: createSelector2((state) => state.disabled),
    instantType: createSelector2((state) => state.instantType),
    isInstantPhase: createSelector2((state) => state.isInstantPhase),
    trackCursorAxis: createSelector2((state) => state.trackCursorAxis),
    disableHoverablePopup: createSelector2((state) => state.disableHoverablePopup),
    lastOpenChangeReason: createSelector2((state) => state.openChangeReason),
    closeOnClick: createSelector2((state) => state.closeOnClick),
    closeDelay: createSelector2((state) => state.closeDelay),
    hasViewport: createSelector2((state) => state.hasViewport)
  };
  var TooltipStore = class _TooltipStore extends ReactStore {
    constructor(initialState, floatingId, nested = false) {
      const triggerElements = new PopupTriggerMap();
      const state = {
        ...createInitialState(),
        ...initialState
      };
      state.floatingRootContext = createPopupFloatingRootContext(triggerElements, floatingId, nested);
      super(state, {
        popupRef: /* @__PURE__ */ React45.createRef(),
        onOpenChange: void 0,
        onOpenChangeComplete: void 0,
        triggerElements
      }, selectors2);
    }
    setOpen = (nextOpen, eventDetails) => {
      applyPopupOpenChange(this, nextOpen, eventDetails, {
        extraState: {
          openChangeReason: eventDetails.reason
        }
      });
    };
    // Used by trigger clicks to clear a delayed hover open without reporting a public open-state change.
    cancelPendingOpen(event) {
      this.state.floatingRootContext.dispatchOpenChange(false, createChangeEventDetails(reason_parts_exports.triggerPress, event));
    }
    static useStore(externalStore, initialState) {
      const store2 = usePopupStore(externalStore, (floatingId, nested) => new _TooltipStore(initialState, floatingId, nested)).store;
      return store2;
    }
  };
  function createInitialState() {
    return {
      ...createInitialPopupStoreState(),
      disabled: false,
      instantType: void 0,
      isInstantPhase: false,
      trackCursorAxis: "none",
      disableHoverablePopup: false,
      openChangeReason: null,
      closeOnClick: true,
      closeDelay: 0,
      hasViewport: false
    };
  }

  // node_modules/@base-ui/react/tooltip/root/TooltipRoot.mjs
  var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
  var TooltipRoot = fastComponent(function TooltipRoot2(props) {
    const {
      disabled: disabled2 = false,
      defaultOpen = false,
      open: openProp,
      disableHoverablePopup = false,
      trackCursorAxis = "none",
      actionsRef,
      onOpenChange,
      onOpenChangeComplete,
      handle,
      triggerId: triggerIdProp,
      defaultTriggerId: defaultTriggerIdProp = null,
      children
    } = props;
    const store2 = TooltipStore.useStore(handle?.store, {
      open: defaultOpen,
      openProp,
      activeTriggerId: defaultTriggerIdProp,
      triggerIdProp
    });
    useInitialOpenSync(store2, openProp, defaultOpen, defaultTriggerIdProp);
    store2.useControlledProp("openProp", openProp);
    store2.useControlledProp("triggerIdProp", triggerIdProp);
    store2.useContextCallback("onOpenChange", onOpenChange);
    store2.useContextCallback("onOpenChangeComplete", onOpenChangeComplete);
    const openState = store2.useState("open");
    const open = !disabled2 && openState;
    const activeTriggerId = store2.useState("activeTriggerId");
    const mounted = store2.useState("mounted");
    const payload = store2.useState("payload");
    store2.useSyncedValues({
      trackCursorAxis,
      disableHoverablePopup
    });
    store2.useSyncedValue("disabled", disabled2);
    useImplicitActiveTrigger(store2, {
      closeOnActiveTriggerUnmount: true
    });
    const {
      forceUnmount,
      transitionStatus
    } = useOpenStateTransitions(open, store2);
    const isInstantPhase = store2.useState("isInstantPhase");
    const instantType = store2.useState("instantType");
    const lastOpenChangeReason = store2.useState("lastOpenChangeReason");
    const previousInstantTypeRef = React46.useRef(null);
    useIsoLayoutEffect(() => {
      if (openState && disabled2) {
        store2.setOpen(false, createChangeEventDetails(reason_parts_exports.disabled));
      }
    }, [openState, disabled2, store2]);
    useIsoLayoutEffect(() => {
      if (transitionStatus === "ending" && lastOpenChangeReason === reason_parts_exports.none || transitionStatus !== "ending" && isInstantPhase) {
        if (instantType !== "delay") {
          previousInstantTypeRef.current = instantType;
        }
        store2.set("instantType", "delay");
      } else if (previousInstantTypeRef.current !== null) {
        store2.set("instantType", previousInstantTypeRef.current);
        previousInstantTypeRef.current = null;
      }
    }, [transitionStatus, isInstantPhase, lastOpenChangeReason, instantType, store2]);
    useIsoLayoutEffect(() => {
      if (open) {
        if (activeTriggerId == null) {
          store2.set("payload", void 0);
        }
      }
    }, [store2, activeTriggerId, open]);
    const handleImperativeClose = React46.useCallback(() => {
      store2.setOpen(false, createChangeEventDetails(reason_parts_exports.imperativeAction));
    }, [store2]);
    React46.useImperativeHandle(actionsRef, () => ({
      unmount: forceUnmount,
      close: handleImperativeClose
    }), [forceUnmount, handleImperativeClose]);
    const shouldRenderInteractions = open || mounted || !disabled2 && trackCursorAxis !== "none";
    return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(TooltipRootContext.Provider, {
      value: store2,
      children: [shouldRenderInteractions && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(TooltipInteractions, {
        store: store2,
        disabled: disabled2,
        trackCursorAxis
      }), typeof children === "function" ? children({
        payload
      }) : children]
    });
  });
  if (true) TooltipRoot.displayName = "TooltipRoot";
  function TooltipInteractions({
    store: store2,
    disabled: disabled2,
    trackCursorAxis
  }) {
    const floatingRootContext = store2.useState("floatingRootContext");
    const dismiss = useDismiss(floatingRootContext, {
      enabled: !disabled2,
      referencePress: () => store2.select("closeOnClick")
    });
    const clientPoint = useClientPoint(floatingRootContext, {
      enabled: !disabled2 && trackCursorAxis !== "none",
      axis: trackCursorAxis === "none" ? void 0 : trackCursorAxis
    });
    const activeTriggerProps = React46.useMemo(() => mergeProps(clientPoint.reference, dismiss.reference), [clientPoint.reference, dismiss.reference]);
    const inactiveTriggerProps = React46.useMemo(() => mergeProps(clientPoint.trigger, dismiss.trigger), [clientPoint.trigger, dismiss.trigger]);
    const popupProps = React46.useMemo(() => mergeProps(FOCUSABLE_POPUP_PROPS, clientPoint.floating, dismiss.floating), [clientPoint.floating, dismiss.floating]);
    usePopupInteractionProps(store2, {
      activeTriggerProps,
      inactiveTriggerProps,
      popupProps
    });
    return null;
  }

  // node_modules/@base-ui/react/tooltip/trigger/TooltipTrigger.mjs
  var React48 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/tooltip/provider/TooltipProviderContext.mjs
  var React47 = __toESM(require_react(), 1);
  var TooltipProviderContext = /* @__PURE__ */ React47.createContext(void 0);
  if (true) TooltipProviderContext.displayName = "TooltipProviderContext";
  function useTooltipProviderContext() {
    return React47.useContext(TooltipProviderContext);
  }

  // node_modules/@base-ui/react/tooltip/trigger/TooltipTriggerDataAttributes.mjs
  var TooltipTriggerDataAttributes = (function(TooltipTriggerDataAttributes2) {
    TooltipTriggerDataAttributes2[TooltipTriggerDataAttributes2["popupOpen"] = CommonTriggerDataAttributes.popupOpen] = "popupOpen";
    TooltipTriggerDataAttributes2["triggerDisabled"] = "data-trigger-disabled";
    return TooltipTriggerDataAttributes2;
  })({});

  // node_modules/@base-ui/react/tooltip/utils/constants.mjs
  var OPEN_DELAY = 600;

  // node_modules/@base-ui/react/tooltip/trigger/TooltipTrigger.mjs
  var TOOLTIP_TRIGGER_IDENTIFIER = "data-base-ui-tooltip-trigger";
  function getTargetElement(event) {
    if ("composedPath" in event) {
      const path = event.composedPath();
      for (let i2 = 0; i2 < path.length; i2 += 1) {
        const element = path[i2];
        if (isElement(element)) {
          return element;
        }
      }
    }
    const target = event.target;
    if (isElement(target)) {
      return target;
    }
    return null;
  }
  function closestEnabledTooltipTrigger(element) {
    let current = element;
    while (current) {
      if (current.hasAttribute(TOOLTIP_TRIGGER_IDENTIFIER)) {
        return current;
      }
      const parentElement = current.parentElement;
      if (parentElement) {
        current = parentElement;
        continue;
      }
      const root = current.getRootNode();
      current = "host" in root && isElement(root.host) ? root.host : null;
    }
    return null;
  }
  var TooltipTrigger = fastComponentRef(function TooltipTrigger2(componentProps, forwardedRef) {
    const {
      render: render4,
      className,
      style,
      handle,
      payload,
      disabled: disabledProp,
      delay,
      closeOnClick = true,
      closeDelay,
      id: idProp,
      ...elementProps
    } = componentProps;
    const rootContext = useTooltipRootContext(true);
    const store2 = handle?.store ?? rootContext;
    if (!store2) {
      throw new Error(true ? "Base UI: <Tooltip.Trigger> must be either used within a <Tooltip.Root> component or provided with a handle." : formatErrorMessage_default(82));
    }
    const thisTriggerId = useBaseUiId(idProp);
    const isTriggerActive = store2.useState("isTriggerActive", thisTriggerId);
    const isOpenedByThisTrigger = store2.useState("isOpenedByTrigger", thisTriggerId);
    const floatingRootContext = store2.useState("floatingRootContext");
    const triggerElementRef = React48.useRef(null);
    const delayWithDefault = delay ?? OPEN_DELAY;
    const closeDelayWithDefault = closeDelay ?? 0;
    const {
      registerTrigger,
      isMountedByThisTrigger
    } = useTriggerDataForwarding(thisTriggerId, triggerElementRef, store2, {
      payload,
      closeOnClick,
      closeDelay: closeDelayWithDefault
    });
    const providerContext = useTooltipProviderContext();
    const {
      delayRef,
      isInstantPhase,
      hasProvider
    } = useDelayGroup(floatingRootContext, {
      open: isOpenedByThisTrigger
    });
    const hoverInteraction = useHoverInteractionSharedState(floatingRootContext);
    store2.useSyncedValue("isInstantPhase", isInstantPhase);
    const rootDisabled = store2.useState("disabled");
    const disabled2 = disabledProp ?? rootDisabled;
    const disabledRef = useValueAsRef(disabled2);
    const trackCursorAxis = store2.useState("trackCursorAxis");
    const disableHoverablePopup = store2.useState("disableHoverablePopup");
    const isNestedTriggerHoveredRef = React48.useRef(false);
    const nestedTriggerOpenTimeout = useTimeout();
    const pointerTypeRef = React48.useRef(void 0);
    function getOpenDelay() {
      const providerDelay = providerContext?.delay;
      const groupOpenValue = typeof delayRef.current === "object" ? delayRef.current.open : void 0;
      let computedOpenDelay = delayWithDefault;
      if (hasProvider) {
        if (groupOpenValue !== 0) {
          computedOpenDelay = delay ?? providerDelay ?? delayWithDefault;
        } else {
          computedOpenDelay = 0;
        }
      }
      return computedOpenDelay;
    }
    function isEnabledNestedTriggerTarget(target) {
      const triggerEl = triggerElementRef.current;
      if (!triggerEl || !target) {
        return false;
      }
      const nearestTrigger = closestEnabledTooltipTrigger(target);
      return nearestTrigger !== null && nearestTrigger !== triggerEl && contains(triggerEl, nearestTrigger);
    }
    function detectNestedTriggerHover(target) {
      const nestedTriggerHovered = isEnabledNestedTriggerTarget(target);
      isNestedTriggerHoveredRef.current = nestedTriggerHovered;
      if (nestedTriggerHovered) {
        hoverInteraction.openChangeTimeout.clear();
        hoverInteraction.restTimeout.clear();
        hoverInteraction.restTimeoutPending = false;
        nestedTriggerOpenTimeout.clear();
      }
      return nestedTriggerHovered;
    }
    const hoverProps = useHoverReferenceInteraction(floatingRootContext, {
      enabled: !disabled2,
      mouseOnly: true,
      move: false,
      handleClose: !disableHoverablePopup && trackCursorAxis !== "both" ? safePolygon() : null,
      restMs: getOpenDelay,
      delay() {
        const closeValue = typeof delayRef.current === "object" ? delayRef.current.close : void 0;
        let computedCloseDelay = closeDelayWithDefault;
        if (closeDelay == null && hasProvider) {
          computedCloseDelay = closeValue;
        }
        return {
          close: computedCloseDelay
        };
      },
      triggerElementRef,
      isActiveTrigger: isTriggerActive,
      isClosing: () => store2.select("transitionStatus") === "ending",
      shouldOpen() {
        return !isNestedTriggerHoveredRef.current;
      }
    });
    const focusProps = useFocus(floatingRootContext, {
      enabled: !disabled2
    }).reference;
    const handleNestedTriggerHover = (event) => {
      const wasNestedTriggerHovered = isNestedTriggerHoveredRef.current;
      const target = getTargetElement(event);
      const nestedTriggerHovered = detectNestedTriggerHover(target);
      const triggerEl = triggerElementRef.current;
      const targetInsideTrigger = triggerEl && target && contains(triggerEl, target);
      if (nestedTriggerHovered && store2.select("open") && store2.select("lastOpenChangeReason") === reason_parts_exports.triggerHover) {
        store2.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
        return;
      }
      if (wasNestedTriggerHovered && !nestedTriggerHovered && targetInsideTrigger && !disabledRef.current && !store2.select("open") && triggerEl && // Match the hover hook's non-strict mouse fallback for mouse-only event sequences.
      isMouseLikePointerType(pointerTypeRef.current)) {
        const open = () => {
          if (!isNestedTriggerHoveredRef.current && !disabledRef.current && !store2.select("open")) {
            store2.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerEl));
          }
        };
        const openDelay = getOpenDelay();
        if (openDelay === 0) {
          nestedTriggerOpenTimeout.clear();
          open();
        } else {
          nestedTriggerOpenTimeout.start(openDelay, open);
        }
      }
    };
    const rootTriggerProps = store2.useState("triggerProps", isMountedByThisTrigger);
    const shouldApplyRootTriggerProps = isMountedByThisTrigger || trackCursorAxis !== "none";
    const state = {
      open: isOpenedByThisTrigger
    };
    const element = useRenderElement("button", componentProps, {
      state,
      ref: [forwardedRef, registerTrigger, triggerElementRef],
      props: [hoverProps, focusProps, shouldApplyRootTriggerProps ? rootTriggerProps : void 0, {
        onMouseOver(event) {
          handleNestedTriggerHover(event.nativeEvent);
        },
        onFocus(event) {
          if (isEnabledNestedTriggerTarget(getTargetElement(event.nativeEvent))) {
            event.preventBaseUIHandler();
          }
        },
        onMouseLeave() {
          isNestedTriggerHoveredRef.current = false;
          nestedTriggerOpenTimeout.clear();
          pointerTypeRef.current = void 0;
        },
        onPointerEnter(event) {
          pointerTypeRef.current = event.pointerType;
        },
        onPointerDown(event) {
          pointerTypeRef.current = event.pointerType;
          store2.set("closeOnClick", closeOnClick);
          if (closeOnClick && !store2.select("open")) {
            store2.cancelPendingOpen(event.nativeEvent);
          }
        },
        onClick(event) {
          if (closeOnClick && !store2.select("open")) {
            store2.cancelPendingOpen(event.nativeEvent);
          }
        },
        id: thisTriggerId,
        [TooltipTriggerDataAttributes.triggerDisabled]: disabled2 ? "" : void 0,
        [TOOLTIP_TRIGGER_IDENTIFIER]: disabled2 ? void 0 : ""
      }, elementProps],
      stateAttributesMapping: triggerOpenStateMapping2
    });
    return element;
  });
  if (true) TooltipTrigger.displayName = "TooltipTrigger";

  // node_modules/@base-ui/react/tooltip/portal/TooltipPortal.mjs
  var React50 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/tooltip/portal/TooltipPortalContext.mjs
  var React49 = __toESM(require_react(), 1);
  var TooltipPortalContext = /* @__PURE__ */ React49.createContext(void 0);
  if (true) TooltipPortalContext.displayName = "TooltipPortalContext";
  function useTooltipPortalContext() {
    const value = React49.useContext(TooltipPortalContext);
    if (value === void 0) {
      throw new Error(true ? "Base UI: <Tooltip.Portal> is missing." : formatErrorMessage_default(70));
    }
    return value;
  }

  // node_modules/@base-ui/react/tooltip/portal/TooltipPortal.mjs
  var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
  var TooltipPortal = /* @__PURE__ */ React50.forwardRef(function TooltipPortal2(props, forwardedRef) {
    const {
      keepMounted = false,
      ...portalProps
    } = props;
    const store2 = useTooltipRootContext();
    const mounted = store2.useState("mounted");
    const shouldRender = mounted || keepMounted;
    if (!shouldRender) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(TooltipPortalContext.Provider, {
      value: keepMounted,
      children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(FloatingPortalLite, {
        ref: forwardedRef,
        ...portalProps
      })
    });
  });
  if (true) TooltipPortal.displayName = "TooltipPortal";

  // node_modules/@base-ui/react/tooltip/positioner/TooltipPositioner.mjs
  var React52 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/tooltip/positioner/TooltipPositionerContext.mjs
  var React51 = __toESM(require_react(), 1);
  var TooltipPositionerContext = /* @__PURE__ */ React51.createContext(void 0);
  if (true) TooltipPositionerContext.displayName = "TooltipPositionerContext";
  function useTooltipPositionerContext() {
    const context = React51.useContext(TooltipPositionerContext);
    if (context === void 0) {
      throw new Error(true ? "Base UI: TooltipPositionerContext is missing. TooltipPositioner parts must be placed within <Tooltip.Positioner>." : formatErrorMessage_default(71));
    }
    return context;
  }

  // node_modules/@base-ui/react/tooltip/positioner/TooltipPositioner.mjs
  var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
  var TooltipPositioner = /* @__PURE__ */ React52.forwardRef(function TooltipPositioner2(componentProps, forwardedRef) {
    const {
      render: render4,
      className,
      anchor,
      positionMethod = "absolute",
      side = "top",
      align = "center",
      sideOffset = 0,
      alignOffset = 0,
      collisionBoundary = "clipping-ancestors",
      collisionPadding = 5,
      arrowPadding = 5,
      sticky = false,
      disableAnchorTracking = false,
      collisionAvoidance = POPUP_COLLISION_AVOIDANCE,
      style,
      ...elementProps
    } = componentProps;
    const store2 = useTooltipRootContext();
    const keepMounted = useTooltipPortalContext();
    const open = store2.useState("open");
    const mounted = store2.useState("mounted");
    const trackCursorAxis = store2.useState("trackCursorAxis");
    const disableHoverablePopup = store2.useState("disableHoverablePopup");
    const floatingRootContext = store2.useState("floatingRootContext");
    const instantType = store2.useState("instantType");
    const transitionStatus = store2.useState("transitionStatus");
    const hasViewport = store2.useState("hasViewport");
    const positioning = useAnchorPositioning({
      anchor,
      positionMethod,
      floatingRootContext,
      mounted,
      side,
      sideOffset,
      align,
      alignOffset,
      collisionBoundary,
      collisionPadding,
      sticky,
      arrowPadding,
      disableAnchorTracking,
      keepMounted,
      collisionAvoidance,
      adaptiveOrigin: hasViewport ? adaptiveOrigin : void 0
    });
    const state = React52.useMemo(() => ({
      open,
      side: positioning.side,
      align: positioning.align,
      anchorHidden: positioning.anchorHidden,
      instant: trackCursorAxis !== "none" ? "tracking-cursor" : instantType
    }), [open, positioning.side, positioning.align, positioning.anchorHidden, trackCursorAxis, instantType]);
    const element = usePositioner(componentProps, state, {
      styles: positioning.positionerStyles,
      transitionStatus,
      props: elementProps,
      refs: [forwardedRef, store2.useStateSetter("positionerElement")],
      hidden: !mounted,
      inert: !open || trackCursorAxis === "both" || disableHoverablePopup
    });
    return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(TooltipPositionerContext.Provider, {
      value: positioning,
      children: element
    });
  });
  if (true) TooltipPositioner.displayName = "TooltipPositioner";

  // node_modules/@base-ui/react/tooltip/popup/TooltipPopup.mjs
  var React53 = __toESM(require_react(), 1);
  var stateAttributesMapping2 = {
    ...popupStateMapping,
    ...transitionStatusMapping
  };
  var TooltipPopup = /* @__PURE__ */ React53.forwardRef(function TooltipPopup2(componentProps, forwardedRef) {
    const {
      render: render4,
      className,
      style,
      ...elementProps
    } = componentProps;
    const store2 = useTooltipRootContext();
    const {
      side,
      align
    } = useTooltipPositionerContext();
    const open = store2.useState("open");
    const instantType = store2.useState("instantType");
    const transitionStatus = store2.useState("transitionStatus");
    const popupProps = store2.useState("popupProps");
    const floatingContext = store2.useState("floatingRootContext");
    const disabled2 = store2.useState("disabled");
    const closeDelay = store2.useState("closeDelay");
    useOpenChangeComplete({
      open,
      ref: store2.context.popupRef,
      onComplete() {
        if (open) {
          store2.context.onOpenChangeComplete?.(true);
        }
      }
    });
    useHoverFloatingInteraction(floatingContext, {
      enabled: !disabled2,
      closeDelay
    });
    const setPopupElement = store2.useStateSetter("popupElement");
    const state = {
      open,
      side,
      align,
      instant: instantType,
      transitionStatus
    };
    const element = useRenderElement("div", componentProps, {
      state,
      ref: [forwardedRef, store2.context.popupRef, setPopupElement],
      props: [popupProps, getDisabledMountTransitionStyles(transitionStatus), elementProps],
      stateAttributesMapping: stateAttributesMapping2
    });
    return element;
  });
  if (true) TooltipPopup.displayName = "TooltipPopup";

  // node_modules/@base-ui/react/tooltip/arrow/TooltipArrow.mjs
  var React54 = __toESM(require_react(), 1);
  var TooltipArrow = /* @__PURE__ */ React54.forwardRef(function TooltipArrow2(componentProps, forwardedRef) {
    const {
      render: render4,
      className,
      style,
      ...elementProps
    } = componentProps;
    const store2 = useTooltipRootContext();
    const {
      arrowRef,
      side,
      align,
      arrowUncentered,
      arrowStyles
    } = useTooltipPositionerContext();
    const open = store2.useState("open");
    const instantType = store2.useState("instantType");
    const state = {
      open,
      side,
      align,
      uncentered: arrowUncentered,
      instant: instantType
    };
    const element = useRenderElement("div", componentProps, {
      state,
      ref: [forwardedRef, arrowRef],
      props: [{
        style: arrowStyles,
        "aria-hidden": true
      }, elementProps],
      stateAttributesMapping: popupStateMapping
    });
    return element;
  });
  if (true) TooltipArrow.displayName = "TooltipArrow";

  // node_modules/@base-ui/react/tooltip/provider/TooltipProvider.mjs
  var React55 = __toESM(require_react(), 1);
  var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
  var TooltipProvider = function TooltipProvider2(props) {
    const {
      delay,
      closeDelay,
      timeout = 400
    } = props;
    const contextValue = React55.useMemo(() => ({
      delay,
      closeDelay
    }), [delay, closeDelay]);
    const delayValue = React55.useMemo(() => ({
      open: delay,
      close: closeDelay
    }), [delay, closeDelay]);
    return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(TooltipProviderContext.Provider, {
      value: contextValue,
      children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(FloatingDelayGroup, {
        delay: delayValue,
        timeoutMs: timeout,
        children: props.children
      })
    });
  };
  if (true) TooltipProvider.displayName = "TooltipProvider";

  // node_modules/@base-ui/react/tooltip/viewport/TooltipViewport.mjs
  var React56 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/tooltip/viewport/TooltipViewportCssVars.mjs
  var TooltipViewportCssVars = /* @__PURE__ */ (function(TooltipViewportCssVars2) {
    TooltipViewportCssVars2["popupWidth"] = "--popup-width";
    TooltipViewportCssVars2["popupHeight"] = "--popup-height";
    return TooltipViewportCssVars2;
  })({});

  // node_modules/@base-ui/react/tooltip/viewport/TooltipViewport.mjs
  var stateAttributesMapping3 = {
    activationDirection: (value) => value ? {
      "data-activation-direction": value
    } : null
  };
  var TooltipViewport = /* @__PURE__ */ React56.forwardRef(function TooltipViewport2(componentProps, forwardedRef) {
    const {
      render: render4,
      className,
      style,
      children,
      ...elementProps
    } = componentProps;
    const store2 = useTooltipRootContext();
    const positioner = useTooltipPositionerContext();
    const instantType = store2.useState("instantType");
    const {
      children: childrenToRender,
      state: viewportState
    } = usePopupViewport({
      store: store2,
      side: positioner.side,
      cssVars: TooltipViewportCssVars,
      children
    });
    const state = {
      activationDirection: viewportState.activationDirection,
      transitioning: viewportState.transitioning,
      instant: instantType
    };
    return useRenderElement("div", componentProps, {
      state,
      ref: forwardedRef,
      props: [elementProps, {
        children: childrenToRender
      }],
      stateAttributesMapping: stateAttributesMapping3
    });
  });
  if (true) TooltipViewport.displayName = "TooltipViewport";

  // node_modules/@base-ui/react/tooltip/store/TooltipHandle.mjs
  var TooltipHandle = class {
    /**
     * Internal store holding the tooltip state.
     * @internal
     */
    constructor() {
      this.store = new TooltipStore();
    }
    /**
     * Opens the tooltip and associates it with the trigger with the given ID.
     * The trigger must be a Tooltip.Trigger component with this handle passed as a prop.
     *
     * This method should only be called in an event handler or an effect (not during rendering).
     *
     * @param triggerId ID of the trigger to associate with the tooltip.
     */
    open(triggerId) {
      const triggerElement = triggerId ? this.store.context.triggerElements.getById(triggerId) : void 0;
      if (triggerId && !triggerElement) {
        throw new Error(true ? `Base UI: TooltipHandle.open: No trigger found with id "${triggerId}".` : formatErrorMessage_default(81, triggerId));
      }
      this.store.setOpen(true, createChangeEventDetails(reason_parts_exports.imperativeAction, void 0, triggerElement));
    }
    /**
     * Closes the tooltip.
     */
    close() {
      this.store.setOpen(false, createChangeEventDetails(reason_parts_exports.imperativeAction, void 0, void 0));
    }
    /**
     * Indicates whether the tooltip is currently open.
     */
    get isOpen() {
      return this.store.select("open");
    }
  };
  function createTooltipHandle() {
    return new TooltipHandle();
  }

  // node_modules/@base-ui/react/use-render/useRender.mjs
  function useRender(params) {
    return useRenderElement(params.defaultTagName ?? "div", params, params);
  }

  // packages/ui/build-module/text/text.mjs
  var import_element10 = __toESM(require_element(), 1);
  var STYLE_HASH_ATTRIBUTE = "data-wp-hash";
  function getRuntime() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument(targetDocument) {
    const runtime = getRuntime();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle(hash, css) {
    const runtime = getRuntime();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle("a495f9d138", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._83ed8a8da5dd50ea__text{margin:0}._14437cfb77831647__heading-2xl{--_gcd-heading-font-size:var(--wpds-typography-font-size-2xl,32px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-emphasis,600);--_gcd-p-font-size:var(--wpds-typography-font-size-2xl,32px);--_gcd-p-line-height:var(--wpds-typography-line-height-2xl,40px);font-size:var(--wpds-typography-font-size-2xl,32px);line-height:var(--wpds-typography-line-height-2xl,40px)}._14437cfb77831647__heading-2xl,._3c78b7fa9b4072dd__heading-xl{font-family:var(--wpds-typography-font-family-heading,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-weight:var(--wpds-typography-font-weight-emphasis,600)}._3c78b7fa9b4072dd__heading-xl{--_gcd-heading-font-size:var(--wpds-typography-font-size-xl,20px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-emphasis,600);--_gcd-p-font-size:var(--wpds-typography-font-size-xl,20px);--_gcd-p-line-height:var(--wpds-typography-line-height-md,24px);font-size:var(--wpds-typography-font-size-xl,20px);line-height:var(--wpds-typography-line-height-md,24px)}.aa58f227716bcde2__heading-lg{--_gcd-heading-font-size:var(--wpds-typography-font-size-lg,15px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-emphasis,600);--_gcd-p-font-size:var(--wpds-typography-font-size-lg,15px);--_gcd-p-line-height:var(--wpds-typography-line-height-sm,20px);font-size:var(--wpds-typography-font-size-lg,15px)}.aa58f227716bcde2__heading-lg,.fc4da56d8dfe52c4__heading-md{font-family:var(--wpds-typography-font-family-heading,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-weight:var(--wpds-typography-font-weight-emphasis,600);line-height:var(--wpds-typography-line-height-sm,20px)}.fc4da56d8dfe52c4__heading-md{--_gcd-heading-font-size:var(--wpds-typography-font-size-md,13px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-emphasis,600);--_gcd-p-font-size:var(--wpds-typography-font-size-md,13px);--_gcd-p-line-height:var(--wpds-typography-line-height-sm,20px);font-size:var(--wpds-typography-font-size-md,13px)}.a9b78c7c82e8dff7__heading-sm{--_gcd-heading-font-size:var(--wpds-typography-font-size-xs,11px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-emphasis,600);--_gcd-p-font-size:var(--wpds-typography-font-size-xs,11px);--_gcd-p-line-height:var(--wpds-typography-line-height-xs,16px);font-family:var(--wpds-typography-font-family-heading,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-xs,11px);font-weight:var(--wpds-typography-font-weight-emphasis,600);line-height:var(--wpds-typography-line-height-xs,16px);text-transform:uppercase}._305ff559e52180d5__body-xl{--_gcd-heading-font-size:var(--wpds-typography-font-size-xl,20px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-default,400);--_gcd-p-font-size:var(--wpds-typography-font-size-xl,20px);--_gcd-p-line-height:var(--wpds-typography-line-height-xl,32px);font-size:var(--wpds-typography-font-size-xl,20px);line-height:var(--wpds-typography-line-height-xl,32px)}._305ff559e52180d5__body-xl,.ca1aa3fc2029e958__body-lg{font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-weight:var(--wpds-typography-font-weight-default,400)}.ca1aa3fc2029e958__body-lg{--_gcd-heading-font-size:var(--wpds-typography-font-size-lg,15px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-default,400);--_gcd-p-font-size:var(--wpds-typography-font-size-lg,15px);--_gcd-p-line-height:var(--wpds-typography-line-height-md,24px);font-size:var(--wpds-typography-font-size-lg,15px);line-height:var(--wpds-typography-line-height-md,24px)}._131101940be12424__body-md{--_gcd-heading-font-size:var(--wpds-typography-font-size-md,13px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-default,400);--_gcd-p-font-size:var(--wpds-typography-font-size-md,13px);--_gcd-p-line-height:var(--wpds-typography-line-height-sm,20px);font-size:var(--wpds-typography-font-size-md,13px);line-height:var(--wpds-typography-line-height-sm,20px)}._0e8d87a42c1f75fa__body-sm,._131101940be12424__body-md{font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-weight:var(--wpds-typography-font-weight-default,400)}._0e8d87a42c1f75fa__body-sm{--_gcd-heading-font-size:var(--wpds-typography-font-size-sm,12px);--_gcd-heading-font-weight:var(--wpds-typography-font-weight-default,400);--_gcd-p-font-size:var(--wpds-typography-font-size-sm,12px);--_gcd-p-line-height:var(--wpds-typography-line-height-xs,16px);font-size:var(--wpds-typography-font-size-sm,12px);line-height:var(--wpds-typography-line-height-xs,16px)}}}');
  }
  var style_default = { "text": "_83ed8a8da5dd50ea__text", "heading-2xl": "_14437cfb77831647__heading-2xl", "heading-xl": "_3c78b7fa9b4072dd__heading-xl", "heading-lg": "aa58f227716bcde2__heading-lg", "heading-md": "fc4da56d8dfe52c4__heading-md", "heading-sm": "a9b78c7c82e8dff7__heading-sm", "body-xl": "_305ff559e52180d5__body-xl", "body-lg": "ca1aa3fc2029e958__body-lg", "body-md": "_131101940be12424__body-md", "body-sm": "_0e8d87a42c1f75fa__body-sm" };
  if (typeof process === "undefined" || true) {
    registerStyle("af6d9984a6", "._6defc79820e382c6__button{box-sizing:var(--_gcd-button-box-sizing,border-box);font-family:var(--_gcd-button-font-family,inherit);font-size:var(--_gcd-button-font-size,inherit);font-weight:var(--_gcd-button-font-weight,inherit)}.d2cff2e5dea83bd1__input{box-sizing:var(--_gcd-input-box-sizing,border-box);font-family:var(--_gcd-input-font-family,inherit);font-size:var(--_gcd-input-font-size,inherit);font-weight:var(--_gcd-input-font-weight,inherit);margin:var(--_gcd-input-margin,0);&:is(textarea,[type=text],[type=password],[type=color],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){background-color:var(--_gcd-input-background-color,transparent);border:var(--_gcd-input-border,none);border-radius:var(--_gcd-input-border-radius,0);box-shadow:var(--_gcd-input-box-shadow,0 0 0 transparent);color:var(--_gcd-input-color,var(--wpds-color-foreground-interactive-neutral,#1e1e1e));&:focus{border-color:var(--_gcd-input-border-color-focus,var(--wp-admin-theme-color));box-shadow:var(--_gcd-input-box-shadow-focus,none);outline:var(--_gcd-input-outline-focus,none)}&:disabled{background:var(--_gcd-input-background-disabled,transparent);border-color:var(--_gcd-input-border-color-disabled,transparent);box-shadow:var(--_gcd-input-box-shadow-disabled,none);color:var(--_gcd-input-color-disabled,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}&::placeholder{color:var(--_gcd-input-placeholder-color,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}}&:is(textarea,[type=text],[type=password],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){line-height:var(--_gcd-input-line-height,inherit);min-height:var(--_gcd-input-min-height,auto);padding:var(--_gcd-input-padding,0)}}._547d86373d02e108__textarea{box-sizing:var(--_gcd-textarea-box-sizing,border-box);overflow:var(--_gcd-textarea-overflow,auto);resize:var(--_gcd-textarea-resize,block)}._8c15fd0ed9f28ba4__div{outline:var(--_gcd-div-outline,0 solid transparent)}p._43cec3e1eec1066d__p{font-size:var(--_gcd-p-font-size,13px);line-height:var(--_gcd-p-line-height,1.5);margin:var(--_gcd-p-margin,0)}:is(h1,h2,h3,h4,h5,h6).e97669c6d9a38497__heading{color:var(--_gcd-heading-color,var(--wpds-color-foreground-content-neutral,#1e1e1e));font-size:var(--_gcd-heading-font-size,inherit);font-weight:var(--_gcd-heading-font-weight,var(--wpds-typography-font-weight-emphasis,600));margin:var(--_gcd-heading-margin,0)}._2c0831b0499dbd6e__a,._2c0831b0499dbd6e__a:is(:hover,:focus,:active){border-radius:var(--_gcd-a-border-radius,0);box-shadow:var(--_gcd-a-box-shadow,none);color:var(--_gcd-a-color,inherit);outline:var(--_gcd-a-outline,0 solid transparent);transition:var(--_gcd-a-transition,none)}");
  }
  var global_css_defense_default = { "button": "_6defc79820e382c6__button", "input": "d2cff2e5dea83bd1__input", "textarea": "_547d86373d02e108__textarea", "div": "_8c15fd0ed9f28ba4__div", "p": "_43cec3e1eec1066d__p", "heading": "e97669c6d9a38497__heading", "a": "_2c0831b0499dbd6e__a" };
  var Text = (0, import_element10.forwardRef)(function Text2({ variant = "body-md", render: render4, className, ...props }, ref) {
    const element = useRender({
      render: render4,
      defaultTagName: "span",
      ref,
      props: mergeProps(props, {
        className: clsx_default(
          style_default.text,
          global_css_defense_default.heading,
          global_css_defense_default.p,
          style_default[variant],
          className
        )
      })
    });
    return element;
  });

  // packages/ui/build-module/badge/badge.mjs
  var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
  var STYLE_HASH_ATTRIBUTE2 = "data-wp-hash";
  function getRuntime2() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument2(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash2(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE2}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE2) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle2(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime2();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash2(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE2, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument2(targetDocument) {
    const runtime = getRuntime2();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle2(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle2(hash, css) {
    const runtime = getRuntime2();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle2(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle2("9db2873e7f", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._96e6251aad1a6136__badge{border-radius:var(--wpds-border-radius-lg,8px);padding-block:var(--wpds-dimension-padding-xs,4px);padding-inline:var(--wpds-dimension-padding-sm,8px)}._99f7158cb520f750__is-high-intent{background-color:var(--wpds-color-background-surface-error,#f6e6e3);color:var(--wpds-color-foreground-content-error,#470000)}.c20ebef2365bc8b7__is-medium-intent{background-color:var(--wpds-color-background-surface-warning,#fde6be);color:var(--wpds-color-foreground-content-warning,#2e1900)}._365e1626c6202e52__is-low-intent{background-color:var(--wpds-color-background-surface-caution,#fee995);color:var(--wpds-color-foreground-content-caution,#281d00)}._33f8198127ddf4ef__is-stable-intent{background-color:var(--wpds-color-background-surface-success,#c6f7cd);color:var(--wpds-color-foreground-content-success,#002900)}._04c1aca8fc449412__is-informational-intent{background-color:var(--wpds-color-background-surface-info,#deebfa);color:var(--wpds-color-foreground-content-info,#001b4f)}._90726e69d495ec19__is-draft-intent{background-color:var(--wpds-color-background-surface-neutral-weak,#f4f4f4);color:var(--wpds-color-foreground-content-neutral,#1e1e1e)}._898f4a544993bd39__is-none-intent{background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:var(--wpds-border-width-xs,1px) solid var(--wpds-color-stroke-surface-neutral,#dbdbdb);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);padding-block:calc(var(--wpds-dimension-padding-xs, 4px) - var(--wpds-border-width-xs, 1px));padding-inline:calc(var(--wpds-dimension-padding-sm, 8px) - var(--wpds-border-width-xs, 1px))}}}");
  }
  var style_default2 = { "badge": "_96e6251aad1a6136__badge", "is-high-intent": "_99f7158cb520f750__is-high-intent", "is-medium-intent": "c20ebef2365bc8b7__is-medium-intent", "is-low-intent": "_365e1626c6202e52__is-low-intent", "is-stable-intent": "_33f8198127ddf4ef__is-stable-intent", "is-informational-intent": "_04c1aca8fc449412__is-informational-intent", "is-draft-intent": "_90726e69d495ec19__is-draft-intent", "is-none-intent": "_898f4a544993bd39__is-none-intent" };
  var Badge = (0, import_element11.forwardRef)(function Badge2({ intent = "none", className, ...props }, ref) {
    return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      Text,
      {
        ref,
        className: clsx_default(
          style_default2.badge,
          style_default2[`is-${intent}-intent`],
          className
        ),
        ...props,
        variant: "body-sm"
      }
    );
  });

  // packages/ui/build-module/icon/icon.mjs
  var import_element12 = __toESM(require_element(), 1);
  var import_primitives = __toESM(require_primitives(), 1);
  var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
  var Icon = (0, import_element12.forwardRef)(function Icon2({ icon, size: size4 = 24, ...restProps }, ref) {
    return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
      import_primitives.SVG,
      {
        ref,
        ...icon.props,
        ...restProps,
        width: size4,
        height: size4
      }
    );
  });

  // packages/ui/build-module/card/index.mjs
  var card_exports = {};
  __export(card_exports, {
    Content: () => Content,
    FullBleed: () => FullBleed,
    Header: () => Header,
    Root: () => Root,
    Title: () => Title
  });

  // packages/ui/build-module/card/root.mjs
  var import_element13 = __toESM(require_element(), 1);
  var STYLE_HASH_ATTRIBUTE3 = "data-wp-hash";
  function getRuntime3() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument3(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash3(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE3}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE3) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle3(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime3();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash3(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE3, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument3(targetDocument) {
    const runtime = getRuntime3();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle3(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle3(hash, css) {
    const runtime = getRuntime3();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle3(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle3("10f3806643", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._336cd3e4e743482f__box-sizing{box-sizing:border-box;*,:after,:before{box-sizing:inherit}}}}");
  }
  var resets_default = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
  if (typeof process === "undefined" || true) {
    registerStyle3("5d38cbdd27", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._02872bf298eadc43__root{--wp-ui-card-padding:var(--wpds-dimension-padding-2xl,24px);--wp-ui-card-header-content-gap:var(--wpds-dimension-gap-xl,24px);--wp-ui-card-header-content-margin:calc(var(--wp-ui-card-header-content-gap) - var(--wp-ui-card-padding));background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:1px solid var(--wpds-color-stroke-surface-neutral-weak,#f0f0f0);border-radius:var(--wpds-border-radius-lg,8px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);display:flex;flex-direction:column;overflow:clip}._5dffdaf2a6e669ac__content,.bbccc92e6ba5662d__header{padding:var(--wp-ui-card-padding);&:not(:first-child):not(:last-child){padding-block-end:0}}.bbccc92e6ba5662d__header+._5dffdaf2a6e669ac__content{margin-block-start:var(--wp-ui-card-header-content-margin);padding-block-start:0}.c1fa192587e1b4a6__fullbleed{margin-inline:calc(var(--wp-ui-card-padding)*-1);width:calc(100% + var(--wp-ui-card-padding)*2)}._02872bf298eadc43__root>:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):first-child>.c1fa192587e1b4a6__fullbleed:first-child{margin-block-start:calc(var(--wp-ui-card-padding)*-1)}:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):last-child>.c1fa192587e1b4a6__fullbleed:last-child{margin-block-end:calc(var(--wp-ui-card-padding)*-1)}}}");
  }
  var style_default3 = { "root": "_02872bf298eadc43__root", "header": "bbccc92e6ba5662d__header", "content": "_5dffdaf2a6e669ac__content", "fullbleed": "c1fa192587e1b4a6__fullbleed" };
  var Root = (0, import_element13.forwardRef)(function Card({ render: render4, ...restProps }, ref) {
    const mergedClassName = clsx_default(style_default3.root, resets_default["box-sizing"]);
    const element = useRender({
      defaultTagName: "div",
      render: render4,
      ref,
      props: mergeProps({ className: mergedClassName }, restProps)
    });
    return element;
  });

  // packages/ui/build-module/card/header.mjs
  var import_element14 = __toESM(require_element(), 1);
  var STYLE_HASH_ATTRIBUTE4 = "data-wp-hash";
  function getRuntime4() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument4(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash4(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE4}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE4) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle4(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime4();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash4(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE4, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument4(targetDocument) {
    const runtime = getRuntime4();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle4(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle4(hash, css) {
    const runtime = getRuntime4();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle4(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle4("5d38cbdd27", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._02872bf298eadc43__root{--wp-ui-card-padding:var(--wpds-dimension-padding-2xl,24px);--wp-ui-card-header-content-gap:var(--wpds-dimension-gap-xl,24px);--wp-ui-card-header-content-margin:calc(var(--wp-ui-card-header-content-gap) - var(--wp-ui-card-padding));background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:1px solid var(--wpds-color-stroke-surface-neutral-weak,#f0f0f0);border-radius:var(--wpds-border-radius-lg,8px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);display:flex;flex-direction:column;overflow:clip}._5dffdaf2a6e669ac__content,.bbccc92e6ba5662d__header{padding:var(--wp-ui-card-padding);&:not(:first-child):not(:last-child){padding-block-end:0}}.bbccc92e6ba5662d__header+._5dffdaf2a6e669ac__content{margin-block-start:var(--wp-ui-card-header-content-margin);padding-block-start:0}.c1fa192587e1b4a6__fullbleed{margin-inline:calc(var(--wp-ui-card-padding)*-1);width:calc(100% + var(--wp-ui-card-padding)*2)}._02872bf298eadc43__root>:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):first-child>.c1fa192587e1b4a6__fullbleed:first-child{margin-block-start:calc(var(--wp-ui-card-padding)*-1)}:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):last-child>.c1fa192587e1b4a6__fullbleed:last-child{margin-block-end:calc(var(--wp-ui-card-padding)*-1)}}}");
  }
  var style_default4 = { "root": "_02872bf298eadc43__root", "header": "bbccc92e6ba5662d__header", "content": "_5dffdaf2a6e669ac__content", "fullbleed": "c1fa192587e1b4a6__fullbleed" };
  var Header = (0, import_element14.forwardRef)(
    function CardHeader({ render: render4, ...props }, ref) {
      const element = useRender({
        defaultTagName: "div",
        render: render4,
        ref,
        props: mergeProps({ className: style_default4.header }, props)
      });
      return element;
    }
  );

  // packages/ui/build-module/card/content.mjs
  var import_element15 = __toESM(require_element(), 1);
  var STYLE_HASH_ATTRIBUTE5 = "data-wp-hash";
  function getRuntime5() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument5(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash5(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE5}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE5) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle5(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime5();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash5(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE5, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument5(targetDocument) {
    const runtime = getRuntime5();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle5(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle5(hash, css) {
    const runtime = getRuntime5();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle5(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle5("5d38cbdd27", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._02872bf298eadc43__root{--wp-ui-card-padding:var(--wpds-dimension-padding-2xl,24px);--wp-ui-card-header-content-gap:var(--wpds-dimension-gap-xl,24px);--wp-ui-card-header-content-margin:calc(var(--wp-ui-card-header-content-gap) - var(--wp-ui-card-padding));background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:1px solid var(--wpds-color-stroke-surface-neutral-weak,#f0f0f0);border-radius:var(--wpds-border-radius-lg,8px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);display:flex;flex-direction:column;overflow:clip}._5dffdaf2a6e669ac__content,.bbccc92e6ba5662d__header{padding:var(--wp-ui-card-padding);&:not(:first-child):not(:last-child){padding-block-end:0}}.bbccc92e6ba5662d__header+._5dffdaf2a6e669ac__content{margin-block-start:var(--wp-ui-card-header-content-margin);padding-block-start:0}.c1fa192587e1b4a6__fullbleed{margin-inline:calc(var(--wp-ui-card-padding)*-1);width:calc(100% + var(--wp-ui-card-padding)*2)}._02872bf298eadc43__root>:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):first-child>.c1fa192587e1b4a6__fullbleed:first-child{margin-block-start:calc(var(--wp-ui-card-padding)*-1)}:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):last-child>.c1fa192587e1b4a6__fullbleed:last-child{margin-block-end:calc(var(--wp-ui-card-padding)*-1)}}}");
  }
  var style_default5 = { "root": "_02872bf298eadc43__root", "header": "bbccc92e6ba5662d__header", "content": "_5dffdaf2a6e669ac__content", "fullbleed": "c1fa192587e1b4a6__fullbleed" };
  var Content = (0, import_element15.forwardRef)(
    function CardContent({ render: render4, ...props }, ref) {
      const element = useRender({
        defaultTagName: "div",
        render: render4,
        ref,
        props: mergeProps({ className: style_default5.content }, props)
      });
      return element;
    }
  );

  // packages/ui/build-module/card/full-bleed.mjs
  var import_element16 = __toESM(require_element(), 1);
  var STYLE_HASH_ATTRIBUTE6 = "data-wp-hash";
  function getRuntime6() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument6(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash6(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE6}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE6) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle6(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime6();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash6(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE6, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument6(targetDocument) {
    const runtime = getRuntime6();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle6(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle6(hash, css) {
    const runtime = getRuntime6();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle6(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle6("5d38cbdd27", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._02872bf298eadc43__root{--wp-ui-card-padding:var(--wpds-dimension-padding-2xl,24px);--wp-ui-card-header-content-gap:var(--wpds-dimension-gap-xl,24px);--wp-ui-card-header-content-margin:calc(var(--wp-ui-card-header-content-gap) - var(--wp-ui-card-padding));background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border:1px solid var(--wpds-color-stroke-surface-neutral-weak,#f0f0f0);border-radius:var(--wpds-border-radius-lg,8px);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);display:flex;flex-direction:column;overflow:clip}._5dffdaf2a6e669ac__content,.bbccc92e6ba5662d__header{padding:var(--wp-ui-card-padding);&:not(:first-child):not(:last-child){padding-block-end:0}}.bbccc92e6ba5662d__header+._5dffdaf2a6e669ac__content{margin-block-start:var(--wp-ui-card-header-content-margin);padding-block-start:0}.c1fa192587e1b4a6__fullbleed{margin-inline:calc(var(--wp-ui-card-padding)*-1);width:calc(100% + var(--wp-ui-card-padding)*2)}._02872bf298eadc43__root>:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):first-child>.c1fa192587e1b4a6__fullbleed:first-child{margin-block-start:calc(var(--wp-ui-card-padding)*-1)}:is(.bbccc92e6ba5662d__header,._5dffdaf2a6e669ac__content):last-child>.c1fa192587e1b4a6__fullbleed:last-child{margin-block-end:calc(var(--wp-ui-card-padding)*-1)}}}");
  }
  var style_default6 = { "root": "_02872bf298eadc43__root", "header": "bbccc92e6ba5662d__header", "content": "_5dffdaf2a6e669ac__content", "fullbleed": "c1fa192587e1b4a6__fullbleed" };
  var FullBleed = (0, import_element16.forwardRef)(
    function CardFullBleed({ render: render4, ...props }, ref) {
      const element = useRender({
        defaultTagName: "div",
        render: render4,
        ref,
        props: mergeProps(
          { className: style_default6.fullbleed },
          props
        )
      });
      return element;
    }
  );

  // packages/ui/build-module/card/title.mjs
  var import_element17 = __toESM(require_element(), 1);
  var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1);
  var DEFAULT_TAG = /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("div", {});
  var Title = (0, import_element17.forwardRef)(
    function CardTitle({ render: render4 = DEFAULT_TAG, children, ...props }, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
        Text,
        {
          ref,
          variant: "heading-lg",
          render: render4,
          ...props,
          children
        }
      );
    }
  );

  // packages/ui/build-module/collapsible/panel.mjs
  var import_element18 = __toESM(require_element(), 1);
  var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
  var Panel = (0, import_element18.forwardRef)(
    function CollapsiblePanel3(props, forwardedRef) {
      return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(index_parts_exports.Panel, { ref: forwardedRef, ...props });
    }
  );

  // packages/ui/build-module/collapsible/root.mjs
  var import_element19 = __toESM(require_element(), 1);
  var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
  var Root2 = (0, import_element19.forwardRef)(
    function CollapsibleRoot3(props, forwardedRef) {
      return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(index_parts_exports.Root, { ref: forwardedRef, ...props });
    }
  );

  // packages/ui/build-module/collapsible/trigger.mjs
  var import_element20 = __toESM(require_element(), 1);
  var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
  var Trigger = (0, import_element20.forwardRef)(
    function CollapsibleTrigger3(props, forwardedRef) {
      return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(index_parts_exports.Trigger, { ref: forwardedRef, ...props });
    }
  );

  // packages/ui/build-module/collapsible-card/index.mjs
  var collapsible_card_exports = {};
  __export(collapsible_card_exports, {
    Content: () => Content2,
    Header: () => Header2,
    HeaderDescription: () => HeaderDescription,
    Root: () => Root3
  });

  // packages/ui/build-module/collapsible-card/root.mjs
  var import_element21 = __toESM(require_element(), 1);
  var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
  var Root3 = (0, import_element21.forwardRef)(
    function CollapsibleCardRoot({ render: render4, ...restProps }, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
        Root2,
        {
          ref,
          render: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Root, { render: render4 }),
          ...restProps
        }
      );
    }
  );

  // packages/ui/build-module/collapsible-card/header.mjs
  var import_element24 = __toESM(require_element(), 1);

  // packages/icons/build-module/icon/index.mjs
  var import_element22 = __toESM(require_element(), 1);
  var icon_default = (0, import_element22.forwardRef)(
    ({ icon, size: size4 = 24, ...props }, ref) => {
      return (0, import_element22.cloneElement)(icon, {
        width: size4,
        height: size4,
        ...props,
        ref
      });
    }
  );

  // packages/icons/build-module/library/archive.mjs
  var import_primitives2 = __toESM(require_primitives(), 1);
  var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
  var archive_default = /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_primitives2.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_primitives2.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M11.934 7.406a1 1 0 0 0 .914.594H19a.5.5 0 0 1 .5.5v9a.5.5 0 0 1-.5.5H5a.5.5 0 0 1-.5-.5V6a.5.5 0 0 1 .5-.5h5.764a.5.5 0 0 1 .447.276l.723 1.63Zm1.064-1.216a.5.5 0 0 0 .462.31H19a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h5.764a2 2 0 0 1 1.789 1.106l.445 1.084ZM8.5 10.5h7V12h-7v-1.5Zm7 3.5h-7v1.5h7V14Z" }) });

  // packages/icons/build-module/library/arrow-down.mjs
  var import_primitives3 = __toESM(require_primitives(), 1);
  var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
  var arrow_down_default = /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_primitives3.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_primitives3.Path, { d: "m16.5 13.5-3.7 3.7V4h-1.5v13.2l-3.8-3.7-1 1 5.5 5.6 5.5-5.6z" }) });

  // packages/icons/build-module/library/arrow-left.mjs
  var import_primitives4 = __toESM(require_primitives(), 1);
  var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
  var arrow_left_default = /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_primitives4.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_primitives4.Path, { d: "M20 11.2H6.8l3.7-3.7-1-1L3.9 12l5.6 5.5 1-1-3.7-3.7H20z" }) });

  // packages/icons/build-module/library/arrow-right.mjs
  var import_primitives5 = __toESM(require_primitives(), 1);
  var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1);
  var arrow_right_default = /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(import_primitives5.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(import_primitives5.Path, { d: "m14.5 6.5-1 1 3.7 3.7H4v1.6h13.2l-3.7 3.7 1 1 5.6-5.5z" }) });

  // packages/icons/build-module/library/arrow-up.mjs
  var import_primitives6 = __toESM(require_primitives(), 1);
  var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
  var arrow_up_default = /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(import_primitives6.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(import_primitives6.Path, { d: "M12 3.9 6.5 9.5l1 1 3.8-3.7V20h1.5V6.8l3.7 3.7 1-1z" }) });

  // packages/icons/build-module/library/audio.mjs
  var import_primitives7 = __toESM(require_primitives(), 1);
  var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1);
  var audio_default = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(import_primitives7.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(import_primitives7.Path, { d: "M17.7 4.3c-1.2 0-2.8 0-3.8 1-.6.6-.9 1.5-.9 2.6V14c-.6-.6-1.5-1-2.5-1C8.6 13 7 14.6 7 16.5S8.6 20 10.5 20c1.5 0 2.8-1 3.3-2.3.5-.8.7-1.8.7-2.5V7.9c0-.7.2-1.2.5-1.6.6-.6 1.8-.6 2.8-.6h.3V4.3h-.4z" }) });

  // packages/icons/build-module/library/backup.mjs
  var import_primitives8 = __toESM(require_primitives(), 1);
  var import_jsx_runtime25 = __toESM(require_jsx_runtime(), 1);
  var backup_default = /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(import_primitives8.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(import_primitives8.Path, { d: "M13.75 4.194a8 8 0 0 0-4.812.415l-.301.132a8 8 0 0 0-3.203 2.692L4 6.001v4h4L6.517 8.516q.333-.526.758-.977l.011-.012q.341-.359.733-.662l.025-.02a6.5 6.5 0 0 1 2.469-1.172l.034-.008q.117-.027.236-.05l.015-.002q.32-.06.65-.088.08-.008.16-.013a7 7 0 0 1 .323-.01L12 5.5h.05l.203.005.101.003q.146.008.293.023l.12.014.158.02q.103.015.205.033l.058.011q.107.02.212.043l.068.016a6.5 6.5 0 0 1 1.447.521l.02.01a7 7 0 0 1 .452.25l.02.014a7 7 0 0 1 .468.317l.07.054a7 7 0 0 1 .403.334l.034.03q.091.084.18.172l.047.045q.293.294.548.627l.03.038.07.097.096.135q.037.053.072.107a6 6 0 0 1 .167.265l.042.073q.236.411.413.857l.027.07a6.5 6.5 0 0 1 .418 2.014 6.6 6.6 0 0 1-.034 1.04 6 6 0 0 1-.063.424q-.109.597-.32 1.152-.016.034-.028.07a6.5 6.5 0 0 1-.413.856l-.042.073a6 6 0 0 1-.327.497l-.087.118-.02.028a7 7 0 0 1-.526.604l-.035.035-.035.032q-.089.088-.18.172l-.034.03a7 7 0 0 1-.38.317l-.093.071q-.09.067-.183.13l-.076.053q-.112.076-.227.146-.218.133-.446.247l-.028.015-.192.093-.081.036a6.5 6.5 0 0 1-1.184.396l-.058.012a7 7 0 0 1-.475.087q-.08.012-.157.02l-.122.014q-.145.015-.292.023l-.136.005-.139.003L12 18.5q-.053-.002-.104-.003l-.127-.004-.162-.007q-.08-.005-.159-.013a7 7 0 0 1-.65-.088q-.008 0-.015-.002a7 7 0 0 1-.236-.05l-.034-.008a6.5 6.5 0 0 1-4.14-3.077l-1.3.75a8 8 0 0 0 3.564 3.26l.301.131a8 8 0 0 0 11.055-7.061l.007-.33c0-1.76-.581-3.473-1.653-4.87l-.206-.256a8 8 0 0 0-4.07-2.6zM12 7.75a.75.75 0 0 0-.75.75V12a.75.75 0 0 0 .218.529l1.282-.839-1.28.84 2.5 2.5a.75.75 0 1 0 1.06-1.06l-2.28-2.28V8.5a.75.75 0 0 0-.75-.75" }) });

  // packages/icons/build-module/library/block-meta.mjs
  var import_primitives9 = __toESM(require_primitives(), 1);
  var import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
  var block_meta_default = /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(import_primitives9.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(import_primitives9.Path, { fillRule: "evenodd", d: "M8.95 11.25H4v1.5h4.95v4.5H13V18c0 1.1.9 2 2 2h3c1.1 0 2-.9 2-2v-3c0-1.1-.9-2-2-2h-3c-1.1 0-2 .9-2 2v.75h-2.55v-7.5H13V9c0 1.1.9 2 2 2h3c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3c-1.1 0-2 .9-2 2v.75H8.95v4.5ZM14.5 15v3c0 .3.2.5.5.5h3c.3 0 .5-.2.5-.5v-3c0-.3-.2-.5-.5-.5h-3c-.3 0-.5.2-.5.5Zm0-6V6c0-.3.2-.5.5-.5h3c.3 0 .5.2.5.5v3c0 .3-.2.5-.5.5h-3c-.3 0-.5-.2-.5-.5Z", clipRule: "evenodd" }) });

  // packages/icons/build-module/library/block-table.mjs
  var import_primitives10 = __toESM(require_primitives(), 1);
  var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1);
  var block_table_default = /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(import_primitives10.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(import_primitives10.Path, { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5 4.5h14c.3 0 .5.2.5.5v3.5h-15V5c0-.3.2-.5.5-.5zm8 5.5h6.5v3.5H13V10zm-1.5 3.5h-7V10h7v3.5zm-7 5.5v-4h7v4.5H5c-.3 0-.5-.2-.5-.5zm14.5.5h-6V15h6.5v4c0 .3-.2.5-.5.5z" }) });

  // packages/icons/build-module/library/calendar.mjs
  var import_primitives11 = __toESM(require_primitives(), 1);
  var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
  var calendar_default = /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_primitives11.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_primitives11.Path, { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm.5 16c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5V7h15v12zM9 10H7v2h2v-2zm0 4H7v2h2v-2zm4-4h-2v2h2v-2zm4 0h-2v2h2v-2zm-4 4h-2v2h2v-2zm4 0h-2v2h2v-2z" }) });

  // packages/icons/build-module/library/category.mjs
  var import_primitives12 = __toESM(require_primitives(), 1);
  var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1);
  var category_default = /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(import_primitives12.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(import_primitives12.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M6 5.5h3a.5.5 0 01.5.5v3a.5.5 0 01-.5.5H6a.5.5 0 01-.5-.5V6a.5.5 0 01.5-.5zM4 6a2 2 0 012-2h3a2 2 0 012 2v3a2 2 0 01-2 2H6a2 2 0 01-2-2V6zm11-.5h3a.5.5 0 01.5.5v3a.5.5 0 01-.5.5h-3a.5.5 0 01-.5-.5V6a.5.5 0 01.5-.5zM13 6a2 2 0 012-2h3a2 2 0 012 2v3a2 2 0 01-2 2h-3a2 2 0 01-2-2V6zm5 8.5h-3a.5.5 0 00-.5.5v3a.5.5 0 00.5.5h3a.5.5 0 00.5-.5v-3a.5.5 0 00-.5-.5zM15 13a2 2 0 00-2 2v3a2 2 0 002 2h3a2 2 0 002-2v-3a2 2 0 00-2-2h-3zm-9 1.5h3a.5.5 0 01.5.5v3a.5.5 0 01-.5.5H6a.5.5 0 01-.5-.5v-3a.5.5 0 01.5-.5zM4 15a2 2 0 012-2h3a2 2 0 012 2v3a2 2 0 01-2 2H6a2 2 0 01-2-2v-3z" }) });

  // packages/icons/build-module/library/check.mjs
  var import_primitives13 = __toESM(require_primitives(), 1);
  var import_jsx_runtime30 = __toESM(require_jsx_runtime(), 1);
  var check_default = /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_primitives13.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_primitives13.Path, { d: "M16.5 7.5 10 13.9l-2.5-2.4-1 1 3.5 3.6 7.5-7.6z" }) });

  // packages/icons/build-module/library/chevron-down.mjs
  var import_primitives14 = __toESM(require_primitives(), 1);
  var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1);
  var chevron_down_default = /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_primitives14.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_primitives14.Path, { d: "M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z" }) });

  // packages/icons/build-module/library/chevron-left-small.mjs
  var import_primitives15 = __toESM(require_primitives(), 1);
  var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
  var chevron_left_small_default = /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_primitives15.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_primitives15.Path, { d: "m13.1 16-3.4-4 3.4-4 1.1 1-2.6 3 2.6 3-1.1 1z" }) });

  // packages/icons/build-module/library/chevron-left.mjs
  var import_primitives16 = __toESM(require_primitives(), 1);
  var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1);
  var chevron_left_default = /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_primitives16.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_primitives16.Path, { d: "M14.6 7l-1.2-1L8 12l5.4 6 1.2-1-4.6-5z" }) });

  // packages/icons/build-module/library/chevron-right-small.mjs
  var import_primitives17 = __toESM(require_primitives(), 1);
  var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
  var chevron_right_small_default = /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(import_primitives17.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(import_primitives17.Path, { d: "M10.8622 8.04053L14.2805 12.0286L10.8622 16.0167L9.72327 15.0405L12.3049 12.0286L9.72327 9.01672L10.8622 8.04053Z" }) });

  // packages/icons/build-module/library/chevron-right.mjs
  var import_primitives18 = __toESM(require_primitives(), 1);
  var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1);
  var chevron_right_default = /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_primitives18.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_primitives18.Path, { d: "M10.6 6L9.4 7l4.6 5-4.6 5 1.2 1 5.4-6z" }) });

  // packages/icons/build-module/library/chevron-up.mjs
  var import_primitives19 = __toESM(require_primitives(), 1);
  var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1);
  var chevron_up_default = /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(import_primitives19.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(import_primitives19.Path, { d: "M6.5 12.4L12 8l5.5 4.4-.9 1.2L12 10l-4.5 3.6-1-1.2z" }) });

  // packages/icons/build-module/library/close-small.mjs
  var import_primitives20 = __toESM(require_primitives(), 1);
  var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1);
  var close_small_default = /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(import_primitives20.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(import_primitives20.Path, { d: "M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z" }) });

  // packages/icons/build-module/library/cog.mjs
  var import_primitives21 = __toESM(require_primitives(), 1);
  var import_jsx_runtime38 = __toESM(require_jsx_runtime(), 1);
  var cog_default = /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(import_primitives21.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(import_primitives21.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M10.289 4.836A1 1 0 0111.275 4h1.306a1 1 0 01.987.836l.244 1.466c.787.26 1.503.679 2.108 1.218l1.393-.522a1 1 0 011.216.437l.653 1.13a1 1 0 01-.23 1.273l-1.148.944a6.025 6.025 0 010 2.435l1.149.946a1 1 0 01.23 1.272l-.653 1.13a1 1 0 01-1.216.437l-1.394-.522c-.605.54-1.32.958-2.108 1.218l-.244 1.466a1 1 0 01-.987.836h-1.306a1 1 0 01-.986-.836l-.244-1.466a5.995 5.995 0 01-2.108-1.218l-1.394.522a1 1 0 01-1.217-.436l-.653-1.131a1 1 0 01.23-1.272l1.149-.946a6.026 6.026 0 010-2.435l-1.148-.944a1 1 0 01-.23-1.272l.653-1.131a1 1 0 011.217-.437l1.393.522a5.994 5.994 0 012.108-1.218l.244-1.466zM14.929 12a3 3 0 11-6 0 3 3 0 016 0z" }) });

  // packages/icons/build-module/library/comment-author-avatar.mjs
  var import_primitives22 = __toESM(require_primitives(), 1);
  var import_jsx_runtime39 = __toESM(require_jsx_runtime(), 1);
  var comment_author_avatar_default = /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(import_primitives22.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(import_primitives22.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M7.25 16.437a6.5 6.5 0 1 1 9.5 0V16A2.75 2.75 0 0 0 14 13.25h-4A2.75 2.75 0 0 0 7.25 16v.437Zm1.5 1.193a6.47 6.47 0 0 0 3.25.87 6.47 6.47 0 0 0 3.25-.87V16c0-.69-.56-1.25-1.25-1.25h-4c-.69 0-1.25.56-1.25 1.25v1.63ZM4 12a8 8 0 1 1 16 0 8 8 0 0 1-16 0Zm10-2a2 2 0 1 1-4 0 2 2 0 0 1 4 0Z" }) });

  // packages/icons/build-module/library/download.mjs
  var import_primitives23 = __toESM(require_primitives(), 1);
  var import_jsx_runtime40 = __toESM(require_jsx_runtime(), 1);
  var download_default = /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(import_primitives23.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(import_primitives23.Path, { d: "M18 11.3l-1-1.1-4 4V3h-1.5v11.3L7 10.2l-1 1.1 6.2 5.8 5.8-5.8zm.5 3.7v3.5h-13V15H4v5h16v-5h-1.5z" }) });

  // packages/icons/build-module/library/drafts.mjs
  var import_primitives24 = __toESM(require_primitives(), 1);
  var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1);
  var drafts_default = /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_primitives24.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_primitives24.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12 18.5a6.5 6.5 0 1 1 0-13 6.5 6.5 0 0 1 0 13ZM4 12a8 8 0 1 1 16 0 8 8 0 0 1-16 0Zm8 4a4 4 0 0 0 4-4H8a4 4 0 0 0 4 4Z" }) });

  // packages/icons/build-module/library/drawer-right.mjs
  var import_primitives25 = __toESM(require_primitives(), 1);
  var import_jsx_runtime42 = __toESM(require_jsx_runtime(), 1);
  var drawer_right_default = /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_primitives25.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_primitives25.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-4 14.5H6c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h8v13zm4.5-.5c0 .3-.2.5-.5.5h-2.5v-13H18c.3 0 .5.2.5.5v12z" }) });

  // packages/icons/build-module/library/envelope.mjs
  var import_primitives26 = __toESM(require_primitives(), 1);
  var import_jsx_runtime43 = __toESM(require_jsx_runtime(), 1);
  var envelope_default = /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(import_primitives26.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(import_primitives26.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M3 7c0-1.1.9-2 2-2h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Zm2-.5h14c.3 0 .5.2.5.5v1L12 13.5 4.5 7.9V7c0-.3.2-.5.5-.5Zm-.5 3.3V17c0 .3.2.5.5.5h14c.3 0 .5-.2.5-.5V9.8L12 15.4 4.5 9.8Z" }) });

  // packages/icons/build-module/library/error.mjs
  var import_primitives27 = __toESM(require_primitives(), 1);
  var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1);
  var error_default = /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(import_primitives27.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(import_primitives27.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12.218 5.377a.25.25 0 0 0-.436 0l-7.29 12.96a.25.25 0 0 0 .218.373h14.58a.25.25 0 0 0 .218-.372l-7.29-12.96Zm-1.743-.735c.669-1.19 2.381-1.19 3.05 0l7.29 12.96a1.75 1.75 0 0 1-1.525 2.608H4.71a1.75 1.75 0 0 1-1.525-2.608l7.29-12.96ZM12.75 17.46h-1.5v-1.5h1.5v1.5Zm-1.5-3h1.5v-5h-1.5v5Z" }) });

  // packages/icons/build-module/library/file.mjs
  var import_primitives28 = __toESM(require_primitives(), 1);
  var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1);
  var file_default = /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(import_primitives28.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(import_primitives28.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12.848 8a1 1 0 0 1-.914-.594l-.723-1.63a.5.5 0 0 0-.447-.276H5a.5.5 0 0 0-.5.5v11.5a.5.5 0 0 0 .5.5h14a.5.5 0 0 0 .5-.5v-9A.5.5 0 0 0 19 8h-6.152Zm.612-1.5a.5.5 0 0 1-.462-.31l-.445-1.084A2 2 0 0 0 10.763 4H5a2 2 0 0 0-2 2v11.5a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-9a2 2 0 0 0-2-2h-5.54Z" }) });

  // packages/icons/build-module/library/format-list-bullets-rtl.mjs
  var import_primitives29 = __toESM(require_primitives(), 1);
  var import_jsx_runtime46 = __toESM(require_jsx_runtime(), 1);
  var format_list_bullets_rtl_default = /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_primitives29.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_primitives29.Path, { d: "M4 8.8h8.9V7.2H4v1.6zm0 7h8.9v-1.5H4v1.5zM18 13c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z" }) });

  // packages/icons/build-module/library/format-list-bullets.mjs
  var import_primitives30 = __toESM(require_primitives(), 1);
  var import_jsx_runtime47 = __toESM(require_jsx_runtime(), 1);
  var format_list_bullets_default = /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(import_primitives30.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(import_primitives30.Path, { d: "M11.1 15.8H20v-1.5h-8.9v1.5zm0-8.6v1.5H20V7.2h-8.9zM6 13c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-7c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" }) });

  // packages/icons/build-module/library/funnel.mjs
  var import_primitives31 = __toESM(require_primitives(), 1);
  var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1);
  var funnel_default = /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(import_primitives31.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(import_primitives31.Path, { d: "M10 17.5H14V16H10V17.5ZM6 6V7.5H18V6H6ZM8 12.5H16V11H8V12.5Z" }) });

  // packages/icons/build-module/library/globe.mjs
  var import_primitives32 = __toESM(require_primitives(), 1);
  var import_jsx_runtime49 = __toESM(require_jsx_runtime(), 1);
  var globe_default = /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_primitives32.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_primitives32.Path, { d: "M12 4c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8Zm6.5 8c0 .6 0 1.2-.2 1.8h-2.7c0-.6.2-1.1.2-1.8s0-1.2-.2-1.8h2.7c.2.6.2 1.1.2 1.8Zm-.9-3.2h-2.4c-.3-.9-.7-1.8-1.1-2.4-.1-.2-.2-.4-.3-.5 1.6.5 3 1.6 3.8 3ZM12.8 17c-.3.5-.6 1-.8 1.3-.2-.3-.5-.8-.8-1.3-.3-.5-.6-1.1-.8-1.7h3.3c-.2.6-.5 1.2-.8 1.7Zm-2.9-3.2c-.1-.6-.2-1.1-.2-1.8s0-1.2.2-1.8H14c.1.6.2 1.1.2 1.8s0 1.2-.2 1.8H9.9ZM11.2 7c.3-.5.6-1 .8-1.3.2.3.5.8.8 1.3.3.5.6 1.1.8 1.7h-3.3c.2-.6.5-1.2.8-1.7Zm-1-1.2c-.1.2-.2.3-.3.5-.4.7-.8 1.5-1.1 2.4H6.4c.8-1.4 2.2-2.5 3.8-3Zm-1.8 8H5.7c-.2-.6-.2-1.1-.2-1.8s0-1.2.2-1.8h2.7c0 .6-.2 1.1-.2 1.8s0 1.2.2 1.8Zm-2 1.4h2.4c.3.9.7 1.8 1.1 2.4.1.2.2.4.3.5-1.6-.5-3-1.6-3.8-3Zm7.4 3c.1-.2.2-.3.3-.5.4-.7.8-1.5 1.1-2.4h2.4c-.8 1.4-2.2 2.5-3.8 3Z" }) });

  // packages/icons/build-module/library/help.mjs
  var import_primitives33 = __toESM(require_primitives(), 1);
  var import_jsx_runtime50 = __toESM(require_jsx_runtime(), 1);
  var help_default = /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_primitives33.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_primitives33.Path, { d: "M12 4a8 8 0 1 1 .001 16.001A8 8 0 0 1 12 4Zm0 1.5a6.5 6.5 0 1 0-.001 13.001A6.5 6.5 0 0 0 12 5.5Zm.75 11h-1.5V15h1.5v1.5Zm-.445-9.234a3 3 0 0 1 .445 5.89V14h-1.5v-1.25c0-.57.452-.958.917-1.01A1.5 1.5 0 0 0 12 8.75a1.5 1.5 0 0 0-1.5 1.5H9a3 3 0 0 1 3.305-2.984Z" }) });

  // packages/icons/build-module/library/home.mjs
  var import_primitives34 = __toESM(require_primitives(), 1);
  var import_jsx_runtime51 = __toESM(require_jsx_runtime(), 1);
  var home_default = /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(import_primitives34.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(import_primitives34.Path, { d: "M12 4L4 7.9V20h16V7.9L12 4zm6.5 14.5H14V13h-4v5.5H5.5V8.8L12 5.7l6.5 3.1v9.7z" }) });

  // packages/icons/build-module/library/layout.mjs
  var import_primitives35 = __toESM(require_primitives(), 1);
  var import_jsx_runtime52 = __toESM(require_jsx_runtime(), 1);
  var layout_default = /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_primitives35.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_primitives35.Path, { d: "M18 5.5H6a.5.5 0 00-.5.5v3h13V6a.5.5 0 00-.5-.5zm.5 5H10v8h8a.5.5 0 00.5-.5v-7.5zm-10 0h-3V18a.5.5 0 00.5.5h2.5v-8zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z" }) });

  // packages/icons/build-module/library/link.mjs
  var import_primitives36 = __toESM(require_primitives(), 1);
  var import_jsx_runtime53 = __toESM(require_jsx_runtime(), 1);
  var link_default = /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_primitives36.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_primitives36.Path, { d: "M10 17.389H8.444A5.194 5.194 0 1 1 8.444 7H10v1.5H8.444a3.694 3.694 0 0 0 0 7.389H10v1.5ZM14 7h1.556a5.194 5.194 0 0 1 0 10.39H14v-1.5h1.556a3.694 3.694 0 0 0 0-7.39H14V7Zm-4.5 6h5v-1.5h-5V13Z" }) });

  // packages/icons/build-module/library/list.mjs
  var import_primitives37 = __toESM(require_primitives(), 1);
  var import_jsx_runtime54 = __toESM(require_jsx_runtime(), 1);
  var list_default = /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(import_primitives37.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(import_primitives37.Path, { d: "M4 4v1.5h16V4H4zm8 8.5h8V11h-8v1.5zM4 20h16v-1.5H4V20zm4-8c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2z" }) });

  // packages/icons/build-module/library/media.mjs
  var import_primitives38 = __toESM(require_primitives(), 1);
  var import_jsx_runtime55 = __toESM(require_jsx_runtime(), 1);
  var media_default = /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(import_primitives38.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
    /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(import_primitives38.Path, { d: "m7 6.5 4 2.5-4 2.5z" }),
    /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(import_primitives38.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "m5 3c-1.10457 0-2 .89543-2 2v14c0 1.1046.89543 2 2 2h14c1.1046 0 2-.8954 2-2v-14c0-1.10457-.8954-2-2-2zm14 1.5h-14c-.27614 0-.5.22386-.5.5v10.7072l3.62953-2.6465c.25108-.1831.58905-.1924.84981-.0234l2.92666 1.8969 3.5712-3.4719c.2911-.2831.7545-.2831 1.0456 0l2.9772 2.8945v-9.3568c0-.27614-.2239-.5-.5-.5zm-14.5 14.5v-1.4364l4.09643-2.987 2.99567 1.9417c.2936.1903.6798.1523.9307-.0917l3.4772-3.3806 3.4772 3.3806.0228-.0234v2.5968c0 .2761-.2239.5-.5.5h-14c-.27614 0-.5-.2239-.5-.5z" })
  ] });

  // packages/icons/build-module/library/mobile.mjs
  var import_primitives39 = __toESM(require_primitives(), 1);
  var import_jsx_runtime56 = __toESM(require_jsx_runtime(), 1);
  var mobile_default = /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(import_primitives39.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(import_primitives39.Path, { d: "M15 4H9c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h6c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm.5 14c0 .3-.2.5-.5.5H9c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h6c.3 0 .5.2.5.5v12zm-4.5-.5h2V16h-2v1.5z" }) });

  // packages/icons/build-module/library/more-vertical.mjs
  var import_primitives40 = __toESM(require_primitives(), 1);
  var import_jsx_runtime57 = __toESM(require_jsx_runtime(), 1);
  var more_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_primitives40.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_primitives40.Path, { d: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z" }) });

  // packages/icons/build-module/library/navigation.mjs
  var import_primitives41 = __toESM(require_primitives(), 1);
  var import_jsx_runtime58 = __toESM(require_jsx_runtime(), 1);
  var navigation_default = /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(import_primitives41.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(import_primitives41.Path, { d: "M12 4c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8zm0 14.5c-3.6 0-6.5-2.9-6.5-6.5S8.4 5.5 12 5.5s6.5 2.9 6.5 6.5-2.9 6.5-6.5 6.5zM9 16l4.5-3L15 8.4l-4.5 3L9 16z" }) });

  // packages/icons/build-module/library/next.mjs
  var import_primitives42 = __toESM(require_primitives(), 1);
  var import_jsx_runtime59 = __toESM(require_jsx_runtime(), 1);
  var next_default = /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(import_primitives42.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(import_primitives42.Path, { d: "M6.6 6L5.4 7l4.5 5-4.5 5 1.1 1 5.5-6-5.4-6zm6 0l-1.1 1 4.5 5-4.5 5 1.1 1 5.5-6-5.5-6z" }) });

  // packages/icons/build-module/library/not-allowed.mjs
  var import_primitives43 = __toESM(require_primitives(), 1);
  var import_jsx_runtime60 = __toESM(require_jsx_runtime(), 1);
  var not_allowed_default = /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_primitives43.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_primitives43.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12 18.5A6.5 6.5 0 0 1 6.93 7.931l9.139 9.138A6.473 6.473 0 0 1 12 18.5Zm5.123-2.498a6.5 6.5 0 0 0-9.124-9.124l9.124 9.124ZM4 12a8 8 0 1 1 16 0 8 8 0 0 1-16 0Z" }) });

  // packages/icons/build-module/library/not-found.mjs
  var import_primitives44 = __toESM(require_primitives(), 1);
  var import_jsx_runtime61 = __toESM(require_jsx_runtime(), 1);
  var not_found_default = /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(import_primitives44.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(import_primitives44.Path, { d: "M19 5c1.1 0 2 .9 2 2v10c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2V7c0-1.1.9-2 2-2zM5 6.5c-.3 0-.5.2-.5.5v10c0 .3.2.5.5.5h14c.3 0 .5-.2.5-.5V7c0-.3-.2-.5-.5-.5zm7.01 2.75q.711 0 1.24.364.533.364.824 1.012.296.645.296 1.488 0 .887-.296 1.556-.292.664-.824 1.036-.528.368-1.24.368-.708 0-1.24-.368-.527-.372-.824-1.036-.296-.668-.296-1.556 0-.848.296-1.492.296-.648.824-1.008a2.14 2.14 0 0 1 1.24-.364m-3.484 3.6h.72v.832h-.72v1.28h-.984v-1.28H4.75l3.08-4.32h.696zm9.522 0h.72v.832h-.72v1.28h-.983v-1.28h-2.793l3.08-4.32h.696zm-6.038-2.696q-.568 0-.952.48-.384.475-.384 1.48 0 .716.176 1.168.176.45.476.66.304.212.684.212t.68-.208q.304-.207.48-.656.176-.451.176-1.176 0-.996-.384-1.476-.38-.484-.952-.484M6.33 12.85h1.212v-1.722zm9.523 0h1.211v-1.722z" }) });

  // packages/icons/build-module/library/page.mjs
  var import_primitives45 = __toESM(require_primitives(), 1);
  var import_jsx_runtime62 = __toESM(require_jsx_runtime(), 1);
  var page_default = /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(import_primitives45.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
    /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(import_primitives45.Path, { d: "M15.5 7.5h-7V9h7V7.5Zm-7 3.5h7v1.5h-7V11Zm7 3.5h-7V16h7v-1.5Z" }),
    /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(import_primitives45.Path, { d: "M17 4H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2ZM7 5.5h10a.5.5 0 0 1 .5.5v12a.5.5 0 0 1-.5.5H7a.5.5 0 0 1-.5-.5V6a.5.5 0 0 1 .5-.5Z" })
  ] });

  // packages/icons/build-module/library/pages.mjs
  var import_primitives46 = __toESM(require_primitives(), 1);
  var import_jsx_runtime63 = __toESM(require_jsx_runtime(), 1);
  var pages_default = /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(import_primitives46.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
    /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(import_primitives46.Path, { d: "M14.5 5.5h-7V7h7V5.5ZM7.5 9h7v1.5h-7V9Zm7 3.5h-7V14h7v-1.5Z" }),
    /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(import_primitives46.Path, { d: "M16 2H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2ZM6 3.5h10a.5.5 0 0 1 .5.5v12a.5.5 0 0 1-.5.5H6a.5.5 0 0 1-.5-.5V4a.5.5 0 0 1 .5-.5Z" }),
    /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(import_primitives46.Path, { d: "M20 8v11c0 .69-.31 1-.999 1H6v1.5h13.001c1.52 0 2.499-.982 2.499-2.5V8H20Z" })
  ] });

  // packages/icons/build-module/library/pencil.mjs
  var import_primitives47 = __toESM(require_primitives(), 1);
  var import_jsx_runtime64 = __toESM(require_jsx_runtime(), 1);
  var pencil_default = /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(import_primitives47.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(import_primitives47.Path, { d: "m19 7-3-3-8.5 8.5-1 4 4-1L19 7Zm-7 11.5H5V20h7v-1.5Z" }) });

  // packages/icons/build-module/library/pending.mjs
  var import_primitives48 = __toESM(require_primitives(), 1);
  var import_jsx_runtime65 = __toESM(require_jsx_runtime(), 1);
  var pending_default = /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_primitives48.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_primitives48.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12 18.5a6.5 6.5 0 1 1 0-13 6.5 6.5 0 0 1 0 13ZM4 12a8 8 0 1 1 16 0 8 8 0 0 1-16 0Zm8 4a4 4 0 0 1-4-4h4V8a4 4 0 0 1 0 8Z" }) });

  // packages/icons/build-module/library/pin.mjs
  var import_primitives49 = __toESM(require_primitives(), 1);
  var import_jsx_runtime66 = __toESM(require_jsx_runtime(), 1);
  var pin_default = /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(import_primitives49.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(import_primitives49.Path, { d: "m21.5 9.1-6.6-6.6-4.2 5.6c-1.2-.1-2.4.1-3.6.7-.1 0-.1.1-.2.1-.5.3-.9.6-1.2.9l3.7 3.7-5.7 5.7v1.1h1.1l5.7-5.7 3.7 3.7c.4-.4.7-.8.9-1.2.1-.1.1-.2.2-.3.6-1.1.8-2.4.6-3.6l5.6-4.1zm-7.3 3.5.1.9c.1.9 0 1.8-.4 2.6l-6-6c.8-.4 1.7-.5 2.6-.4l.9.1L15 4.9 19.1 9l-4.9 3.6z" }) });

  // packages/icons/build-module/library/plugins.mjs
  var import_primitives50 = __toESM(require_primitives(), 1);
  var import_jsx_runtime67 = __toESM(require_jsx_runtime(), 1);
  var plugins_default = /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(import_primitives50.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(import_primitives50.Path, { d: "M10.5 4v4h3V4H15v4h1.5a1 1 0 011 1v4l-3 4v2a1 1 0 01-1 1h-3a1 1 0 01-1-1v-2l-3-4V9a1 1 0 011-1H9V4h1.5zm.5 12.5v2h2v-2l3-4v-3H8v3l3 4z" }) });

  // packages/icons/build-module/library/post.mjs
  var import_primitives51 = __toESM(require_primitives(), 1);
  var import_jsx_runtime68 = __toESM(require_jsx_runtime(), 1);
  var post_default = /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(import_primitives51.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(import_primitives51.Path, { d: "m7.3 9.7 1.4 1.4c.2-.2.3-.3.4-.5 0 0 0-.1.1-.1.3-.5.4-1.1.3-1.6L12 7 9 4 7.2 6.5c-.6-.1-1.1 0-1.6.3 0 0-.1 0-.1.1-.3.1-.4.2-.6.4l1.4 1.4L4 11v1h1l2.3-2.3zM4 20h9v-1.5H4V20zm0-5.5V16h16v-1.5H4z" }) });

  // packages/icons/build-module/library/previous.mjs
  var import_primitives52 = __toESM(require_primitives(), 1);
  var import_jsx_runtime69 = __toESM(require_jsx_runtime(), 1);
  var previous_default = /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(import_primitives52.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(import_primitives52.Path, { d: "M11.6 7l-1.1-1L5 12l5.5 6 1.1-1L7 12l4.6-5zm6 0l-1.1-1-5.5 6 5.5 6 1.1-1-4.6-5 4.6-5z" }) });

  // packages/icons/build-module/library/published.mjs
  var import_primitives53 = __toESM(require_primitives(), 1);
  var import_jsx_runtime70 = __toESM(require_jsx_runtime(), 1);
  var published_default = /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_primitives53.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_primitives53.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12 18.5a6.5 6.5 0 1 1 0-13 6.5 6.5 0 0 1 0 13ZM4 12a8 8 0 1 1 16 0 8 8 0 0 1-16 0Zm11.53-1.47-1.06-1.06L11 12.94l-1.47-1.47-1.06 1.06L11 15.06l4.53-4.53Z" }) });

  // packages/icons/build-module/library/rotate-left.mjs
  var import_primitives54 = __toESM(require_primitives(), 1);
  var import_jsx_runtime71 = __toESM(require_jsx_runtime(), 1);
  var rotate_left_default = /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(import_primitives54.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(import_primitives54.Path, { d: "M12 4V2.2L9 4.8l3 2.5V5.5c3.6 0 6.5 2.9 6.5 6.5 0 2.9-1.9 5.3-4.5 6.2v.2l-.1-.2c-.4.1-.7.2-1.1.2l.2 1.5c.3 0 .6-.1 1-.2 3.5-.9 6-4 6-7.7 0-4.4-3.6-8-8-8zm-7.9 7l1.5.2c.1-1.2.5-2.3 1.2-3.2l-1.1-.9C4.8 8.2 4.3 9.6 4.1 11zm1.5 1.8l-1.5.2c.1.7.3 1.4.5 2 .3.7.6 1.3 1 1.8l1.2-.8c-.3-.5-.6-1-.8-1.5s-.4-1.1-.4-1.7zm1.5 5.5c1.1.9 2.4 1.4 3.8 1.6l.2-1.5c-1.1-.1-2.2-.5-3.1-1.2l-.9 1.1z" }) });

  // packages/icons/build-module/library/rotate-right.mjs
  var import_primitives55 = __toESM(require_primitives(), 1);
  var import_jsx_runtime72 = __toESM(require_jsx_runtime(), 1);
  var rotate_right_default = /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_primitives55.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_primitives55.Path, { d: "M15.1 4.8l-3-2.5V4c-4.4 0-8 3.6-8 8 0 3.7 2.5 6.9 6 7.7.3.1.6.1 1 .2l.2-1.5c-.4 0-.7-.1-1.1-.2l-.1.2v-.2c-2.6-.8-4.5-3.3-4.5-6.2 0-3.6 2.9-6.5 6.5-6.5v1.8l3-2.5zM20 11c-.2-1.4-.7-2.7-1.6-3.8l-1.2.8c.7.9 1.1 2 1.3 3.1L20 11zm-1.5 1.8c-.1.5-.2 1.1-.4 1.6s-.5 1-.8 1.5l1.2.9c.4-.5.8-1.1 1-1.8s.5-1.3.5-2l-1.5-.2zm-5.6 5.6l.2 1.5c1.4-.2 2.7-.7 3.8-1.6l-.9-1.1c-.9.7-2 1.1-3.1 1.2z" }) });

  // packages/icons/build-module/library/scheduled.mjs
  var import_primitives56 = __toESM(require_primitives(), 1);
  var import_jsx_runtime73 = __toESM(require_jsx_runtime(), 1);
  var scheduled_default = /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(import_primitives56.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(import_primitives56.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12 18.5a6.5 6.5 0 1 1 0-13 6.5 6.5 0 0 1 0 13ZM4 12a8 8 0 1 1 16 0 8 8 0 0 1-16 0Zm9 1V8h-1.5v3.5h-2V13H13Z" }) });

  // packages/icons/build-module/library/search.mjs
  var import_primitives57 = __toESM(require_primitives(), 1);
  var import_jsx_runtime74 = __toESM(require_jsx_runtime(), 1);
  var search_default = /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_primitives57.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_primitives57.Path, { d: "M13 5c-3.3 0-6 2.7-6 6 0 1.4.5 2.7 1.3 3.7l-3.8 3.8 1.1 1.1 3.8-3.8c1 .8 2.3 1.3 3.7 1.3 3.3 0 6-2.7 6-6S16.3 5 13 5zm0 10.5c-2.5 0-4.5-2-4.5-4.5s2-4.5 4.5-4.5 4.5 2 4.5 4.5-2 4.5-4.5 4.5z" }) });

  // packages/icons/build-module/library/seen.mjs
  var import_primitives58 = __toESM(require_primitives(), 1);
  var import_jsx_runtime75 = __toESM(require_jsx_runtime(), 1);
  var seen_default = /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_primitives58.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_primitives58.Path, { d: "M3.99961 13C4.67043 13.3354 4.6703 13.3357 4.67017 13.3359L4.67298 13.3305C4.67621 13.3242 4.68184 13.3135 4.68988 13.2985C4.70595 13.2686 4.7316 13.2218 4.76695 13.1608C4.8377 13.0385 4.94692 12.8592 5.09541 12.6419C5.39312 12.2062 5.84436 11.624 6.45435 11.0431C7.67308 9.88241 9.49719 8.75 11.9996 8.75C14.502 8.75 16.3261 9.88241 17.5449 11.0431C18.1549 11.624 18.6061 12.2062 18.9038 12.6419C19.0523 12.8592 19.1615 13.0385 19.2323 13.1608C19.2676 13.2218 19.2933 13.2686 19.3093 13.2985C19.3174 13.3135 19.323 13.3242 19.3262 13.3305L19.3291 13.3359C19.3289 13.3357 19.3288 13.3354 19.9996 13C20.6704 12.6646 20.6703 12.6643 20.6701 12.664L20.6697 12.6632L20.6688 12.6614L20.6662 12.6563L20.6583 12.6408C20.6517 12.6282 20.6427 12.6108 20.631 12.5892C20.6078 12.5459 20.5744 12.4852 20.5306 12.4096C20.4432 12.2584 20.3141 12.0471 20.1423 11.7956C19.7994 11.2938 19.2819 10.626 18.5794 9.9569C17.1731 8.61759 14.9972 7.25 11.9996 7.25C9.00203 7.25 6.82614 8.61759 5.41987 9.9569C4.71736 10.626 4.19984 11.2938 3.85694 11.7956C3.68511 12.0471 3.55605 12.2584 3.4686 12.4096C3.42484 12.4852 3.39142 12.5459 3.36818 12.5892C3.35656 12.6108 3.34748 12.6282 3.34092 12.6408L3.33297 12.6563L3.33041 12.6614L3.32948 12.6632L3.32911 12.664C3.32894 12.6643 3.32879 12.6646 3.99961 13ZM11.9996 16C13.9326 16 15.4996 14.433 15.4996 12.5C15.4996 10.567 13.9326 9 11.9996 9C10.0666 9 8.49961 10.567 8.49961 12.5C8.49961 14.433 10.0666 16 11.9996 16Z" }) });

  // packages/icons/build-module/library/site-logo.mjs
  var import_primitives59 = __toESM(require_primitives(), 1);
  var import_jsx_runtime76 = __toESM(require_jsx_runtime(), 1);
  var site_logo_default = /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(import_primitives59.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(import_primitives59.Path, { d: "M12 4c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8Zm0 1.5c3.4 0 6.2 2.7 6.5 6l-1.2-.6-.8-.4c-.1 0-.2 0-.3-.1H16c-.1-.2-.4-.2-.7 0l-2.9 2.1L9 11.3h-.7L5.5 13v-1.1c0-3.6 2.9-6.5 6.5-6.5Zm0 13c-2.7 0-5-1.7-6-4l2.8-1.7 3.5 1.2h.4s.2 0 .4-.2l2.9-2.1.4.2c.6.3 1.4.7 2.1 1.1-.5 3.1-3.2 5.4-6.4 5.4Z" }) });

  // packages/icons/build-module/library/styles.mjs
  var import_primitives60 = __toESM(require_primitives(), 1);
  var import_jsx_runtime77 = __toESM(require_jsx_runtime(), 1);
  var styles_default = /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(import_primitives60.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(import_primitives60.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M20 12a8 8 0 1 1-16 0 8 8 0 0 1 16 0Zm-1.5 0a6.5 6.5 0 0 1-6.5 6.5v-13a6.5 6.5 0 0 1 6.5 6.5Z" }) });

  // packages/icons/build-module/library/symbol-filled.mjs
  var import_primitives61 = __toESM(require_primitives(), 1);
  var import_jsx_runtime78 = __toESM(require_jsx_runtime(), 1);
  var symbol_filled_default = /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_primitives61.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_primitives61.Path, { d: "M21.3 10.8l-5.6-5.6c-.7-.7-1.8-.7-2.5 0l-5.6 5.6c-.7.7-.7 1.8 0 2.5l5.6 5.6c.3.3.8.5 1.2.5s.9-.2 1.2-.5l5.6-5.6c.8-.7.8-1.9.1-2.5zm-17.6 1L10 5.5l-1-1-6.3 6.3c-.7.7-.7 1.8 0 2.5L9 19.5l1.1-1.1-6.3-6.3c-.2 0-.2-.2-.1-.3z" }) });

  // packages/icons/build-module/library/symbol.mjs
  var import_primitives62 = __toESM(require_primitives(), 1);
  var import_jsx_runtime79 = __toESM(require_jsx_runtime(), 1);
  var symbol_default = /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(import_primitives62.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(import_primitives62.Path, { d: "M21.3 10.8l-5.6-5.6c-.7-.7-1.8-.7-2.5 0l-5.6 5.6c-.7.7-.7 1.8 0 2.5l5.6 5.6c.3.3.8.5 1.2.5s.9-.2 1.2-.5l5.6-5.6c.8-.7.8-1.9.1-2.5zm-1 1.4l-5.6 5.6c-.1.1-.3.1-.4 0l-5.6-5.6c-.1-.1-.1-.3 0-.4l5.6-5.6s.1-.1.2-.1.1 0 .2.1l5.6 5.6c.1.1.1.3 0 .4zm-16.6-.4L10 5.5l-1-1-6.3 6.3c-.7.7-.7 1.8 0 2.5L9 19.5l1.1-1.1-6.3-6.3c-.2 0-.2-.2-.1-.3z" }) });

  // packages/icons/build-module/library/tag.mjs
  var import_primitives63 = __toESM(require_primitives(), 1);
  var import_jsx_runtime80 = __toESM(require_jsx_runtime(), 1);
  var tag_default = /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(import_primitives63.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(import_primitives63.Path, { d: "M4.75 4a.75.75 0 0 0-.75.75v7.826c0 .2.08.39.22.53l6.72 6.716a2.313 2.313 0 0 0 3.276-.001l5.61-5.611-.531-.53.532.528a2.315 2.315 0 0 0 0-3.264L13.104 4.22a.75.75 0 0 0-.53-.22H4.75ZM19 12.576a.815.815 0 0 1-.236.574l-5.61 5.611a.814.814 0 0 1-1.153 0L5.5 12.264V5.5h6.763l6.5 6.502a.816.816 0 0 1 .237.574ZM8.75 9.75a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z" }) });

  // packages/icons/build-module/library/trash.mjs
  var import_primitives64 = __toESM(require_primitives(), 1);
  var import_jsx_runtime81 = __toESM(require_jsx_runtime(), 1);
  var trash_default = /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_primitives64.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_primitives64.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M12 5.5A2.25 2.25 0 0 0 9.878 7h4.244A2.251 2.251 0 0 0 12 5.5ZM12 4a3.751 3.751 0 0 0-3.675 3H5v1.5h1.27l.818 8.997a2.75 2.75 0 0 0 2.739 2.501h4.347a2.75 2.75 0 0 0 2.738-2.5L17.73 8.5H19V7h-3.325A3.751 3.751 0 0 0 12 4Zm4.224 4.5H7.776l.806 8.861a1.25 1.25 0 0 0 1.245 1.137h4.347a1.25 1.25 0 0 0 1.245-1.137l.805-8.861Z" }) });

  // packages/icons/build-module/library/unseen.mjs
  var import_primitives65 = __toESM(require_primitives(), 1);
  var import_jsx_runtime82 = __toESM(require_jsx_runtime(), 1);
  var unseen_default = /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_primitives65.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_primitives65.Path, { d: "M20.7 12.7s0-.1-.1-.2c0-.2-.2-.4-.4-.6-.3-.5-.9-1.2-1.6-1.8-.7-.6-1.5-1.3-2.6-1.8l-.6 1.4c.9.4 1.6 1 2.1 1.5.6.6 1.1 1.2 1.4 1.6.1.2.3.4.3.5v.1l.7-.3.7-.3Zm-5.2-9.3-1.8 4c-.5-.1-1.1-.2-1.7-.2-3 0-5.2 1.4-6.6 2.7-.7.7-1.2 1.3-1.6 1.8-.2.3-.3.5-.4.6 0 0 0 .1-.1.2s0 0 .7.3l.7.3V13c0-.1.2-.3.3-.5.3-.4.7-1 1.4-1.6 1.2-1.2 3-2.3 5.5-2.3H13v.3c-.4 0-.8-.1-1.1-.1-1.9 0-3.5 1.6-3.5 3.5s.6 2.3 1.6 2.9l-2 4.4.9.4 7.6-16.2-.9-.4Zm-3 12.6c1.7-.2 3-1.7 3-3.5s-.2-1.4-.6-1.9L12.4 16Z" }) });

  // packages/icons/build-module/library/upload.mjs
  var import_primitives66 = __toESM(require_primitives(), 1);
  var import_jsx_runtime83 = __toESM(require_jsx_runtime(), 1);
  var upload_default = /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_primitives66.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_primitives66.Path, { d: "M18.5 15v3.5H13V6.7l4.5 4.1 1-1.1-6.2-5.8-5.8 5.8 1 1.1 4-4v11.7h-6V15H4v5h16v-5z" }) });

  // packages/icons/build-module/library/verse.mjs
  var import_primitives67 = __toESM(require_primitives(), 1);
  var import_jsx_runtime84 = __toESM(require_jsx_runtime(), 1);
  var verse_default = /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(import_primitives67.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(import_primitives67.Path, { d: "M17.8 2l-.9.3c-.1 0-3.6 1-5.2 2.1C10 5.5 9.3 6.5 8.9 7.1c-.6.9-1.7 4.7-1.7 6.3l-.9 2.3c-.2.4 0 .8.4 1 .1 0 .2.1.3.1.3 0 .6-.2.7-.5l.6-1.5c.3 0 .7-.1 1.2-.2.7-.1 1.4-.3 2.2-.5.8-.2 1.6-.5 2.4-.8.7-.3 1.4-.7 1.9-1.2s.8-1.2 1-1.9c.2-.7.3-1.6.4-2.4.1-.8.1-1.7.2-2.5 0-.8.1-1.5.2-2.1V2zm-1.9 5.6c-.1.8-.2 1.5-.3 2.1-.2.6-.4 1-.6 1.3-.3.3-.8.6-1.4.9-.7.3-1.4.5-2.2.8-.6.2-1.3.3-1.8.4L15 7.5c.3-.3.6-.7 1-1.1 0 .4 0 .8-.1 1.2zM6 20h8v-1.5H6V20z" }) });

  // packages/icons/build-module/library/video.mjs
  var import_primitives68 = __toESM(require_primitives(), 1);
  var import_jsx_runtime85 = __toESM(require_jsx_runtime(), 1);
  var video_default = /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_primitives68.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_primitives68.Path, { d: "M18.7 3H5.3C4 3 3 4 3 5.3v13.4C3 20 4 21 5.3 21h13.4c1.3 0 2.3-1 2.3-2.3V5.3C21 4 20 3 18.7 3zm.8 15.7c0 .4-.4.8-.8.8H5.3c-.4 0-.8-.4-.8-.8V5.3c0-.4.4-.8.8-.8h13.4c.4 0 .8.4.8.8v13.4zM10 15l5-3-5-3v6z" }) });

  // packages/ui/build-module/collapsible-card/context.mjs
  var import_element23 = __toESM(require_element(), 1);
  var HeaderDescriptionIdContext = (0, import_element23.createContext)({
    setDescriptionId: () => {
    }
  });

  // packages/ui/build-module/collapsible-card/header.mjs
  var import_jsx_runtime86 = __toESM(require_jsx_runtime(), 1);
  var STYLE_HASH_ATTRIBUTE7 = "data-wp-hash";
  function getRuntime7() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument7(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash7(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE7}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE7) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle7(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime7();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash7(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE7, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument7(targetDocument) {
    const runtime = getRuntime7();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle7(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle7(hash, css) {
    const runtime = getRuntime7();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle7(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle7("78199613cf", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._626190151275d6d3__heading-wrapper{--_gcd-heading-color:inherit;--_gcd-heading-font-size:inherit;--_gcd-heading-font-weight:inherit;--_gcd-heading-margin:0;font-family:inherit;line-height:inherit}.cab17c7a373cb60d__header-content{flex:1;min-width:0}.dd89d27c4f15912d__header-trigger-positioner{align-self:center;flex-shrink:0;max-height:0;overflow:visible}.bcfab5f2448bafef__header-trigger-wrapper{border-radius:var(--wpds-border-radius-sm,2px);display:flex;translate:0 -50%}._3106f8d2b0330faa__header-trigger{@media not (prefers-reduced-motion){transition:rotate .15s ease-out}}._5d2dfcb4085c6d0f__header[data-panel-open] ._3106f8d2b0330faa__header-trigger{rotate:180deg}._5d2dfcb4085c6d0f__header[data-disabled] ._3106f8d2b0330faa__header-trigger{color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d)}.e34cf37ccd0d81e0__content{height:var(--collapsible-panel-height);margin-block-start:var(--wp-ui-card-header-content-margin);overflow:hidden;&._03cfdbcd710393c9__overflow-visible{overflow:visible}&[hidden]:not([hidden=until-found]){display:none}&[data-ending-style],&[data-starting-style]{height:0}@media not (prefers-reduced-motion){transition:all .15s ease-out}}}@layer compositions{._41bfdbf7b6c087c2__content-inner{padding-block-start:0}._5d2dfcb4085c6d0f__header{align-items:stretch;display:flex;flex-direction:row;gap:var(--wpds-dimension-gap-sm,8px);outline:none;&:not([data-disabled]){cursor:var(--wpds-cursor-control,pointer)}}}}");
  }
  var style_default7 = { "heading-wrapper": "_626190151275d6d3__heading-wrapper", "header-content": "cab17c7a373cb60d__header-content", "header-trigger-positioner": "dd89d27c4f15912d__header-trigger-positioner", "header-trigger-wrapper": "bcfab5f2448bafef__header-trigger-wrapper", "header-trigger": "_3106f8d2b0330faa__header-trigger", "header": "_5d2dfcb4085c6d0f__header", "content": "e34cf37ccd0d81e0__content", "overflow-visible": "_03cfdbcd710393c9__overflow-visible", "content-inner": "_41bfdbf7b6c087c2__content-inner" };
  if (typeof process === "undefined" || true) {
    registerStyle7("af6d9984a6", "._6defc79820e382c6__button{box-sizing:var(--_gcd-button-box-sizing,border-box);font-family:var(--_gcd-button-font-family,inherit);font-size:var(--_gcd-button-font-size,inherit);font-weight:var(--_gcd-button-font-weight,inherit)}.d2cff2e5dea83bd1__input{box-sizing:var(--_gcd-input-box-sizing,border-box);font-family:var(--_gcd-input-font-family,inherit);font-size:var(--_gcd-input-font-size,inherit);font-weight:var(--_gcd-input-font-weight,inherit);margin:var(--_gcd-input-margin,0);&:is(textarea,[type=text],[type=password],[type=color],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){background-color:var(--_gcd-input-background-color,transparent);border:var(--_gcd-input-border,none);border-radius:var(--_gcd-input-border-radius,0);box-shadow:var(--_gcd-input-box-shadow,0 0 0 transparent);color:var(--_gcd-input-color,var(--wpds-color-foreground-interactive-neutral,#1e1e1e));&:focus{border-color:var(--_gcd-input-border-color-focus,var(--wp-admin-theme-color));box-shadow:var(--_gcd-input-box-shadow-focus,none);outline:var(--_gcd-input-outline-focus,none)}&:disabled{background:var(--_gcd-input-background-disabled,transparent);border-color:var(--_gcd-input-border-color-disabled,transparent);box-shadow:var(--_gcd-input-box-shadow-disabled,none);color:var(--_gcd-input-color-disabled,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}&::placeholder{color:var(--_gcd-input-placeholder-color,var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d))}}&:is(textarea,[type=text],[type=password],[type=date],[type=datetime],[type=datetime-local],[type=email],[type=month],[type=number],[type=search],[type=tel],[type=time],[type=url],[type=week]){line-height:var(--_gcd-input-line-height,inherit);min-height:var(--_gcd-input-min-height,auto);padding:var(--_gcd-input-padding,0)}}._547d86373d02e108__textarea{box-sizing:var(--_gcd-textarea-box-sizing,border-box);overflow:var(--_gcd-textarea-overflow,auto);resize:var(--_gcd-textarea-resize,block)}._8c15fd0ed9f28ba4__div{outline:var(--_gcd-div-outline,0 solid transparent)}p._43cec3e1eec1066d__p{font-size:var(--_gcd-p-font-size,13px);line-height:var(--_gcd-p-line-height,1.5);margin:var(--_gcd-p-margin,0)}:is(h1,h2,h3,h4,h5,h6).e97669c6d9a38497__heading{color:var(--_gcd-heading-color,var(--wpds-color-foreground-content-neutral,#1e1e1e));font-size:var(--_gcd-heading-font-size,inherit);font-weight:var(--_gcd-heading-font-weight,var(--wpds-typography-font-weight-emphasis,600));margin:var(--_gcd-heading-margin,0)}._2c0831b0499dbd6e__a,._2c0831b0499dbd6e__a:is(:hover,:focus,:active){border-radius:var(--_gcd-a-border-radius,0);box-shadow:var(--_gcd-a-box-shadow,none);color:var(--_gcd-a-color,inherit);outline:var(--_gcd-a-outline,0 solid transparent);transition:var(--_gcd-a-transition,none)}");
  }
  var global_css_defense_default2 = { "button": "_6defc79820e382c6__button", "input": "d2cff2e5dea83bd1__input", "textarea": "_547d86373d02e108__textarea", "div": "_8c15fd0ed9f28ba4__div", "p": "_43cec3e1eec1066d__p", "heading": "e97669c6d9a38497__heading", "a": "_2c0831b0499dbd6e__a" };
  if (typeof process === "undefined" || true) {
    registerStyle7("5f8e7aa0bc", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._08e8a2e44959f892__outset-ring--focus:focus,._970d04df7376df67__outset-ring--focus-within-except-active:focus-within:not(:has(:active)),.c5cb3ee4bddaa8e4__outset-ring--focus-within-visible:focus-within:has(:focus-visible),.cd83dfc2126a0846__outset-ring--focus-within:focus-within,.d0541bc9dd9dc7b6__outset-ring--focus-visible:focus-visible,.e25b2bdd7aa21721__outset-ring--focus-except-active:focus:not(:active),:focus-visible .ecadb9e080e2dfa5__outset-ring--focus-parent-visible{--_gcd-a-outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));--_gcd-div-outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));outline-offset:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px))}}}");
  }
  var focus_default = { "outset-ring--focus": "_08e8a2e44959f892__outset-ring--focus", "outset-ring--focus-except-active": "e25b2bdd7aa21721__outset-ring--focus-except-active", "outset-ring--focus-visible": "d0541bc9dd9dc7b6__outset-ring--focus-visible", "outset-ring--focus-within": "cd83dfc2126a0846__outset-ring--focus-within", "outset-ring--focus-within-except-active": "_970d04df7376df67__outset-ring--focus-within-except-active", "outset-ring--focus-within-visible": "c5cb3ee4bddaa8e4__outset-ring--focus-within-visible", "outset-ring--focus-parent-visible": "ecadb9e080e2dfa5__outset-ring--focus-parent-visible" };
  var Header2 = (0, import_element24.forwardRef)(
    function CollapsibleCardHeader({ children, className, render: render4, ...restProps }, ref) {
      const [descriptionId, setDescriptionId] = (0, import_element24.useState)();
      const contextValue = (0, import_element24.useMemo)(
        () => ({ setDescriptionId }),
        [setDescriptionId]
      );
      return useRender({
        defaultTagName: "div",
        render: render4,
        ref,
        props: mergeProps(restProps, {
          className: clsx_default(
            global_css_defense_default2.heading,
            style_default7["heading-wrapper"],
            className
          ),
          children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(HeaderDescriptionIdContext.Provider, { value: contextValue, children: /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(
            Trigger,
            {
              className: style_default7.header,
              render: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Header, {}),
              nativeButton: false,
              "aria-describedby": descriptionId,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime86.jsx)("div", { className: style_default7["header-content"], children }),
                /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
                  "div",
                  {
                    className: clsx_default(
                      style_default7["header-trigger-positioner"]
                    ),
                    children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
                      "div",
                      {
                        className: clsx_default(
                          style_default7["header-trigger-wrapper"],
                          global_css_defense_default2.div,
                          // While the interactive trigger element is the whole header,
                          // the focus ring will be displayed only on the icon to visually
                          // emulate it being the button.
                          focus_default["outset-ring--focus-parent-visible"]
                        ),
                        children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
                          Icon,
                          {
                            icon: chevron_down_default,
                            className: style_default7["header-trigger"]
                          }
                        )
                      }
                    )
                  }
                )
              ]
            }
          ) })
        })
      });
    }
  );

  // packages/ui/build-module/collapsible-card/header-description.mjs
  var import_element25 = __toESM(require_element(), 1);
  var import_jsx_runtime87 = __toESM(require_jsx_runtime(), 1);
  var HeaderDescription = (0, import_element25.forwardRef)(function CollapsibleCardHeaderDescription({ children, className, ...restProps }, ref) {
    const descriptionId = (0, import_element25.useId)();
    const { setDescriptionId } = (0, import_element25.useContext)(HeaderDescriptionIdContext);
    (0, import_element25.useEffect)(() => {
      setDescriptionId(descriptionId);
      return () => setDescriptionId(void 0);
    }, [descriptionId, setDescriptionId]);
    return /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(
      "div",
      {
        ref,
        id: descriptionId,
        "aria-hidden": "true",
        className,
        ...restProps,
        children
      }
    );
  });

  // packages/ui/build-module/collapsible-card/content.mjs
  var import_element26 = __toESM(require_element(), 1);
  var import_jsx_runtime88 = __toESM(require_jsx_runtime(), 1);
  var STYLE_HASH_ATTRIBUTE8 = "data-wp-hash";
  function getRuntime8() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument8(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash8(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE8}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE8) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle8(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime8();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash8(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE8, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument8(targetDocument) {
    const runtime = getRuntime8();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle8(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle8(hash, css) {
    const runtime = getRuntime8();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle8(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle8("78199613cf", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._626190151275d6d3__heading-wrapper{--_gcd-heading-color:inherit;--_gcd-heading-font-size:inherit;--_gcd-heading-font-weight:inherit;--_gcd-heading-margin:0;font-family:inherit;line-height:inherit}.cab17c7a373cb60d__header-content{flex:1;min-width:0}.dd89d27c4f15912d__header-trigger-positioner{align-self:center;flex-shrink:0;max-height:0;overflow:visible}.bcfab5f2448bafef__header-trigger-wrapper{border-radius:var(--wpds-border-radius-sm,2px);display:flex;translate:0 -50%}._3106f8d2b0330faa__header-trigger{@media not (prefers-reduced-motion){transition:rotate .15s ease-out}}._5d2dfcb4085c6d0f__header[data-panel-open] ._3106f8d2b0330faa__header-trigger{rotate:180deg}._5d2dfcb4085c6d0f__header[data-disabled] ._3106f8d2b0330faa__header-trigger{color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d)}.e34cf37ccd0d81e0__content{height:var(--collapsible-panel-height);margin-block-start:var(--wp-ui-card-header-content-margin);overflow:hidden;&._03cfdbcd710393c9__overflow-visible{overflow:visible}&[hidden]:not([hidden=until-found]){display:none}&[data-ending-style],&[data-starting-style]{height:0}@media not (prefers-reduced-motion){transition:all .15s ease-out}}}@layer compositions{._41bfdbf7b6c087c2__content-inner{padding-block-start:0}._5d2dfcb4085c6d0f__header{align-items:stretch;display:flex;flex-direction:row;gap:var(--wpds-dimension-gap-sm,8px);outline:none;&:not([data-disabled]){cursor:var(--wpds-cursor-control,pointer)}}}}");
  }
  var style_default8 = { "heading-wrapper": "_626190151275d6d3__heading-wrapper", "header-content": "cab17c7a373cb60d__header-content", "header-trigger-positioner": "dd89d27c4f15912d__header-trigger-positioner", "header-trigger-wrapper": "bcfab5f2448bafef__header-trigger-wrapper", "header-trigger": "_3106f8d2b0330faa__header-trigger", "header": "_5d2dfcb4085c6d0f__header", "content": "e34cf37ccd0d81e0__content", "overflow-visible": "_03cfdbcd710393c9__overflow-visible", "content-inner": "_41bfdbf7b6c087c2__content-inner" };
  var Content2 = (0, import_element26.forwardRef)(
    function CollapsibleCardContent({ className, render: render4, children, hiddenUntilFound = true, ...restProps }, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
        Panel,
        {
          ref,
          className: (state) => clsx_default(
            style_default8.content,
            state.open && state.transitionStatus === "idle" && style_default8["overflow-visible"],
            className
          ),
          hiddenUntilFound,
          ...restProps,
          children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
            Content,
            {
              className: style_default8["content-inner"],
              render: render4,
              children
            }
          )
        }
      );
    }
  );

  // packages/ui/build-module/utils/render-slot-with-children.mjs
  var import_element27 = __toESM(require_element(), 1);
  function renderSlotWithChildren(slot, defaultSlot, children) {
    return (0, import_element27.cloneElement)(slot ?? defaultSlot, { children });
  }

  // packages/ui/build-module/utils/theme-provider.mjs
  var theme = __toESM(require_theme(), 1);

  // packages/ui/build-module/lock-unlock.mjs
  var import_private_apis2 = __toESM(require_private_apis(), 1);
  var { lock: lock2, unlock: unlock2 } = (0, import_private_apis2.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
    "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
    "@wordpress/ui"
  );

  // packages/ui/build-module/utils/theme-provider.mjs
  function getThemeProvider() {
    const themePackage = theme;
    if (themePackage.ThemeProvider) {
      return themePackage.ThemeProvider;
    }
    if (!themePackage.privateApis) {
      throw new Error(
        "@wordpress/ui: @wordpress/theme must expose `ThemeProvider` or `privateApis.ThemeProvider`."
      );
    }
    return unlock2(
      themePackage.privateApis
    ).ThemeProvider;
  }
  var ThemeProvider = getThemeProvider();

  // packages/ui/build-module/stack/stack.mjs
  var import_element28 = __toESM(require_element(), 1);
  var STYLE_HASH_ATTRIBUTE9 = "data-wp-hash";
  function getRuntime9() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument9(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash9(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE9}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE9) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle9(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime9();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash9(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE9, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument9(targetDocument) {
    const runtime = getRuntime9();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle9(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle9(hash, css) {
    const runtime = getRuntime9();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle9(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle9("32aba35fe1", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._19ce0419607e1896__stack{display:flex}}}");
  }
  var style_default9 = { "stack": "_19ce0419607e1896__stack" };
  var gapTokens = {
    xs: "var(--wpds-dimension-gap-xs, 4px)",
    sm: "var(--wpds-dimension-gap-sm, 8px)",
    md: "var(--wpds-dimension-gap-md, 12px)",
    lg: "var(--wpds-dimension-gap-lg, 16px)",
    xl: "var(--wpds-dimension-gap-xl, 24px)",
    "2xl": "var(--wpds-dimension-gap-2xl, 32px)",
    "3xl": "var(--wpds-dimension-gap-3xl, 40px)"
  };
  var Stack = (0, import_element28.forwardRef)(function Stack2({ direction, gap, align, justify, wrap, render: render4, ...props }, ref) {
    const style = {
      gap: gap && gapTokens[gap],
      alignItems: align,
      justifyContent: justify,
      flexDirection: direction,
      flexWrap: wrap
    };
    const element = useRender({
      render: render4,
      ref,
      props: mergeProps(props, { style, className: style_default9.stack })
    });
    return element;
  });

  // packages/ui/build-module/tooltip/index.mjs
  var tooltip_exports = {};
  __export(tooltip_exports, {
    Popup: () => Popup,
    Portal: () => Portal,
    Positioner: () => Positioner,
    Provider: () => Provider,
    Root: () => Root4,
    Trigger: () => Trigger2
  });

  // packages/ui/build-module/tooltip/popup.mjs
  var import_element31 = __toESM(require_element(), 1);

  // packages/ui/build-module/tooltip/portal.mjs
  var import_element29 = __toESM(require_element(), 1);

  // packages/ui/build-module/utils/wp-compat-overlay-slot.mjs
  var STYLE_HASH_ATTRIBUTE10 = "data-wp-hash";
  function getRuntime10() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument10(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash10(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE10}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE10) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle10(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime10();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash10(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE10, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument10(targetDocument) {
    const runtime = getRuntime10();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle10(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle10(hash, css) {
    const runtime = getRuntime10();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle10(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle10("be37f31c1e", "._11fc52b637ff8a7e__slot{inset:0;isolation:isolate;pointer-events:none;position:fixed;z-index:1000000003}@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._11fc52b637ff8a7e__slot>*{pointer-events:auto}}}");
  }
  var wp_compat_overlay_slot_default = { "slot": "_11fc52b637ff8a7e__slot" };
  var WP_COMPAT_OVERLAY_SLOT_ATTRIBUTE = "data-wp-compat-overlay-slot";
  function resolveOwnerDocument() {
    return typeof document === "undefined" ? null : document;
  }
  function isInWordPressEnvironment() {
    let topWp;
    try {
      topWp = window.top?.wp;
    } catch {
    }
    const wp = topWp ?? window.wp;
    return typeof wp?.components === "object" && wp.components !== null;
  }
  var cachedSlot = null;
  function ensureSlotIsAccessible(element) {
    element.setAttribute("aria-hidden", "false");
    return element;
  }
  function createSlot(ownerDocument2) {
    const element = ownerDocument2.createElement("div");
    element.setAttribute(WP_COMPAT_OVERLAY_SLOT_ATTRIBUTE, "");
    if (wp_compat_overlay_slot_default.slot) {
      element.classList.add(wp_compat_overlay_slot_default.slot);
    }
    ownerDocument2.body.appendChild(element);
    return element;
  }
  function getWpCompatOverlaySlot() {
    if (typeof window === "undefined") {
      return void 0;
    }
    if (!isInWordPressEnvironment() && window.__wpUiCompatOverlaySlotEnabled !== true) {
      return void 0;
    }
    const ownerDocument2 = resolveOwnerDocument();
    if (!ownerDocument2 || !ownerDocument2.body) {
      return void 0;
    }
    if (cachedSlot && cachedSlot.ownerDocument === ownerDocument2 && cachedSlot.isConnected) {
      return ensureSlotIsAccessible(cachedSlot);
    }
    const existing = ownerDocument2.querySelector(
      `[${WP_COMPAT_OVERLAY_SLOT_ATTRIBUTE}]`
    );
    if (existing instanceof HTMLDivElement) {
      cachedSlot = ensureSlotIsAccessible(existing);
      return cachedSlot;
    }
    if (cachedSlot?.isConnected) {
      cachedSlot.remove();
    }
    cachedSlot = ensureSlotIsAccessible(createSlot(ownerDocument2));
    return cachedSlot;
  }

  // packages/ui/build-module/tooltip/portal.mjs
  var import_jsx_runtime89 = __toESM(require_jsx_runtime(), 1);
  var Portal = (0, import_element29.forwardRef)(
    function TooltipPortal3({ container, ...restProps }, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(
        index_parts_exports2.Portal,
        {
          container: container ?? getWpCompatOverlaySlot(),
          ...restProps,
          ref
        }
      );
    }
  );

  // packages/ui/build-module/tooltip/positioner.mjs
  var import_element30 = __toESM(require_element(), 1);
  var import_jsx_runtime90 = __toESM(require_jsx_runtime(), 1);
  var STYLE_HASH_ATTRIBUTE11 = "data-wp-hash";
  function getRuntime11() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument11(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash11(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE11}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE11) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle11(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime11();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash11(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE11, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument11(targetDocument) {
    const runtime = getRuntime11();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle11(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle11(hash, css) {
    const runtime = getRuntime11();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle11(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle11("10f3806643", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._336cd3e4e743482f__box-sizing{box-sizing:border-box;*,:after,:before{box-sizing:inherit}}}}");
  }
  var resets_default2 = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
  if (typeof process === "undefined" || true) {
    registerStyle11("19fcc06039", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._480b748dd3510e64__positioner{z-index:var(--wp-ui-tooltip-z-index,initial)}._50096b232db7709d__popup{--_wp-ui-elevation-sm:0 1px 2px rgba(0,0,0,.05),0 2px 3px rgba(0,0,0,.04),0 6px 6px rgba(0,0,0,.03),0 8px 8px rgba(0,0,0,.02);background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border-radius:var(--wpds-border-radius-md,4px);box-shadow:var(--_wp-ui-elevation-sm);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-sm,12px);line-height:1.4;padding:var(--wpds-dimension-padding-xs,4px) var(--wpds-dimension-padding-sm,8px);@media (forced-colors:active){border-bottom-color:CanvasText;border-bottom-style:solid;border-bottom-width:1px;border-left-color:CanvasText;border-left-style:solid;border-left-width:1px;border-right-color:CanvasText;border-right-style:solid;border-right-width:1px;border-top-color:CanvasText;border-top-style:solid;border-top-width:1px}}}}');
  }
  var style_default10 = { "positioner": "_480b748dd3510e64__positioner", "popup": "_50096b232db7709d__popup" };
  var Positioner = (0, import_element30.forwardRef)(
    function TooltipPositioner3({ align = "center", className, side = "top", sideOffset = 4, ...props }, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(
        index_parts_exports2.Positioner,
        {
          ref,
          align,
          side,
          sideOffset,
          ...props,
          className: clsx_default(
            resets_default2["box-sizing"],
            style_default10.positioner,
            className
          )
        }
      );
    }
  );

  // packages/ui/build-module/tooltip/popup.mjs
  var import_jsx_runtime91 = __toESM(require_jsx_runtime(), 1);
  var STYLE_HASH_ATTRIBUTE12 = "data-wp-hash";
  function getRuntime12() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument12(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash12(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE12}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE12) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle12(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime12();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash12(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE12, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument12(targetDocument) {
    const runtime = getRuntime12();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle12(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle12(hash, css) {
    const runtime = getRuntime12();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle12(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle12("19fcc06039", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._480b748dd3510e64__positioner{z-index:var(--wp-ui-tooltip-z-index,initial)}._50096b232db7709d__popup{--_wp-ui-elevation-sm:0 1px 2px rgba(0,0,0,.05),0 2px 3px rgba(0,0,0,.04),0 6px 6px rgba(0,0,0,.03),0 8px 8px rgba(0,0,0,.02);background-color:var(--wpds-color-background-surface-neutral-strong,#fff);border-radius:var(--wpds-border-radius-md,4px);box-shadow:var(--_wp-ui-elevation-sm);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);font-size:var(--wpds-typography-font-size-sm,12px);line-height:1.4;padding:var(--wpds-dimension-padding-xs,4px) var(--wpds-dimension-padding-sm,8px);@media (forced-colors:active){border-bottom-color:CanvasText;border-bottom-style:solid;border-bottom-width:1px;border-left-color:CanvasText;border-left-style:solid;border-left-width:1px;border-right-color:CanvasText;border-right-style:solid;border-right-width:1px;border-top-color:CanvasText;border-top-style:solid;border-top-width:1px}}}}');
  }
  var style_default11 = { "positioner": "_480b748dd3510e64__positioner", "popup": "_50096b232db7709d__popup" };
  var POPUP_COLOR = { background: "#1e1e1e" };
  var Popup = (0, import_element31.forwardRef)(function TooltipPopup3({ portal, positioner, children, className, ...props }, ref) {
    const popupContent = /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(ThemeProvider, { color: POPUP_COLOR, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      index_parts_exports2.Popup,
      {
        ref,
        className: clsx_default(style_default11.popup, className),
        ...props,
        children
      }
    ) });
    const positionedPopup = renderSlotWithChildren(
      positioner,
      /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Positioner, {}),
      popupContent
    );
    return renderSlotWithChildren(portal, /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Portal, {}), positionedPopup);
  });

  // packages/ui/build-module/tooltip/trigger.mjs
  var import_element32 = __toESM(require_element(), 1);
  var import_jsx_runtime92 = __toESM(require_jsx_runtime(), 1);
  var Trigger2 = (0, import_element32.forwardRef)(
    function TooltipTrigger3(props, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(index_parts_exports2.Trigger, { ref, ...props });
    }
  );

  // packages/ui/build-module/tooltip/root.mjs
  var import_jsx_runtime93 = __toESM(require_jsx_runtime(), 1);
  function Root4(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(index_parts_exports2.Root, { ...props });
  }

  // packages/ui/build-module/tooltip/provider.mjs
  var import_jsx_runtime94 = __toESM(require_jsx_runtime(), 1);
  function Provider({ ...props }) {
    return /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(index_parts_exports2.Provider, { ...props });
  }

  // packages/ui/build-module/visually-hidden/visually-hidden.mjs
  var import_element33 = __toESM(require_element(), 1);
  var STYLE_HASH_ATTRIBUTE13 = "data-wp-hash";
  function getRuntime13() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument13(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash13(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE13}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE13) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle13(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime13();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash13(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE13, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument13(targetDocument) {
    const runtime = getRuntime13();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle13(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle13(hash, css) {
    const runtime = getRuntime13();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle13(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle13("fa606a57ae", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{.f37b9e2e191ebd66__visually-hidden{word-wrap:normal;border:0;clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-break:normal}}}");
  }
  var style_default12 = { "visually-hidden": "f37b9e2e191ebd66__visually-hidden" };
  var VisuallyHidden = (0, import_element33.forwardRef)(
    function VisuallyHidden2({ render: render4, ...restProps }, ref) {
      const element = useRender({
        render: render4,
        ref,
        props: mergeProps(
          { className: style_default12["visually-hidden"] },
          restProps,
          {
            // @ts-expect-error Arbitrary data-* attributes aren't indexable on the typed div props. Kept hardcoded so consumers can't change or remove it.
            "data-visually-hidden": ""
          }
        )
      });
      return element;
    }
  );

  // packages/ui/build-module/skeleton/skeleton.mjs
  var import_element34 = __toESM(require_element(), 1);
  var STYLE_HASH_ATTRIBUTE14 = "data-wp-hash";
  function getRuntime14() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument14(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash14(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE14}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE14) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle14(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime14();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash14(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE14, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument14(targetDocument) {
    const runtime = getRuntime14();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle14(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle14(hash, css) {
    const runtime = getRuntime14();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle14(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle14("10f3806643", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._336cd3e4e743482f__box-sizing{box-sizing:border-box;*,:after,:before{box-sizing:inherit}}}}");
  }
  var resets_default3 = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
  if (typeof process === "undefined" || true) {
    registerStyle14("ed2c39ec90", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{.b20cc1690085c2f0__skeleton{background-color:var(--wpds-color-background-surface-neutral-weak,#f4f4f4);display:block;@media (forced-colors:active){border:var(--wpds-border-width-xs,1px) solid CanvasText}}._9b143194fdb45f93__pulse{@media not (prefers-reduced-motion){animation:e2b9fe0690281bc8__skeleton-pulse 1.5s ease-in-out infinite}}@keyframes e2b9fe0690281bc8__skeleton-pulse{0%,to{opacity:1}50%{opacity:.4}}}}");
  }
  var style_default13 = { "skeleton": "b20cc1690085c2f0__skeleton", "pulse": "_9b143194fdb45f93__pulse", "skeleton-pulse": "e2b9fe0690281bc8__skeleton-pulse" };
  var Skeleton = (0, import_element34.forwardRef)(
    function Skeleton2({ render: render4, ...props }, ref) {
      return useRender({
        render: render4,
        ref,
        props: mergeProps(
          {
            className: clsx_default(
              style_default13.skeleton,
              style_default13.pulse,
              resets_default3["box-sizing"]
            ),
            // Decorative by default; consumers mark the loading
            // region with aria-busy / role="status".
            "aria-hidden": true
          },
          props
        )
      });
    }
  );

  // packages/admin-ui/build-module/navigable-region/index.mjs
  var import_element35 = __toESM(require_element(), 1);
  var import_jsx_runtime95 = __toESM(require_jsx_runtime(), 1);
  var NavigableRegion = (0, import_element35.forwardRef)(
    ({ children, className, ariaLabel, as: Tag = "div", ...props }, ref) => {
      return /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(
        Tag,
        {
          ref,
          className: clsx_default("admin-ui-navigable-region", className),
          "aria-label": ariaLabel,
          role: "region",
          tabIndex: "-1",
          ...props,
          children
        }
      );
    }
  );
  NavigableRegion.displayName = "NavigableRegion";
  var navigable_region_default = NavigableRegion;

  // packages/admin-ui/build-module/page/sidebar-toggle-slot.mjs
  var import_components = __toESM(require_components(), 1);
  var { Fill: SidebarToggleFill, Slot: SidebarToggleSlot } = (0, import_components.createSlotFill)("SidebarToggle");

  // packages/admin-ui/build-module/page/header.mjs
  var import_jsx_runtime96 = __toESM(require_jsx_runtime(), 1);
  var STYLE_HASH_ATTRIBUTE15 = "data-wp-hash";
  function getRuntime15() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument15(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash15(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE15}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE15) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle15(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime15();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash15(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE15, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument15(targetDocument) {
    const runtime = getRuntime15();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle15(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle15(hash, css) {
    const runtime = getRuntime15();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle15(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle15("ddd9aab364", "._956b6df0898efed0__page{text-wrap:pretty;background-color:var(--wpds-color-background-surface-neutral,#fcfcfc);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);display:flex;flex-flow:column;height:100%;position:relative;z-index:1}._0625b55e82a0d93d__header{background:var(--wpds-color-background-surface-neutral-strong,#fff);border-block-end:var(--wpds-border-width-xs,1px) solid var(--wpds-color-stroke-surface-neutral-weak,#f0f0f0);inset-block-start:0;padding:var(--wpds-dimension-padding-lg,16px) var(--wpds-dimension-padding-2xl,24px);position:sticky;z-index:1}.a43c44d5ae28b2e8__header-content{min-height:var(--wpds-dimension-size-md,32px)}.b7cb5b9daf3a3b25__header-actions{flex-shrink:0}._8113be94e7caf73c__header-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}._9a776c7f70996f61__header-visual{display:grid;flex-shrink:0;grid-template-columns:1fr;grid-template-rows:1fr;height:var(--wpds-dimension-size-sm,24px);width:var(--wpds-dimension-size-sm,24px);>*{grid-column:1/-1;grid-row:1/-1;max-height:100%;max-width:100%}}.d5e0920cd15d35bc__sidebar-toggle-slot:empty{display:none}._60fea2f6bf5319cd__header-subtitle{color:var(--wpds-color-foreground-content-neutral-weak,#707070);padding-block-end:var(--wpds-dimension-padding-xs,4px)}.be5e57d029ec4036__content{display:flex;flex-direction:column;flex-grow:1;overflow:auto;&._128806d0b26e3a50__has-padding{padding:var(--wpds-dimension-padding-lg,16px) var(--wpds-dimension-padding-2xl,24px)}}");
  }
  var style_default14 = { "page": "_956b6df0898efed0__page", "header": "_0625b55e82a0d93d__header", "header-content": "a43c44d5ae28b2e8__header-content", "header-actions": "b7cb5b9daf3a3b25__header-actions", "header-title": "_8113be94e7caf73c__header-title", "header-visual": "_9a776c7f70996f61__header-visual", "sidebar-toggle-slot": "d5e0920cd15d35bc__sidebar-toggle-slot", "header-subtitle": "_60fea2f6bf5319cd__header-subtitle", "content": "be5e57d029ec4036__content", "has-padding": "_128806d0b26e3a50__has-padding" };
  function Header3({
    headingLevel = 1,
    breadcrumbs,
    badges,
    visual,
    title,
    subTitle,
    actions,
    showSidebarToggle = true
  }) {
    const HeadingTag = `h${headingLevel}`;
    return /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(Stack, { direction: "column", className: style_default14.header, children: [
      /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(
        Stack,
        {
          className: style_default14["header-content"],
          direction: "row",
          gap: "sm",
          justify: "space-between",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(Stack, { direction: "row", gap: "sm", align: "center", justify: "start", children: [
              showSidebarToggle && /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(
                SidebarToggleSlot,
                {
                  bubblesVirtually: true,
                  className: style_default14["sidebar-toggle-slot"]
                }
              ),
              visual && /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(
                "div",
                {
                  className: style_default14["header-visual"],
                  "aria-hidden": "true",
                  children: visual
                }
              ),
              title && /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(
                Text,
                {
                  className: style_default14["header-title"],
                  render: /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(HeadingTag, {}),
                  variant: "heading-lg",
                  children: title
                }
              ),
              breadcrumbs,
              badges
            ] }),
            actions && /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(
              Stack,
              {
                align: "center",
                className: style_default14["header-actions"],
                direction: "row",
                gap: "sm",
                children: actions
              }
            )
          ]
        }
      ),
      subTitle && /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(
        Text,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime96.jsx)("p", {}),
          variant: "body-md",
          className: style_default14["header-subtitle"],
          children: subTitle
        }
      )
    ] });
  }

  // packages/admin-ui/build-module/page/index.mjs
  var import_jsx_runtime97 = __toESM(require_jsx_runtime(), 1);
  var STYLE_HASH_ATTRIBUTE16 = "data-wp-hash";
  function getRuntime16() {
    const globalScope = globalThis;
    if (globalScope.__wpStyleRuntime) {
      return globalScope.__wpStyleRuntime;
    }
    globalScope.__wpStyleRuntime = {
      documents: /* @__PURE__ */ new Map(),
      styles: /* @__PURE__ */ new Map(),
      injectedStyles: /* @__PURE__ */ new WeakMap()
    };
    if (typeof document !== "undefined") {
      registerDocument16(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash16(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE16}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE16) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle16(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime16();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash16(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE16, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument16(targetDocument) {
    const runtime = getRuntime16();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle16(targetDocument, hash, css);
    }
    return () => {
      const count = runtime.documents.get(targetDocument);
      if (count === void 0) {
        return;
      }
      if (count <= 1) {
        runtime.documents.delete(targetDocument);
        return;
      }
      runtime.documents.set(targetDocument, count - 1);
    };
  }
  function registerStyle16(hash, css) {
    const runtime = getRuntime16();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle16(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle16("ddd9aab364", "._956b6df0898efed0__page{text-wrap:pretty;background-color:var(--wpds-color-background-surface-neutral,#fcfcfc);color:var(--wpds-color-foreground-content-neutral,#1e1e1e);display:flex;flex-flow:column;height:100%;position:relative;z-index:1}._0625b55e82a0d93d__header{background:var(--wpds-color-background-surface-neutral-strong,#fff);border-block-end:var(--wpds-border-width-xs,1px) solid var(--wpds-color-stroke-surface-neutral-weak,#f0f0f0);inset-block-start:0;padding:var(--wpds-dimension-padding-lg,16px) var(--wpds-dimension-padding-2xl,24px);position:sticky;z-index:1}.a43c44d5ae28b2e8__header-content{min-height:var(--wpds-dimension-size-md,32px)}.b7cb5b9daf3a3b25__header-actions{flex-shrink:0}._8113be94e7caf73c__header-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}._9a776c7f70996f61__header-visual{display:grid;flex-shrink:0;grid-template-columns:1fr;grid-template-rows:1fr;height:var(--wpds-dimension-size-sm,24px);width:var(--wpds-dimension-size-sm,24px);>*{grid-column:1/-1;grid-row:1/-1;max-height:100%;max-width:100%}}.d5e0920cd15d35bc__sidebar-toggle-slot:empty{display:none}._60fea2f6bf5319cd__header-subtitle{color:var(--wpds-color-foreground-content-neutral-weak,#707070);padding-block-end:var(--wpds-dimension-padding-xs,4px)}.be5e57d029ec4036__content{display:flex;flex-direction:column;flex-grow:1;overflow:auto;&._128806d0b26e3a50__has-padding{padding:var(--wpds-dimension-padding-lg,16px) var(--wpds-dimension-padding-2xl,24px)}}");
  }
  var style_default15 = { "page": "_956b6df0898efed0__page", "header": "_0625b55e82a0d93d__header", "header-content": "a43c44d5ae28b2e8__header-content", "header-actions": "b7cb5b9daf3a3b25__header-actions", "header-title": "_8113be94e7caf73c__header-title", "header-visual": "_9a776c7f70996f61__header-visual", "sidebar-toggle-slot": "d5e0920cd15d35bc__sidebar-toggle-slot", "header-subtitle": "_60fea2f6bf5319cd__header-subtitle", "content": "be5e57d029ec4036__content", "has-padding": "_128806d0b26e3a50__has-padding" };
  function Page({
    headingLevel,
    breadcrumbs,
    badges,
    visual,
    title,
    subTitle,
    children,
    className,
    actions,
    ariaLabel,
    hasPadding = false,
    showSidebarToggle = true
  }) {
    const classes = clsx_default(style_default15.page, className);
    const effectiveAriaLabel = ariaLabel ?? (typeof title === "string" ? title : "");
    return /* @__PURE__ */ (0, import_jsx_runtime97.jsxs)(navigable_region_default, { className: classes, ariaLabel: effectiveAriaLabel, children: [
      (title || breadcrumbs || badges || actions || visual) && /* @__PURE__ */ (0, import_jsx_runtime97.jsx)(
        Header3,
        {
          headingLevel,
          breadcrumbs,
          badges,
          visual,
          title,
          subTitle,
          actions,
          showSidebarToggle
        }
      ),
      hasPadding ? /* @__PURE__ */ (0, import_jsx_runtime97.jsx)(
        "div",
        {
          className: clsx_default(
            style_default15.content,
            style_default15["has-padding"]
          ),
          children
        }
      ) : children
    ] });
  }
  Page.SidebarToggleFill = SidebarToggleFill;
  var page_default2 = Page;

  // packages/admin-ui/build-module/admin-theme-colors/index.mjs
  var DEFAULT_THEME_COLORS = {
    primary: "#3858e9",
    background: "#222524"
  };
  var ADMIN_THEME_COLORS = /* @__PURE__ */ new Map([
    ["modern", DEFAULT_THEME_COLORS],
    ["fresh", { primary: "#3858e9", background: "#25292b" }],
    ["midnight", { primary: "#cf4339", background: "#3d4042" }],
    ["coffee", { primary: "#916745", background: "#5b534d" }],
    ["ocean", { primary: "#567958", background: "#5f787f" }],
    ["blue", { primary: "#437aa8", background: "#3876a8" }],
    ["ectoplasm", { primary: "#646c3e", background: "#4f386e" }],
    ["sunrise", { primary: "#ad631e", background: "#cc4541" }],
    ["light", { primary: "#007cba", background: "#eaeeed" }]
  ]);
  function getAdminThemeColors() {
    const scheme = document.body.className.match(/admin-color-([\w-]+)/)?.[1] ?? "modern";
    return ADMIN_THEME_COLORS.get(scheme) ?? DEFAULT_THEME_COLORS;
  }

  // packages/edit-site/build-module/components/layout/index.mjs
  var import_components6 = __toESM(require_components(), 1);
  var import_compose2 = __toESM(require_compose(), 1);
  var import_dom23 = __toESM(require_dom(), 1);
  var import_i18n7 = __toESM(require_i18n(), 1);
  var import_element44 = __toESM(require_element(), 1);
  var import_editor6 = __toESM(require_editor(), 1);
  var import_router6 = __toESM(require_router(), 1);
  var import_theme = __toESM(require_theme(), 1);
  var import_plugins2 = __toESM(require_plugins(), 1);
  var import_notices = __toESM(require_notices(), 1);
  var import_data12 = __toESM(require_data(), 1);
  var import_preferences3 = __toESM(require_preferences(), 1);

  // packages/edit-site/build-module/components/site-hub/index.mjs
  var import_data4 = __toESM(require_data(), 1);
  var import_components2 = __toESM(require_components(), 1);
  var import_i18n2 = __toESM(require_i18n(), 1);
  var import_core_data3 = __toESM(require_core_data(), 1);
  var import_element37 = __toESM(require_element(), 1);
  var import_router = __toESM(require_router(), 1);

  // packages/edit-site/build-module/components/sidebar/index.mjs
  var import_element36 = __toESM(require_element(), 1);
  var import_dom22 = __toESM(require_dom(), 1);
  var import_jsx_runtime98 = __toESM(require_jsx_runtime(), 1);
  var SidebarNavigationContext = (0, import_element36.createContext)(() => {
  });
  SidebarNavigationContext.displayName = "SidebarNavigationContext";
  function focusSidebarElement(el, direction, focusSelector) {
    let elementToFocus;
    if (direction === "back" && focusSelector) {
      elementToFocus = el.querySelector(focusSelector);
    }
    if (direction !== null && !elementToFocus) {
      const [firstTabbable] = import_dom22.focus.tabbable.find(el);
      elementToFocus = firstTabbable ?? el;
    }
    elementToFocus?.focus();
  }
  function createNavState() {
    let state = {
      direction: null,
      focusSelector: null
    };
    return {
      get() {
        return state;
      },
      navigate(direction, focusSelector = null) {
        state = {
          direction,
          focusSelector: direction === "forward" && focusSelector ? focusSelector : state.focusSelector
        };
      }
    };
  }
  function SidebarContentWrapper({ children, shouldAnimate }) {
    const navState = (0, import_element36.useContext)(SidebarNavigationContext);
    const wrapperRef = (0, import_element36.useRef)();
    const [navAnimation, setNavAnimation] = (0, import_element36.useState)(null);
    (0, import_element36.useLayoutEffect)(() => {
      const { direction, focusSelector } = navState.get();
      focusSidebarElement(wrapperRef.current, direction, focusSelector);
      setNavAnimation(direction);
    }, [navState]);
    const wrapperCls = clsx_default(
      "edit-site-sidebar__screen-wrapper",
      /*
       * Some panes do not have sub-panes and therefore
       * should not animate when clicked on.
       */
      shouldAnimate ? {
        "slide-from-left": navAnimation === "back",
        "slide-from-right": navAnimation === "forward"
      } : {}
    );
    return /* @__PURE__ */ (0, import_jsx_runtime98.jsx)("div", { ref: wrapperRef, className: wrapperCls, children });
  }
  function SidebarNavigationProvider({ children }) {
    const [navState] = (0, import_element36.useState)(createNavState);
    return /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(SidebarNavigationContext.Provider, { value: navState, children });
  }
  function SidebarContent({ routeKey, shouldAnimate, children }) {
    return /* @__PURE__ */ (0, import_jsx_runtime98.jsx)("div", { className: "edit-site-sidebar__content", children: /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(
      SidebarContentWrapper,
      {
        shouldAnimate,
        children
      },
      routeKey
    ) });
  }

  // packages/edit-site/build-module/components/site-hub/index.mjs
  var import_jsx_runtime99 = __toESM(require_jsx_runtime(), 1);
  var { useLocation, useHistory } = unlock(import_router.privateApis);
  var SiteHubMobile = (0, import_element37.memo)(
    (0, import_element37.forwardRef)((props, ref) => {
      const { path } = useLocation();
      const history = useHistory();
      const { navigate } = (0, import_element37.useContext)(SidebarNavigationContext);
      const {
        dashboardLink,
        isBlockTheme,
        isClassicThemeWithStyleBookSupport: isClassicThemeWithStyleBookSupport2
      } = (0, import_data4.useSelect)((select4) => {
        const { getSettings: getSettings7 } = unlock(select4(store));
        const { getCurrentTheme } = select4(import_core_data3.store);
        const currentTheme = getCurrentTheme();
        const settings2 = getSettings7();
        const supportsEditorStyles = currentTheme?.theme_supports["editor-styles"];
        const hasThemeJson = settings2.supportsLayout;
        return {
          dashboardLink: settings2.__experimentalDashboardLink,
          isBlockTheme: currentTheme?.is_block_theme,
          isClassicThemeWithStyleBookSupport: !currentTheme?.is_block_theme && (supportsEditorStyles || hasThemeJson)
        };
      }, []);
      let backPath;
      if (path !== "/") {
        if (isBlockTheme || isClassicThemeWithStyleBookSupport2) {
          backPath = "/";
        } else if (path !== "/pattern") {
          backPath = "/pattern";
        }
      }
      const backButtonProps = {
        href: !!backPath ? void 0 : dashboardLink,
        label: !!backPath ? (0, import_i18n2.__)("Go to Site Editor") : (0, import_i18n2.__)("Go to the Dashboard"),
        onClick: !!backPath ? () => {
          history.navigate(backPath);
          navigate("back");
        } : void 0
      };
      return /* @__PURE__ */ (0, import_jsx_runtime99.jsx)("div", { className: "edit-site-site-hub", children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(
        import_components2.Button,
        {
          size: "compact",
          ref,
          className: "edit-site-site-hub__back-button",
          icon: (0, import_i18n2.isRTL)() ? chevron_right_default : chevron_left_default,
          ...backButtonProps
        }
      ) });
    })
  );

  // packages/edit-site/build-module/components/resizable-frame/index.mjs
  var import_element38 = __toESM(require_element(), 1);
  var import_components3 = __toESM(require_components(), 1);
  var import_compose = __toESM(require_compose(), 1);
  var import_i18n3 = __toESM(require_i18n(), 1);
  var import_router2 = __toESM(require_router(), 1);
  var import_data5 = __toESM(require_data(), 1);
  var import_core_data4 = __toESM(require_core_data(), 1);
  var import_url = __toESM(require_url(), 1);
  var import_jsx_runtime100 = __toESM(require_jsx_runtime(), 1);
  var { useLocation: useLocation2, useHistory: useHistory2 } = unlock(import_router2.privateApis);
  var HANDLE_STYLES_OVERRIDE = {
    position: void 0,
    userSelect: void 0,
    cursor: void 0,
    width: void 0,
    height: void 0,
    top: void 0,
    right: void 0,
    bottom: void 0,
    left: void 0
  };
  var FRAME_MIN_WIDTH = 320;
  var FRAME_REFERENCE_WIDTH = 1300;
  var FRAME_TARGET_ASPECT_RATIO = 9 / 19.5;
  var SNAP_TO_EDIT_CANVAS_MODE_THRESHOLD = 200;
  var INITIAL_FRAME_SIZE = { width: "100%", height: "100%" };
  function calculateNewHeight(width, initialAspectRatio) {
    const lerp = (a2, b2, amount) => {
      return a2 + (b2 - a2) * amount;
    };
    const lerpFactor = 1 - Math.max(
      0,
      Math.min(
        1,
        (width - FRAME_MIN_WIDTH) / (FRAME_REFERENCE_WIDTH - FRAME_MIN_WIDTH)
      )
    );
    const intermediateAspectRatio = lerp(
      initialAspectRatio,
      FRAME_TARGET_ASPECT_RATIO,
      lerpFactor
    );
    return width / intermediateAspectRatio;
  }
  function ResizableFrame({
    isFullWidth,
    isOversized,
    setIsOversized,
    isReady,
    children,
    /** The default (unresized) width/height of the frame, based on the space available in the viewport. */
    defaultSize,
    innerContentStyle
  }) {
    const history = useHistory2();
    const { path, query } = useLocation2();
    const { canvas = "view" } = query;
    const disableMotion = (0, import_compose.useReducedMotion)();
    const [frameSize, setFrameSize] = (0, import_element38.useState)(INITIAL_FRAME_SIZE);
    const [startingWidth, setStartingWidth] = (0, import_element38.useState)();
    const [isResizing, setIsResizing] = (0, import_element38.useState)(false);
    const [shouldShowHandle, setShouldShowHandle] = (0, import_element38.useState)(false);
    const [resizeRatio, setResizeRatio] = (0, import_element38.useState)(1);
    const FRAME_TRANSITION = { type: "tween", duration: isResizing ? 0 : 0.5 };
    const frameRef = (0, import_element38.useRef)(null);
    const resizableHandleHelpId = (0, import_compose.useInstanceId)(
      ResizableFrame,
      "edit-site-resizable-frame-handle-help"
    );
    const defaultAspectRatio = defaultSize.width / defaultSize.height;
    const isBlockTheme = (0, import_data5.useSelect)((select4) => {
      const { getCurrentTheme } = select4(import_core_data4.store);
      return getCurrentTheme()?.is_block_theme;
    }, []);
    const handleResizeStart = (_event, _direction, ref) => {
      setStartingWidth(ref.offsetWidth);
      setIsResizing(true);
    };
    const handleResize = (_event, _direction, _ref, delta) => {
      const normalizedDelta = delta.width / resizeRatio;
      const deltaAbs = Math.abs(normalizedDelta);
      const maxDoubledDelta = delta.width < 0 ? deltaAbs : (defaultSize.width - startingWidth) / 2;
      const deltaToDouble = Math.min(deltaAbs, maxDoubledDelta);
      const doubleSegment = deltaAbs === 0 ? 0 : deltaToDouble / deltaAbs;
      const singleSegment = 1 - doubleSegment;
      setResizeRatio(singleSegment + doubleSegment * 2);
      const updatedWidth = startingWidth + delta.width;
      setIsOversized(updatedWidth > defaultSize.width);
      setFrameSize({
        height: isOversized ? "100%" : calculateNewHeight(updatedWidth, defaultAspectRatio)
      });
    };
    const handleResizeStop = (_event, _direction, ref) => {
      setIsResizing(false);
      if (!isOversized) {
        return;
      }
      setIsOversized(false);
      const remainingWidth = ref.ownerDocument.documentElement.offsetWidth - ref.offsetWidth;
      if (remainingWidth > SNAP_TO_EDIT_CANVAS_MODE_THRESHOLD || !isBlockTheme) {
        setFrameSize(INITIAL_FRAME_SIZE);
      } else {
        history.navigate(
          (0, import_url.addQueryArgs)(path, {
            canvas: "edit"
          }),
          {
            transition: "canvas-mode-edit-transition"
          }
        );
      }
    };
    const handleResizableHandleKeyDown = (event) => {
      if (!["ArrowLeft", "ArrowRight"].includes(event.key)) {
        return;
      }
      event.preventDefault();
      const step = 20 * (event.shiftKey ? 5 : 1);
      const delta = step * (event.key === "ArrowLeft" ? 1 : -1) * ((0, import_i18n3.isRTL)() ? -1 : 1);
      const newWidth = Math.min(
        Math.max(
          FRAME_MIN_WIDTH,
          frameRef.current.resizable.offsetWidth + delta
        ),
        defaultSize.width
      );
      setFrameSize({
        width: newWidth,
        height: calculateNewHeight(newWidth, defaultAspectRatio)
      });
    };
    const frameAnimationVariants = {
      default: {
        flexGrow: 0,
        height: frameSize.height
      },
      fullWidth: {
        flexGrow: 1,
        height: frameSize.height
      }
    };
    const resizeHandleVariants = {
      hidden: {
        opacity: 0,
        ...(0, import_i18n3.isRTL)() ? { right: 0 } : { left: 0 }
      },
      visible: {
        opacity: 1,
        // Account for the handle's width.
        ...(0, import_i18n3.isRTL)() ? { right: -14 } : { left: -14 }
      },
      active: {
        opacity: 1,
        // Account for the handle's width.
        ...(0, import_i18n3.isRTL)() ? { right: -14 } : { left: -14 },
        scaleY: 1.3
      }
    };
    const currentResizeHandleVariant = (() => {
      if (isResizing) {
        return "active";
      }
      return shouldShowHandle ? "visible" : "hidden";
    })();
    return /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(
      import_components3.ResizableBox,
      {
        as: import_components3.__unstableMotion.div,
        ref: frameRef,
        initial: false,
        variants: frameAnimationVariants,
        animate: isFullWidth ? "fullWidth" : "default",
        onAnimationComplete: (definition) => {
          if (definition === "fullWidth") {
            setFrameSize({ width: "100%", height: "100%" });
          }
        },
        whileHover: canvas === "view" && isBlockTheme ? {
          scale: 1.005,
          transition: {
            duration: disableMotion ? 0 : 0.5,
            ease: "easeOut"
          }
        } : {},
        transition: FRAME_TRANSITION,
        size: frameSize,
        enable: {
          top: false,
          bottom: false,
          // Resizing will be disabled until the editor content is loaded.
          ...(0, import_i18n3.isRTL)() ? { right: isReady, left: false } : { left: isReady, right: false },
          topRight: false,
          bottomRight: false,
          bottomLeft: false,
          topLeft: false
        },
        resizeRatio,
        handleClasses: void 0,
        handleStyles: {
          left: HANDLE_STYLES_OVERRIDE,
          right: HANDLE_STYLES_OVERRIDE
        },
        minWidth: FRAME_MIN_WIDTH,
        maxWidth: isFullWidth ? "100%" : "150%",
        maxHeight: "100%",
        onFocus: () => setShouldShowHandle(true),
        onBlur: () => setShouldShowHandle(false),
        onMouseOver: () => setShouldShowHandle(true),
        onMouseOut: () => setShouldShowHandle(false),
        handleComponent: {
          [(0, import_i18n3.isRTL)() ? "right" : "left"]: canvas === "view" && /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(import_jsx_runtime100.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(tooltip_exports.Root, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(
                tooltip_exports.Trigger,
                {
                  render: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(
                    import_components3.__unstableMotion.button,
                    {
                      role: "separator",
                      "aria-orientation": "vertical",
                      className: clsx_default(
                        "edit-site-resizable-frame__handle",
                        { "is-resizing": isResizing }
                      ),
                      variants: resizeHandleVariants,
                      animate: currentResizeHandleVariant,
                      "aria-label": (0, import_i18n3.__)("Drag to resize"),
                      "aria-describedby": resizableHandleHelpId,
                      "aria-valuenow": frameRef.current?.resizable?.offsetWidth || void 0,
                      "aria-valuemin": FRAME_MIN_WIDTH,
                      "aria-valuemax": defaultSize.width,
                      onKeyDown: handleResizableHandleKeyDown,
                      initial: "hidden",
                      exit: "hidden",
                      whileFocus: "active",
                      whileHover: "active"
                    },
                    "handle"
                  )
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(tooltip_exports.Popup, { children: (0, import_i18n3.__)("Drag to resize") })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime100.jsx)("div", { hidden: true, id: resizableHandleHelpId, children: (0, import_i18n3.__)(
              "Use left and right arrow keys to resize the canvas. Hold shift to resize in larger increments."
            ) })
          ] })
        },
        onResizeStart: handleResizeStart,
        onResize: handleResize,
        onResizeStop: handleResizeStop,
        className: clsx_default("edit-site-resizable-frame__inner", {
          "is-resizing": isResizing
        }),
        showHandle: false,
        children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(
          "div",
          {
            className: "edit-site-resizable-frame__inner-content",
            style: innerContentStyle,
            children
          }
        )
      }
    );
  }
  var resizable_frame_default = ResizableFrame;

  // packages/edit-site/build-module/components/save-keyboard-shortcut/index.mjs
  var import_element39 = __toESM(require_element(), 1);
  var import_keyboard_shortcuts = __toESM(require_keyboard_shortcuts(), 1);
  var import_i18n4 = __toESM(require_i18n(), 1);
  var import_data6 = __toESM(require_data(), 1);
  var import_core_data5 = __toESM(require_core_data(), 1);
  var import_editor3 = __toESM(require_editor(), 1);
  var shortcutName = "core/edit-site/save";
  function SaveKeyboardShortcut() {
    const { __experimentalGetDirtyEntityRecords, isSavingEntityRecord } = (0, import_data6.useSelect)(import_core_data5.store);
    const { hasNonPostEntityChanges, isPostSavingLocked } = (0, import_data6.useSelect)(import_editor3.store);
    const { savePost } = (0, import_data6.useDispatch)(import_editor3.store);
    const { setIsSaveViewOpened: setIsSaveViewOpened2 } = (0, import_data6.useDispatch)(store);
    const { registerShortcut, unregisterShortcut } = (0, import_data6.useDispatch)(
      import_keyboard_shortcuts.store
    );
    (0, import_element39.useEffect)(() => {
      registerShortcut({
        name: shortcutName,
        category: "global",
        description: (0, import_i18n4.__)("Save your changes."),
        keyCombination: {
          modifier: "primary",
          character: "s"
        }
      });
      return () => {
        unregisterShortcut(shortcutName);
      };
    }, [registerShortcut, unregisterShortcut]);
    (0, import_keyboard_shortcuts.useShortcut)("core/edit-site/save", (event) => {
      event.preventDefault();
      const dirtyEntityRecords = __experimentalGetDirtyEntityRecords();
      const hasDirtyEntities = !!dirtyEntityRecords.length;
      const isSaving = dirtyEntityRecords.some(
        (record) => isSavingEntityRecord(record.kind, record.name, record.key)
      );
      if (!hasDirtyEntities || isSaving) {
        return;
      }
      if (hasNonPostEntityChanges()) {
        setIsSaveViewOpened2(true);
      } else if (!isPostSavingLocked()) {
        savePost();
      }
    });
    return null;
  }

  // packages/edit-site/build-module/components/layout/hooks.mjs
  var import_element40 = __toESM(require_element(), 1);
  var import_data7 = __toESM(require_data(), 1);
  var import_core_data6 = __toESM(require_core_data(), 1);
  var MAX_LOADING_TIME = 1e4;
  var MAX_PAUSE_TIME = 100;
  function waitWhileSiteEditorLoading() {
    let pauseTimeout;
    const { promise, resolve } = Promise.withResolvers();
    function finish() {
      unsubscribe();
      clearTimeout(pauseTimeout);
      clearTimeout(maxTimeout);
      resolve();
    }
    const maxTimeout = setTimeout(finish, MAX_LOADING_TIME);
    function checkResolving() {
      const isResolving = (0, import_data7.select)(import_core_data6.store).hasResolvingSelectors();
      if (isResolving) {
        clearTimeout(pauseTimeout);
        pauseTimeout = void 0;
        return;
      }
      if (!pauseTimeout) {
        pauseTimeout = setTimeout(finish, MAX_PAUSE_TIME);
      }
    }
    const unsubscribe = (0, import_data7.subscribe)(checkResolving, import_core_data6.store);
    checkResolving();
    function cancel() {
      unsubscribe();
      clearTimeout(pauseTimeout);
      clearTimeout(maxTimeout);
    }
    return [promise, cancel];
  }
  function useIsSiteEditorLoading() {
    const [loaded, setLoaded] = (0, import_element40.useState)(false);
    (0, import_element40.useEffect)(() => {
      const [promise, cancel] = waitWhileSiteEditorLoading();
      promise.then(() => setLoaded(true));
      return cancel;
    }, []);
    return !loaded;
  }

  // node_modules/@react-spring/rafz/dist/react-spring-rafz.esm.js
  var updateQueue = makeQueue();
  var raf = (fn) => schedule(fn, updateQueue);
  var writeQueue = makeQueue();
  raf.write = (fn) => schedule(fn, writeQueue);
  var onStartQueue = makeQueue();
  raf.onStart = (fn) => schedule(fn, onStartQueue);
  var onFrameQueue = makeQueue();
  raf.onFrame = (fn) => schedule(fn, onFrameQueue);
  var onFinishQueue = makeQueue();
  raf.onFinish = (fn) => schedule(fn, onFinishQueue);
  var timeouts = [];
  raf.setTimeout = (handler, ms) => {
    let time = raf.now() + ms;
    let cancel = () => {
      let i2 = timeouts.findIndex((t3) => t3.cancel == cancel);
      if (~i2) timeouts.splice(i2, 1);
      pendingCount -= ~i2 ? 1 : 0;
    };
    let timeout = {
      time,
      handler,
      cancel
    };
    timeouts.splice(findTimeout(time), 0, timeout);
    pendingCount += 1;
    start();
    return timeout;
  };
  var findTimeout = (time) => ~(~timeouts.findIndex((t3) => t3.time > time) || ~timeouts.length);
  raf.cancel = (fn) => {
    onStartQueue.delete(fn);
    onFrameQueue.delete(fn);
    onFinishQueue.delete(fn);
    updateQueue.delete(fn);
    writeQueue.delete(fn);
  };
  raf.sync = (fn) => {
    sync = true;
    raf.batchedUpdates(fn);
    sync = false;
  };
  raf.throttle = (fn) => {
    let lastArgs;
    function queuedFn() {
      try {
        fn(...lastArgs);
      } finally {
        lastArgs = null;
      }
    }
    function throttled(...args) {
      lastArgs = args;
      raf.onStart(queuedFn);
    }
    throttled.handler = fn;
    throttled.cancel = () => {
      onStartQueue.delete(queuedFn);
      lastArgs = null;
    };
    return throttled;
  };
  var nativeRaf = typeof window != "undefined" ? window.requestAnimationFrame : () => {
  };
  raf.use = (impl) => nativeRaf = impl;
  raf.now = typeof performance != "undefined" ? () => performance.now() : Date.now;
  raf.batchedUpdates = (fn) => fn();
  raf.catch = console.error;
  raf.frameLoop = "always";
  raf.advance = () => {
    if (raf.frameLoop !== "demand") {
      console.warn("Cannot call the manual advancement of rafz whilst frameLoop is not set as demand");
    } else {
      update2();
    }
  };
  var ts = -1;
  var pendingCount = 0;
  var sync = false;
  function schedule(fn, queue) {
    if (sync) {
      queue.delete(fn);
      fn(0);
    } else {
      queue.add(fn);
      start();
    }
  }
  function start() {
    if (ts < 0) {
      ts = 0;
      if (raf.frameLoop !== "demand") {
        nativeRaf(loop);
      }
    }
  }
  function stop() {
    ts = -1;
  }
  function loop() {
    if (~ts) {
      nativeRaf(loop);
      raf.batchedUpdates(update2);
    }
  }
  function update2() {
    let prevTs = ts;
    ts = raf.now();
    let count = findTimeout(ts);
    if (count) {
      eachSafely(timeouts.splice(0, count), (t3) => t3.handler());
      pendingCount -= count;
    }
    if (!pendingCount) {
      stop();
      return;
    }
    onStartQueue.flush();
    updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667);
    onFrameQueue.flush();
    writeQueue.flush();
    onFinishQueue.flush();
  }
  function makeQueue() {
    let next = /* @__PURE__ */ new Set();
    let current = next;
    return {
      add(fn) {
        pendingCount += current == next && !next.has(fn) ? 1 : 0;
        next.add(fn);
      },
      delete(fn) {
        pendingCount -= current == next && next.has(fn) ? 1 : 0;
        return next.delete(fn);
      },
      flush(arg) {
        if (current.size) {
          next = /* @__PURE__ */ new Set();
          pendingCount -= current.size;
          eachSafely(current, (fn) => fn(arg) && next.add(fn));
          pendingCount += next.size;
          current = next;
        }
      }
    };
  }
  function eachSafely(values, each2) {
    values.forEach((value) => {
      try {
        each2(value);
      } catch (e2) {
        raf.catch(e2);
      }
    });
  }

  // node_modules/@react-spring/shared/dist/react-spring-shared.esm.js
  var import_react12 = __toESM(require_react());
  function noop4() {
  }
  var defineHidden = (obj, key, value) => Object.defineProperty(obj, key, {
    value,
    writable: true,
    configurable: true
  });
  var is = {
    arr: Array.isArray,
    obj: (a2) => !!a2 && a2.constructor.name === "Object",
    fun: (a2) => typeof a2 === "function",
    str: (a2) => typeof a2 === "string",
    num: (a2) => typeof a2 === "number",
    und: (a2) => a2 === void 0
  };
  function isEqual(a2, b2) {
    if (is.arr(a2)) {
      if (!is.arr(b2) || a2.length !== b2.length) return false;
      for (let i2 = 0; i2 < a2.length; i2++) {
        if (a2[i2] !== b2[i2]) return false;
      }
      return true;
    }
    return a2 === b2;
  }
  var each = (obj, fn) => obj.forEach(fn);
  function eachProp(obj, fn, ctx9) {
    if (is.arr(obj)) {
      for (let i2 = 0; i2 < obj.length; i2++) {
        fn.call(ctx9, obj[i2], `${i2}`);
      }
      return;
    }
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        fn.call(ctx9, obj[key], key);
      }
    }
  }
  var toArray = (a2) => is.und(a2) ? [] : is.arr(a2) ? a2 : [a2];
  function flush(queue, iterator) {
    if (queue.size) {
      const items = Array.from(queue);
      queue.clear();
      each(items, iterator);
    }
  }
  var flushCalls = (queue, ...args) => flush(queue, (fn) => fn(...args));
  var isSSR = () => typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent);
  var createStringInterpolator$1;
  var to;
  var colors$1 = null;
  var skipAnimation = false;
  var willAdvance = noop4;
  var assign = (globals2) => {
    if (globals2.to) to = globals2.to;
    if (globals2.now) raf.now = globals2.now;
    if (globals2.colors !== void 0) colors$1 = globals2.colors;
    if (globals2.skipAnimation != null) skipAnimation = globals2.skipAnimation;
    if (globals2.createStringInterpolator) createStringInterpolator$1 = globals2.createStringInterpolator;
    if (globals2.requestAnimationFrame) raf.use(globals2.requestAnimationFrame);
    if (globals2.batchedUpdates) raf.batchedUpdates = globals2.batchedUpdates;
    if (globals2.willAdvance) willAdvance = globals2.willAdvance;
    if (globals2.frameLoop) raf.frameLoop = globals2.frameLoop;
  };
  var globals = /* @__PURE__ */ Object.freeze({
    __proto__: null,
    get createStringInterpolator() {
      return createStringInterpolator$1;
    },
    get to() {
      return to;
    },
    get colors() {
      return colors$1;
    },
    get skipAnimation() {
      return skipAnimation;
    },
    get willAdvance() {
      return willAdvance;
    },
    assign
  });
  var startQueue = /* @__PURE__ */ new Set();
  var currentFrame = [];
  var prevFrame = [];
  var priority = 0;
  var frameLoop = {
    get idle() {
      return !startQueue.size && !currentFrame.length;
    },
    start(animation) {
      if (priority > animation.priority) {
        startQueue.add(animation);
        raf.onStart(flushStartQueue);
      } else {
        startSafely(animation);
        raf(advance);
      }
    },
    advance,
    sort(animation) {
      if (priority) {
        raf.onFrame(() => frameLoop.sort(animation));
      } else {
        const prevIndex = currentFrame.indexOf(animation);
        if (~prevIndex) {
          currentFrame.splice(prevIndex, 1);
          startUnsafely(animation);
        }
      }
    },
    clear() {
      currentFrame = [];
      startQueue.clear();
    }
  };
  function flushStartQueue() {
    startQueue.forEach(startSafely);
    startQueue.clear();
    raf(advance);
  }
  function startSafely(animation) {
    if (!currentFrame.includes(animation)) startUnsafely(animation);
  }
  function startUnsafely(animation) {
    currentFrame.splice(findIndex(currentFrame, (other) => other.priority > animation.priority), 0, animation);
  }
  function advance(dt) {
    const nextFrame = prevFrame;
    for (let i2 = 0; i2 < currentFrame.length; i2++) {
      const animation = currentFrame[i2];
      priority = animation.priority;
      if (!animation.idle) {
        willAdvance(animation);
        animation.advance(dt);
        if (!animation.idle) {
          nextFrame.push(animation);
        }
      }
    }
    priority = 0;
    prevFrame = currentFrame;
    prevFrame.length = 0;
    currentFrame = nextFrame;
    return currentFrame.length > 0;
  }
  function findIndex(arr, test) {
    const index2 = arr.findIndex(test);
    return index2 < 0 ? arr.length : index2;
  }
  var colors = {
    transparent: 0,
    aliceblue: 4042850303,
    antiquewhite: 4209760255,
    aqua: 16777215,
    aquamarine: 2147472639,
    azure: 4043309055,
    beige: 4126530815,
    bisque: 4293182719,
    black: 255,
    blanchedalmond: 4293643775,
    blue: 65535,
    blueviolet: 2318131967,
    brown: 2771004159,
    burlywood: 3736635391,
    burntsienna: 3934150143,
    cadetblue: 1604231423,
    chartreuse: 2147418367,
    chocolate: 3530104575,
    coral: 4286533887,
    cornflowerblue: 1687547391,
    cornsilk: 4294499583,
    crimson: 3692313855,
    cyan: 16777215,
    darkblue: 35839,
    darkcyan: 9145343,
    darkgoldenrod: 3095792639,
    darkgray: 2846468607,
    darkgreen: 6553855,
    darkgrey: 2846468607,
    darkkhaki: 3182914559,
    darkmagenta: 2332068863,
    darkolivegreen: 1433087999,
    darkorange: 4287365375,
    darkorchid: 2570243327,
    darkred: 2332033279,
    darksalmon: 3918953215,
    darkseagreen: 2411499519,
    darkslateblue: 1211993087,
    darkslategray: 793726975,
    darkslategrey: 793726975,
    darkturquoise: 13554175,
    darkviolet: 2483082239,
    deeppink: 4279538687,
    deepskyblue: 12582911,
    dimgray: 1768516095,
    dimgrey: 1768516095,
    dodgerblue: 512819199,
    firebrick: 2988581631,
    floralwhite: 4294635775,
    forestgreen: 579543807,
    fuchsia: 4278255615,
    gainsboro: 3705462015,
    ghostwhite: 4177068031,
    gold: 4292280575,
    goldenrod: 3668254975,
    gray: 2155905279,
    green: 8388863,
    greenyellow: 2919182335,
    grey: 2155905279,
    honeydew: 4043305215,
    hotpink: 4285117695,
    indianred: 3445382399,
    indigo: 1258324735,
    ivory: 4294963455,
    khaki: 4041641215,
    lavender: 3873897215,
    lavenderblush: 4293981695,
    lawngreen: 2096890111,
    lemonchiffon: 4294626815,
    lightblue: 2916673279,
    lightcoral: 4034953471,
    lightcyan: 3774873599,
    lightgoldenrodyellow: 4210742015,
    lightgray: 3553874943,
    lightgreen: 2431553791,
    lightgrey: 3553874943,
    lightpink: 4290167295,
    lightsalmon: 4288707327,
    lightseagreen: 548580095,
    lightskyblue: 2278488831,
    lightslategray: 2005441023,
    lightslategrey: 2005441023,
    lightsteelblue: 2965692159,
    lightyellow: 4294959359,
    lime: 16711935,
    limegreen: 852308735,
    linen: 4210091775,
    magenta: 4278255615,
    maroon: 2147483903,
    mediumaquamarine: 1724754687,
    mediumblue: 52735,
    mediumorchid: 3126187007,
    mediumpurple: 2473647103,
    mediumseagreen: 1018393087,
    mediumslateblue: 2070474495,
    mediumspringgreen: 16423679,
    mediumturquoise: 1221709055,
    mediumvioletred: 3340076543,
    midnightblue: 421097727,
    mintcream: 4127193855,
    mistyrose: 4293190143,
    moccasin: 4293178879,
    navajowhite: 4292783615,
    navy: 33023,
    oldlace: 4260751103,
    olive: 2155872511,
    olivedrab: 1804477439,
    orange: 4289003775,
    orangered: 4282712319,
    orchid: 3664828159,
    palegoldenrod: 4008225535,
    palegreen: 2566625535,
    paleturquoise: 2951671551,
    palevioletred: 3681588223,
    papayawhip: 4293907967,
    peachpuff: 4292524543,
    peru: 3448061951,
    pink: 4290825215,
    plum: 3718307327,
    powderblue: 2967529215,
    purple: 2147516671,
    rebeccapurple: 1714657791,
    red: 4278190335,
    rosybrown: 3163525119,
    royalblue: 1097458175,
    saddlebrown: 2336560127,
    salmon: 4202722047,
    sandybrown: 4104413439,
    seagreen: 780883967,
    seashell: 4294307583,
    sienna: 2689740287,
    silver: 3233857791,
    skyblue: 2278484991,
    slateblue: 1784335871,
    slategray: 1887473919,
    slategrey: 1887473919,
    snow: 4294638335,
    springgreen: 16744447,
    steelblue: 1182971135,
    tan: 3535047935,
    teal: 8421631,
    thistle: 3636451583,
    tomato: 4284696575,
    turquoise: 1088475391,
    violet: 4001558271,
    wheat: 4125012991,
    white: 4294967295,
    whitesmoke: 4126537215,
    yellow: 4294902015,
    yellowgreen: 2597139199
  };
  var NUMBER = "[-+]?\\d*\\.?\\d+";
  var PERCENTAGE = NUMBER + "%";
  function call(...parts) {
    return "\\(\\s*(" + parts.join(")\\s*,\\s*(") + ")\\s*\\)";
  }
  var rgb = new RegExp("rgb" + call(NUMBER, NUMBER, NUMBER));
  var rgba = new RegExp("rgba" + call(NUMBER, NUMBER, NUMBER, NUMBER));
  var hsl = new RegExp("hsl" + call(NUMBER, PERCENTAGE, PERCENTAGE));
  var hsla = new RegExp("hsla" + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER));
  var hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
  var hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
  var hex6 = /^#([0-9a-fA-F]{6})$/;
  var hex8 = /^#([0-9a-fA-F]{8})$/;
  function normalizeColor(color) {
    let match3;
    if (typeof color === "number") {
      return color >>> 0 === color && color >= 0 && color <= 4294967295 ? color : null;
    }
    if (match3 = hex6.exec(color)) return parseInt(match3[1] + "ff", 16) >>> 0;
    if (colors$1 && colors$1[color] !== void 0) {
      return colors$1[color];
    }
    if (match3 = rgb.exec(color)) {
      return (parse255(match3[1]) << 24 | parse255(match3[2]) << 16 | parse255(match3[3]) << 8 | 255) >>> 0;
    }
    if (match3 = rgba.exec(color)) {
      return (parse255(match3[1]) << 24 | parse255(match3[2]) << 16 | parse255(match3[3]) << 8 | parse1(match3[4])) >>> 0;
    }
    if (match3 = hex3.exec(color)) {
      return parseInt(match3[1] + match3[1] + match3[2] + match3[2] + match3[3] + match3[3] + "ff", 16) >>> 0;
    }
    if (match3 = hex8.exec(color)) return parseInt(match3[1], 16) >>> 0;
    if (match3 = hex4.exec(color)) {
      return parseInt(match3[1] + match3[1] + match3[2] + match3[2] + match3[3] + match3[3] + match3[4] + match3[4], 16) >>> 0;
    }
    if (match3 = hsl.exec(color)) {
      return (hslToRgb(parse360(match3[1]), parsePercentage(match3[2]), parsePercentage(match3[3])) | 255) >>> 0;
    }
    if (match3 = hsla.exec(color)) {
      return (hslToRgb(parse360(match3[1]), parsePercentage(match3[2]), parsePercentage(match3[3])) | parse1(match3[4])) >>> 0;
    }
    return null;
  }
  function hue2rgb(p3, q, t3) {
    if (t3 < 0) t3 += 1;
    if (t3 > 1) t3 -= 1;
    if (t3 < 1 / 6) return p3 + (q - p3) * 6 * t3;
    if (t3 < 1 / 2) return q;
    if (t3 < 2 / 3) return p3 + (q - p3) * (2 / 3 - t3) * 6;
    return p3;
  }
  function hslToRgb(h2, s2, l2) {
    const q = l2 < 0.5 ? l2 * (1 + s2) : l2 + s2 - l2 * s2;
    const p3 = 2 * l2 - q;
    const r3 = hue2rgb(p3, q, h2 + 1 / 3);
    const g2 = hue2rgb(p3, q, h2);
    const b2 = hue2rgb(p3, q, h2 - 1 / 3);
    return Math.round(r3 * 255) << 24 | Math.round(g2 * 255) << 16 | Math.round(b2 * 255) << 8;
  }
  function parse255(str) {
    const int = parseInt(str, 10);
    if (int < 0) return 0;
    if (int > 255) return 255;
    return int;
  }
  function parse360(str) {
    const int = parseFloat(str);
    return (int % 360 + 360) % 360 / 360;
  }
  function parse1(str) {
    const num = parseFloat(str);
    if (num < 0) return 0;
    if (num > 1) return 255;
    return Math.round(num * 255);
  }
  function parsePercentage(str) {
    const int = parseFloat(str);
    if (int < 0) return 0;
    if (int > 100) return 1;
    return int / 100;
  }
  function colorToRgba(input) {
    let int32Color = normalizeColor(input);
    if (int32Color === null) return input;
    int32Color = int32Color || 0;
    let r3 = (int32Color & 4278190080) >>> 24;
    let g2 = (int32Color & 16711680) >>> 16;
    let b2 = (int32Color & 65280) >>> 8;
    let a2 = (int32Color & 255) / 255;
    return `rgba(${r3}, ${g2}, ${b2}, ${a2})`;
  }
  var createInterpolator = (range, output, extrapolate) => {
    if (is.fun(range)) {
      return range;
    }
    if (is.arr(range)) {
      return createInterpolator({
        range,
        output,
        extrapolate
      });
    }
    if (is.str(range.output[0])) {
      return createStringInterpolator$1(range);
    }
    const config2 = range;
    const outputRange = config2.output;
    const inputRange = config2.range || [0, 1];
    const extrapolateLeft = config2.extrapolateLeft || config2.extrapolate || "extend";
    const extrapolateRight = config2.extrapolateRight || config2.extrapolate || "extend";
    const easing = config2.easing || ((t3) => t3);
    return (input) => {
      const range2 = findRange(input, inputRange);
      return interpolate(input, inputRange[range2], inputRange[range2 + 1], outputRange[range2], outputRange[range2 + 1], easing, extrapolateLeft, extrapolateRight, config2.map);
    };
  };
  function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) {
    let result = map ? map(input) : input;
    if (result < inputMin) {
      if (extrapolateLeft === "identity") return result;
      else if (extrapolateLeft === "clamp") result = inputMin;
    }
    if (result > inputMax) {
      if (extrapolateRight === "identity") return result;
      else if (extrapolateRight === "clamp") result = inputMax;
    }
    if (outputMin === outputMax) return outputMin;
    if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax;
    if (inputMin === -Infinity) result = -result;
    else if (inputMax === Infinity) result = result - inputMin;
    else result = (result - inputMin) / (inputMax - inputMin);
    result = easing(result);
    if (outputMin === -Infinity) result = -result;
    else if (outputMax === Infinity) result = result + outputMin;
    else result = result * (outputMax - outputMin) + outputMin;
    return result;
  }
  function findRange(input, inputRange) {
    for (var i2 = 1; i2 < inputRange.length - 1; ++i2) if (inputRange[i2] >= input) break;
    return i2 - 1;
  }
  function _extends() {
    _extends = Object.assign ? Object.assign.bind() : function(target) {
      for (var i2 = 1; i2 < arguments.length; i2++) {
        var source = arguments[i2];
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    };
    return _extends.apply(this, arguments);
  }
  var $get = /* @__PURE__ */ Symbol.for("FluidValue.get");
  var $observers = /* @__PURE__ */ Symbol.for("FluidValue.observers");
  var hasFluidValue = (arg) => Boolean(arg && arg[$get]);
  var getFluidValue = (arg) => arg && arg[$get] ? arg[$get]() : arg;
  var getFluidObservers = (target) => target[$observers] || null;
  function callFluidObserver(observer, event) {
    if (observer.eventObserved) {
      observer.eventObserved(event);
    } else {
      observer(event);
    }
  }
  function callFluidObservers(target, event) {
    let observers = target[$observers];
    if (observers) {
      observers.forEach((observer) => {
        callFluidObserver(observer, event);
      });
    }
  }
  var FluidValue = class {
    constructor(get) {
      this[$get] = void 0;
      this[$observers] = void 0;
      if (!get && !(get = this.get)) {
        throw Error("Unknown getter");
      }
      setFluidGetter(this, get);
    }
  };
  var setFluidGetter = (target, get) => setHidden(target, $get, get);
  function addFluidObserver(target, observer) {
    if (target[$get]) {
      let observers = target[$observers];
      if (!observers) {
        setHidden(target, $observers, observers = /* @__PURE__ */ new Set());
      }
      if (!observers.has(observer)) {
        observers.add(observer);
        if (target.observerAdded) {
          target.observerAdded(observers.size, observer);
        }
      }
    }
    return observer;
  }
  function removeFluidObserver(target, observer) {
    let observers = target[$observers];
    if (observers && observers.has(observer)) {
      const count = observers.size - 1;
      if (count) {
        observers.delete(observer);
      } else {
        target[$observers] = null;
      }
      if (target.observerRemoved) {
        target.observerRemoved(count, observer);
      }
    }
  }
  var setHidden = (target, key, value) => Object.defineProperty(target, key, {
    value,
    writable: true,
    configurable: true
  });
  var numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  var colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi;
  var unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, "i");
  var rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi;
  var cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;
  var variableToRgba = (input) => {
    const [token, fallback] = parseCSSVariable(input);
    if (!token || isSSR()) {
      return input;
    }
    const value = window.getComputedStyle(document.documentElement).getPropertyValue(token);
    if (value) {
      return value.trim();
    } else if (fallback && fallback.startsWith("--")) {
      const _value = window.getComputedStyle(document.documentElement).getPropertyValue(fallback);
      if (_value) {
        return _value;
      } else {
        return input;
      }
    } else if (fallback && cssVariableRegex.test(fallback)) {
      return variableToRgba(fallback);
    } else if (fallback) {
      return fallback;
    }
    return input;
  };
  var parseCSSVariable = (current) => {
    const match3 = cssVariableRegex.exec(current);
    if (!match3) return [,];
    const [, token, fallback] = match3;
    return [token, fallback];
  };
  var namedColorRegex;
  var rgbaRound = (_, p1, p22, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p22)}, ${Math.round(p3)}, ${p4})`;
  var createStringInterpolator = (config2) => {
    if (!namedColorRegex) namedColorRegex = colors$1 ? new RegExp(`(${Object.keys(colors$1).join("|")})(?!\\w)`, "g") : /^\b$/;
    const output = config2.output.map((value) => {
      return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba);
    });
    const keyframes = output.map((value) => value.match(numberRegex).map(Number));
    const outputRanges = keyframes[0].map((_, i2) => keyframes.map((values) => {
      if (!(i2 in values)) {
        throw Error('The arity of each "output" value must be equal');
      }
      return values[i2];
    }));
    const interpolators = outputRanges.map((output2) => createInterpolator(_extends({}, config2, {
      output: output2
    })));
    return (input) => {
      var _output$find;
      const missingUnit = !unitRegex.test(output[0]) && ((_output$find = output.find((value) => unitRegex.test(value))) == null ? void 0 : _output$find.replace(numberRegex, ""));
      let i2 = 0;
      return output[0].replace(numberRegex, () => `${interpolators[i2++](input)}${missingUnit || ""}`).replace(rgbaRegex, rgbaRound);
    };
  };
  var prefix = "react-spring: ";
  var once = (fn) => {
    const func = fn;
    let called = false;
    if (typeof func != "function") {
      throw new TypeError(`${prefix}once requires a function parameter`);
    }
    return (...args) => {
      if (!called) {
        func(...args);
        called = true;
      }
    };
  };
  var warnInterpolate = once(console.warn);
  function deprecateInterpolate() {
    warnInterpolate(`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`);
  }
  var warnDirectCall = once(console.warn);
  function isAnimatedString(value) {
    return is.str(value) && (value[0] == "#" || /\d/.test(value) || !isSSR() && cssVariableRegex.test(value) || value in (colors$1 || {}));
  }
  var useIsomorphicLayoutEffect = isSSR() ? import_react12.useEffect : import_react12.useLayoutEffect;
  var useIsMounted = () => {
    const isMounted = (0, import_react12.useRef)(false);
    useIsomorphicLayoutEffect(() => {
      isMounted.current = true;
      return () => {
        isMounted.current = false;
      };
    }, []);
    return isMounted;
  };
  function useForceUpdate() {
    const update4 = (0, import_react12.useState)()[1];
    const isMounted = useIsMounted();
    return () => {
      if (isMounted.current) {
        update4(Math.random());
      }
    };
  }
  function useMemoOne(getResult, inputs) {
    const [initial2] = (0, import_react12.useState)(() => ({
      inputs,
      result: getResult()
    }));
    const committed = (0, import_react12.useRef)();
    const prevCache = committed.current;
    let cache = prevCache;
    if (cache) {
      const useCache = Boolean(inputs && cache.inputs && areInputsEqual(inputs, cache.inputs));
      if (!useCache) {
        cache = {
          inputs,
          result: getResult()
        };
      }
    } else {
      cache = initial2;
    }
    (0, import_react12.useEffect)(() => {
      committed.current = cache;
      if (prevCache == initial2) {
        initial2.inputs = initial2.result = void 0;
      }
    }, [cache]);
    return cache.result;
  }
  function areInputsEqual(next, prev) {
    if (next.length !== prev.length) {
      return false;
    }
    for (let i2 = 0; i2 < next.length; i2++) {
      if (next[i2] !== prev[i2]) {
        return false;
      }
    }
    return true;
  }
  var useOnce = (effect) => (0, import_react12.useEffect)(effect, emptyDeps);
  var emptyDeps = [];

  // node_modules/@react-spring/core/dist/react-spring-core.esm.js
  var React58 = __toESM(require_react());
  var import_react14 = __toESM(require_react());

  // node_modules/@react-spring/animated/dist/react-spring-animated.esm.js
  var React57 = __toESM(require_react());
  var import_react13 = __toESM(require_react());
  var $node = /* @__PURE__ */ Symbol.for("Animated:node");
  var isAnimated = (value) => !!value && value[$node] === value;
  var getAnimated = (owner) => owner && owner[$node];
  var setAnimated = (owner, node) => defineHidden(owner, $node, node);
  var getPayload = (owner) => owner && owner[$node] && owner[$node].getPayload();
  var Animated = class {
    constructor() {
      this.payload = void 0;
      setAnimated(this, this);
    }
    getPayload() {
      return this.payload || [];
    }
  };
  var AnimatedValue = class _AnimatedValue extends Animated {
    constructor(_value) {
      super();
      this.done = true;
      this.elapsedTime = void 0;
      this.lastPosition = void 0;
      this.lastVelocity = void 0;
      this.v0 = void 0;
      this.durationProgress = 0;
      this._value = _value;
      if (is.num(this._value)) {
        this.lastPosition = this._value;
      }
    }
    static create(value) {
      return new _AnimatedValue(value);
    }
    getPayload() {
      return [this];
    }
    getValue() {
      return this._value;
    }
    setValue(value, step) {
      if (is.num(value)) {
        this.lastPosition = value;
        if (step) {
          value = Math.round(value / step) * step;
          if (this.done) {
            this.lastPosition = value;
          }
        }
      }
      if (this._value === value) {
        return false;
      }
      this._value = value;
      return true;
    }
    reset() {
      const {
        done
      } = this;
      this.done = false;
      if (is.num(this._value)) {
        this.elapsedTime = 0;
        this.durationProgress = 0;
        this.lastPosition = this._value;
        if (done) this.lastVelocity = null;
        this.v0 = null;
      }
    }
  };
  var AnimatedString = class _AnimatedString extends AnimatedValue {
    constructor(value) {
      super(0);
      this._string = null;
      this._toString = void 0;
      this._toString = createInterpolator({
        output: [value, value]
      });
    }
    static create(value) {
      return new _AnimatedString(value);
    }
    getValue() {
      let value = this._string;
      return value == null ? this._string = this._toString(this._value) : value;
    }
    setValue(value) {
      if (is.str(value)) {
        if (value == this._string) {
          return false;
        }
        this._string = value;
        this._value = 1;
      } else if (super.setValue(value)) {
        this._string = null;
      } else {
        return false;
      }
      return true;
    }
    reset(goal) {
      if (goal) {
        this._toString = createInterpolator({
          output: [this.getValue(), goal]
        });
      }
      this._value = 0;
      super.reset();
    }
  };
  var TreeContext = {
    dependencies: null
  };
  var AnimatedObject = class extends Animated {
    constructor(source) {
      super();
      this.source = source;
      this.setValue(source);
    }
    getValue(animated2) {
      const values = {};
      eachProp(this.source, (source, key) => {
        if (isAnimated(source)) {
          values[key] = source.getValue(animated2);
        } else if (hasFluidValue(source)) {
          values[key] = getFluidValue(source);
        } else if (!animated2) {
          values[key] = source;
        }
      });
      return values;
    }
    setValue(source) {
      this.source = source;
      this.payload = this._makePayload(source);
    }
    reset() {
      if (this.payload) {
        each(this.payload, (node) => node.reset());
      }
    }
    _makePayload(source) {
      if (source) {
        const payload = /* @__PURE__ */ new Set();
        eachProp(source, this._addToPayload, payload);
        return Array.from(payload);
      }
    }
    _addToPayload(source) {
      if (TreeContext.dependencies && hasFluidValue(source)) {
        TreeContext.dependencies.add(source);
      }
      const payload = getPayload(source);
      if (payload) {
        each(payload, (node) => this.add(node));
      }
    }
  };
  var AnimatedArray = class _AnimatedArray extends AnimatedObject {
    constructor(source) {
      super(source);
    }
    static create(source) {
      return new _AnimatedArray(source);
    }
    getValue() {
      return this.source.map((node) => node.getValue());
    }
    setValue(source) {
      const payload = this.getPayload();
      if (source.length == payload.length) {
        return payload.map((node, i2) => node.setValue(source[i2])).some(Boolean);
      }
      super.setValue(source.map(makeAnimated));
      return true;
    }
  };
  function makeAnimated(value) {
    const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue;
    return nodeType.create(value);
  }
  function getAnimatedType(value) {
    const parentNode = getAnimated(value);
    return parentNode ? parentNode.constructor : is.arr(value) ? AnimatedArray : isAnimatedString(value) ? AnimatedString : AnimatedValue;
  }
  function _extends2() {
    _extends2 = Object.assign ? Object.assign.bind() : function(target) {
      for (var i2 = 1; i2 < arguments.length; i2++) {
        var source = arguments[i2];
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    };
    return _extends2.apply(this, arguments);
  }
  var withAnimated = (Component, host2) => {
    const hasInstance = !is.fun(Component) || Component.prototype && Component.prototype.isReactComponent;
    return (0, import_react13.forwardRef)((givenProps, givenRef) => {
      const instanceRef = (0, import_react13.useRef)(null);
      const ref = hasInstance && (0, import_react13.useCallback)((value) => {
        instanceRef.current = updateRef(givenRef, value);
      }, [givenRef]);
      const [props, deps] = getAnimatedState(givenProps, host2);
      const forceUpdate = useForceUpdate();
      const callback = () => {
        const instance = instanceRef.current;
        if (hasInstance && !instance) {
          return;
        }
        const didUpdate = instance ? host2.applyAnimatedValues(instance, props.getValue(true)) : false;
        if (didUpdate === false) {
          forceUpdate();
        }
      };
      const observer = new PropsObserver(callback, deps);
      const observerRef = (0, import_react13.useRef)();
      useIsomorphicLayoutEffect(() => {
        observerRef.current = observer;
        each(deps, (dep) => addFluidObserver(dep, observer));
        return () => {
          if (observerRef.current) {
            each(observerRef.current.deps, (dep) => removeFluidObserver(dep, observerRef.current));
            raf.cancel(observerRef.current.update);
          }
        };
      });
      (0, import_react13.useEffect)(callback, []);
      useOnce(() => () => {
        const observer2 = observerRef.current;
        each(observer2.deps, (dep) => removeFluidObserver(dep, observer2));
      });
      const usedProps = host2.getComponentProps(props.getValue());
      return React57.createElement(Component, _extends2({}, usedProps, {
        ref
      }));
    });
  };
  var PropsObserver = class {
    constructor(update4, deps) {
      this.update = update4;
      this.deps = deps;
    }
    eventObserved(event) {
      if (event.type == "change") {
        raf.write(this.update);
      }
    }
  };
  function getAnimatedState(props, host2) {
    const dependencies = /* @__PURE__ */ new Set();
    TreeContext.dependencies = dependencies;
    if (props.style) props = _extends2({}, props, {
      style: host2.createAnimatedStyle(props.style)
    });
    props = new AnimatedObject(props);
    TreeContext.dependencies = null;
    return [props, dependencies];
  }
  function updateRef(ref, value) {
    if (ref) {
      if (is.fun(ref)) ref(value);
      else ref.current = value;
    }
    return value;
  }
  var cacheKey = /* @__PURE__ */ Symbol.for("AnimatedComponent");
  var createHost = (components, {
    applyAnimatedValues: _applyAnimatedValues = () => false,
    createAnimatedStyle: _createAnimatedStyle = (style) => new AnimatedObject(style),
    getComponentProps: _getComponentProps = (props) => props
  } = {}) => {
    const hostConfig = {
      applyAnimatedValues: _applyAnimatedValues,
      createAnimatedStyle: _createAnimatedStyle,
      getComponentProps: _getComponentProps
    };
    const animated2 = (Component) => {
      const displayName = getDisplayName(Component) || "Anonymous";
      if (is.str(Component)) {
        Component = animated2[Component] || (animated2[Component] = withAnimated(Component, hostConfig));
      } else {
        Component = Component[cacheKey] || (Component[cacheKey] = withAnimated(Component, hostConfig));
      }
      Component.displayName = `Animated(${displayName})`;
      return Component;
    };
    eachProp(components, (Component, key) => {
      if (is.arr(components)) {
        key = getDisplayName(Component);
      }
      animated2[key] = animated2(Component);
    });
    return {
      animated: animated2
    };
  };
  var getDisplayName = (arg) => is.str(arg) ? arg : arg && is.str(arg.displayName) ? arg.displayName : is.fun(arg) && arg.name || null;

  // node_modules/@react-spring/core/dist/react-spring-core.esm.js
  function _extends3() {
    _extends3 = Object.assign ? Object.assign.bind() : function(target) {
      for (var i2 = 1; i2 < arguments.length; i2++) {
        var source = arguments[i2];
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    };
    return _extends3.apply(this, arguments);
  }
  function callProp(value, ...args) {
    return is.fun(value) ? value(...args) : value;
  }
  var matchProp = (value, key) => value === true || !!(key && value && (is.fun(value) ? value(key) : toArray(value).includes(key)));
  var resolveProp = (prop, key) => is.obj(prop) ? key && prop[key] : prop;
  var getDefaultProp = (props, key) => props.default === true ? props[key] : props.default ? props.default[key] : void 0;
  var noopTransform = (value) => value;
  var getDefaultProps = (props, transform = noopTransform) => {
    let keys = DEFAULT_PROPS;
    if (props.default && props.default !== true) {
      props = props.default;
      keys = Object.keys(props);
    }
    const defaults2 = {};
    for (const key of keys) {
      const value = transform(props[key], key);
      if (!is.und(value)) {
        defaults2[key] = value;
      }
    }
    return defaults2;
  };
  var DEFAULT_PROPS = ["config", "onProps", "onStart", "onChange", "onPause", "onResume", "onRest"];
  var RESERVED_PROPS = {
    config: 1,
    from: 1,
    to: 1,
    ref: 1,
    loop: 1,
    reset: 1,
    pause: 1,
    cancel: 1,
    reverse: 1,
    immediate: 1,
    default: 1,
    delay: 1,
    onProps: 1,
    onStart: 1,
    onChange: 1,
    onPause: 1,
    onResume: 1,
    onRest: 1,
    onResolve: 1,
    items: 1,
    trail: 1,
    sort: 1,
    expires: 1,
    initial: 1,
    enter: 1,
    update: 1,
    leave: 1,
    children: 1,
    onDestroyed: 1,
    keys: 1,
    callId: 1,
    parentId: 1
  };
  function getForwardProps(props) {
    const forward = {};
    let count = 0;
    eachProp(props, (value, prop) => {
      if (!RESERVED_PROPS[prop]) {
        forward[prop] = value;
        count++;
      }
    });
    if (count) {
      return forward;
    }
  }
  function inferTo(props) {
    const to2 = getForwardProps(props);
    if (to2) {
      const out = {
        to: to2
      };
      eachProp(props, (val, key) => key in to2 || (out[key] = val));
      return out;
    }
    return _extends3({}, props);
  }
  function computeGoal(value) {
    value = getFluidValue(value);
    return is.arr(value) ? value.map(computeGoal) : isAnimatedString(value) ? globals.createStringInterpolator({
      range: [0, 1],
      output: [value, value]
    })(1) : value;
  }
  function isAsyncTo(to2) {
    return is.fun(to2) || is.arr(to2) && is.obj(to2[0]);
  }
  var config = {
    default: {
      tension: 170,
      friction: 26
    },
    gentle: {
      tension: 120,
      friction: 14
    },
    wobbly: {
      tension: 180,
      friction: 12
    },
    stiff: {
      tension: 210,
      friction: 20
    },
    slow: {
      tension: 280,
      friction: 60
    },
    molasses: {
      tension: 280,
      friction: 120
    }
  };
  var c1 = 1.70158;
  var c2 = c1 * 1.525;
  var c3 = c1 + 1;
  var c4 = 2 * Math.PI / 3;
  var c5 = 2 * Math.PI / 4.5;
  var bounceOut = (x2) => {
    const n1 = 7.5625;
    const d1 = 2.75;
    if (x2 < 1 / d1) {
      return n1 * x2 * x2;
    } else if (x2 < 2 / d1) {
      return n1 * (x2 -= 1.5 / d1) * x2 + 0.75;
    } else if (x2 < 2.5 / d1) {
      return n1 * (x2 -= 2.25 / d1) * x2 + 0.9375;
    } else {
      return n1 * (x2 -= 2.625 / d1) * x2 + 0.984375;
    }
  };
  var easings = {
    linear: (x2) => x2,
    easeInQuad: (x2) => x2 * x2,
    easeOutQuad: (x2) => 1 - (1 - x2) * (1 - x2),
    easeInOutQuad: (x2) => x2 < 0.5 ? 2 * x2 * x2 : 1 - Math.pow(-2 * x2 + 2, 2) / 2,
    easeInCubic: (x2) => x2 * x2 * x2,
    easeOutCubic: (x2) => 1 - Math.pow(1 - x2, 3),
    easeInOutCubic: (x2) => x2 < 0.5 ? 4 * x2 * x2 * x2 : 1 - Math.pow(-2 * x2 + 2, 3) / 2,
    easeInQuart: (x2) => x2 * x2 * x2 * x2,
    easeOutQuart: (x2) => 1 - Math.pow(1 - x2, 4),
    easeInOutQuart: (x2) => x2 < 0.5 ? 8 * x2 * x2 * x2 * x2 : 1 - Math.pow(-2 * x2 + 2, 4) / 2,
    easeInQuint: (x2) => x2 * x2 * x2 * x2 * x2,
    easeOutQuint: (x2) => 1 - Math.pow(1 - x2, 5),
    easeInOutQuint: (x2) => x2 < 0.5 ? 16 * x2 * x2 * x2 * x2 * x2 : 1 - Math.pow(-2 * x2 + 2, 5) / 2,
    easeInSine: (x2) => 1 - Math.cos(x2 * Math.PI / 2),
    easeOutSine: (x2) => Math.sin(x2 * Math.PI / 2),
    easeInOutSine: (x2) => -(Math.cos(Math.PI * x2) - 1) / 2,
    easeInExpo: (x2) => x2 === 0 ? 0 : Math.pow(2, 10 * x2 - 10),
    easeOutExpo: (x2) => x2 === 1 ? 1 : 1 - Math.pow(2, -10 * x2),
    easeInOutExpo: (x2) => x2 === 0 ? 0 : x2 === 1 ? 1 : x2 < 0.5 ? Math.pow(2, 20 * x2 - 10) / 2 : (2 - Math.pow(2, -20 * x2 + 10)) / 2,
    easeInCirc: (x2) => 1 - Math.sqrt(1 - Math.pow(x2, 2)),
    easeOutCirc: (x2) => Math.sqrt(1 - Math.pow(x2 - 1, 2)),
    easeInOutCirc: (x2) => x2 < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x2, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x2 + 2, 2)) + 1) / 2,
    easeInBack: (x2) => c3 * x2 * x2 * x2 - c1 * x2 * x2,
    easeOutBack: (x2) => 1 + c3 * Math.pow(x2 - 1, 3) + c1 * Math.pow(x2 - 1, 2),
    easeInOutBack: (x2) => x2 < 0.5 ? Math.pow(2 * x2, 2) * ((c2 + 1) * 2 * x2 - c2) / 2 : (Math.pow(2 * x2 - 2, 2) * ((c2 + 1) * (x2 * 2 - 2) + c2) + 2) / 2,
    easeInElastic: (x2) => x2 === 0 ? 0 : x2 === 1 ? 1 : -Math.pow(2, 10 * x2 - 10) * Math.sin((x2 * 10 - 10.75) * c4),
    easeOutElastic: (x2) => x2 === 0 ? 0 : x2 === 1 ? 1 : Math.pow(2, -10 * x2) * Math.sin((x2 * 10 - 0.75) * c4) + 1,
    easeInOutElastic: (x2) => x2 === 0 ? 0 : x2 === 1 ? 1 : x2 < 0.5 ? -(Math.pow(2, 20 * x2 - 10) * Math.sin((20 * x2 - 11.125) * c5)) / 2 : Math.pow(2, -20 * x2 + 10) * Math.sin((20 * x2 - 11.125) * c5) / 2 + 1,
    easeInBounce: (x2) => 1 - bounceOut(1 - x2),
    easeOutBounce: bounceOut,
    easeInOutBounce: (x2) => x2 < 0.5 ? (1 - bounceOut(1 - 2 * x2)) / 2 : (1 + bounceOut(2 * x2 - 1)) / 2
  };
  var defaults = _extends3({}, config.default, {
    mass: 1,
    damping: 1,
    easing: easings.linear,
    clamp: false
  });
  var AnimationConfig = class {
    constructor() {
      this.tension = void 0;
      this.friction = void 0;
      this.frequency = void 0;
      this.damping = void 0;
      this.mass = void 0;
      this.velocity = 0;
      this.restVelocity = void 0;
      this.precision = void 0;
      this.progress = void 0;
      this.duration = void 0;
      this.easing = void 0;
      this.clamp = void 0;
      this.bounce = void 0;
      this.decay = void 0;
      this.round = void 0;
      Object.assign(this, defaults);
    }
  };
  function mergeConfig(config2, newConfig, defaultConfig) {
    if (defaultConfig) {
      defaultConfig = _extends3({}, defaultConfig);
      sanitizeConfig(defaultConfig, newConfig);
      newConfig = _extends3({}, defaultConfig, newConfig);
    }
    sanitizeConfig(config2, newConfig);
    Object.assign(config2, newConfig);
    for (const key in defaults) {
      if (config2[key] == null) {
        config2[key] = defaults[key];
      }
    }
    let {
      mass,
      frequency,
      damping
    } = config2;
    if (!is.und(frequency)) {
      if (frequency < 0.01) frequency = 0.01;
      if (damping < 0) damping = 0;
      config2.tension = Math.pow(2 * Math.PI / frequency, 2) * mass;
      config2.friction = 4 * Math.PI * damping * mass / frequency;
    }
    return config2;
  }
  function sanitizeConfig(config2, props) {
    if (!is.und(props.decay)) {
      config2.duration = void 0;
    } else {
      const isTensionConfig = !is.und(props.tension) || !is.und(props.friction);
      if (isTensionConfig || !is.und(props.frequency) || !is.und(props.damping) || !is.und(props.mass)) {
        config2.duration = void 0;
        config2.decay = void 0;
      }
      if (isTensionConfig) {
        config2.frequency = void 0;
      }
    }
  }
  var emptyArray = [];
  var Animation = class {
    constructor() {
      this.changed = false;
      this.values = emptyArray;
      this.toValues = null;
      this.fromValues = emptyArray;
      this.to = void 0;
      this.from = void 0;
      this.config = new AnimationConfig();
      this.immediate = false;
    }
  };
  function scheduleProps(callId, {
    key,
    props,
    defaultProps,
    state,
    actions
  }) {
    return new Promise((resolve, reject) => {
      var _props$cancel;
      let delay;
      let timeout;
      let cancel = matchProp((_props$cancel = props.cancel) != null ? _props$cancel : defaultProps == null ? void 0 : defaultProps.cancel, key);
      if (cancel) {
        onStart();
      } else {
        if (!is.und(props.pause)) {
          state.paused = matchProp(props.pause, key);
        }
        let pause = defaultProps == null ? void 0 : defaultProps.pause;
        if (pause !== true) {
          pause = state.paused || matchProp(pause, key);
        }
        delay = callProp(props.delay || 0, key);
        if (pause) {
          state.resumeQueue.add(onResume);
          actions.pause();
        } else {
          actions.resume();
          onResume();
        }
      }
      function onPause() {
        state.resumeQueue.add(onResume);
        state.timeouts.delete(timeout);
        timeout.cancel();
        delay = timeout.time - raf.now();
      }
      function onResume() {
        if (delay > 0 && !globals.skipAnimation) {
          state.delayed = true;
          timeout = raf.setTimeout(onStart, delay);
          state.pauseQueue.add(onPause);
          state.timeouts.add(timeout);
        } else {
          onStart();
        }
      }
      function onStart() {
        if (state.delayed) {
          state.delayed = false;
        }
        state.pauseQueue.delete(onPause);
        state.timeouts.delete(timeout);
        if (callId <= (state.cancelId || 0)) {
          cancel = true;
        }
        try {
          actions.start(_extends3({}, props, {
            callId,
            cancel
          }), resolve);
        } catch (err) {
          reject(err);
        }
      }
    });
  }
  var getCombinedResult = (target, results) => results.length == 1 ? results[0] : results.some((result) => result.cancelled) ? getCancelledResult(target.get()) : results.every((result) => result.noop) ? getNoopResult(target.get()) : getFinishedResult(target.get(), results.every((result) => result.finished));
  var getNoopResult = (value) => ({
    value,
    noop: true,
    finished: true,
    cancelled: false
  });
  var getFinishedResult = (value, finished, cancelled = false) => ({
    value,
    finished,
    cancelled
  });
  var getCancelledResult = (value) => ({
    value,
    cancelled: true,
    finished: false
  });
  function runAsync(to2, props, state, target) {
    const {
      callId,
      parentId,
      onRest
    } = props;
    const {
      asyncTo: prevTo,
      promise: prevPromise
    } = state;
    if (!parentId && to2 === prevTo && !props.reset) {
      return prevPromise;
    }
    return state.promise = (async () => {
      state.asyncId = callId;
      state.asyncTo = to2;
      const defaultProps = getDefaultProps(props, (value, key) => key === "onRest" ? void 0 : value);
      let preventBail;
      let bail;
      const bailPromise = new Promise((resolve, reject) => (preventBail = resolve, bail = reject));
      const bailIfEnded = (bailSignal) => {
        const bailResult = callId <= (state.cancelId || 0) && getCancelledResult(target) || callId !== state.asyncId && getFinishedResult(target, false);
        if (bailResult) {
          bailSignal.result = bailResult;
          bail(bailSignal);
          throw bailSignal;
        }
      };
      const animate = (arg1, arg2) => {
        const bailSignal = new BailSignal();
        const skipAnimationSignal = new SkipAniamtionSignal();
        return (async () => {
          if (globals.skipAnimation) {
            stopAsync(state);
            skipAnimationSignal.result = getFinishedResult(target, false);
            bail(skipAnimationSignal);
            throw skipAnimationSignal;
          }
          bailIfEnded(bailSignal);
          const props2 = is.obj(arg1) ? _extends3({}, arg1) : _extends3({}, arg2, {
            to: arg1
          });
          props2.parentId = callId;
          eachProp(defaultProps, (value, key) => {
            if (is.und(props2[key])) {
              props2[key] = value;
            }
          });
          const result2 = await target.start(props2);
          bailIfEnded(bailSignal);
          if (state.paused) {
            await new Promise((resume) => {
              state.resumeQueue.add(resume);
            });
          }
          return result2;
        })();
      };
      let result;
      if (globals.skipAnimation) {
        stopAsync(state);
        return getFinishedResult(target, false);
      }
      try {
        let animating;
        if (is.arr(to2)) {
          animating = (async (queue) => {
            for (const props2 of queue) {
              await animate(props2);
            }
          })(to2);
        } else {
          animating = Promise.resolve(to2(animate, target.stop.bind(target)));
        }
        await Promise.all([animating.then(preventBail), bailPromise]);
        result = getFinishedResult(target.get(), true, false);
      } catch (err) {
        if (err instanceof BailSignal) {
          result = err.result;
        } else if (err instanceof SkipAniamtionSignal) {
          result = err.result;
        } else {
          throw err;
        }
      } finally {
        if (callId == state.asyncId) {
          state.asyncId = parentId;
          state.asyncTo = parentId ? prevTo : void 0;
          state.promise = parentId ? prevPromise : void 0;
        }
      }
      if (is.fun(onRest)) {
        raf.batchedUpdates(() => {
          onRest(result, target, target.item);
        });
      }
      return result;
    })();
  }
  function stopAsync(state, cancelId) {
    flush(state.timeouts, (t3) => t3.cancel());
    state.pauseQueue.clear();
    state.resumeQueue.clear();
    state.asyncId = state.asyncTo = state.promise = void 0;
    if (cancelId) state.cancelId = cancelId;
  }
  var BailSignal = class extends Error {
    constructor() {
      super("An async animation has been interrupted. You see this error because you forgot to use `await` or `.catch(...)` on its returned promise.");
      this.result = void 0;
    }
  };
  var SkipAniamtionSignal = class extends Error {
    constructor() {
      super("SkipAnimationSignal");
      this.result = void 0;
    }
  };
  var isFrameValue = (value) => value instanceof FrameValue;
  var nextId$1 = 1;
  var FrameValue = class extends FluidValue {
    constructor(...args) {
      super(...args);
      this.id = nextId$1++;
      this.key = void 0;
      this._priority = 0;
    }
    get priority() {
      return this._priority;
    }
    set priority(priority2) {
      if (this._priority != priority2) {
        this._priority = priority2;
        this._onPriorityChange(priority2);
      }
    }
    get() {
      const node = getAnimated(this);
      return node && node.getValue();
    }
    to(...args) {
      return globals.to(this, args);
    }
    interpolate(...args) {
      deprecateInterpolate();
      return globals.to(this, args);
    }
    toJSON() {
      return this.get();
    }
    observerAdded(count) {
      if (count == 1) this._attach();
    }
    observerRemoved(count) {
      if (count == 0) this._detach();
    }
    _attach() {
    }
    _detach() {
    }
    _onChange(value, idle = false) {
      callFluidObservers(this, {
        type: "change",
        parent: this,
        value,
        idle
      });
    }
    _onPriorityChange(priority2) {
      if (!this.idle) {
        frameLoop.sort(this);
      }
      callFluidObservers(this, {
        type: "priority",
        parent: this,
        priority: priority2
      });
    }
  };
  var $P = /* @__PURE__ */ Symbol.for("SpringPhase");
  var HAS_ANIMATED = 1;
  var IS_ANIMATING = 2;
  var IS_PAUSED = 4;
  var hasAnimated = (target) => (target[$P] & HAS_ANIMATED) > 0;
  var isAnimating = (target) => (target[$P] & IS_ANIMATING) > 0;
  var isPaused = (target) => (target[$P] & IS_PAUSED) > 0;
  var setActiveBit = (target, active) => active ? target[$P] |= IS_ANIMATING | HAS_ANIMATED : target[$P] &= ~IS_ANIMATING;
  var setPausedBit = (target, paused) => paused ? target[$P] |= IS_PAUSED : target[$P] &= ~IS_PAUSED;
  var SpringValue = class extends FrameValue {
    constructor(arg1, arg2) {
      super();
      this.key = void 0;
      this.animation = new Animation();
      this.queue = void 0;
      this.defaultProps = {};
      this._state = {
        paused: false,
        delayed: false,
        pauseQueue: /* @__PURE__ */ new Set(),
        resumeQueue: /* @__PURE__ */ new Set(),
        timeouts: /* @__PURE__ */ new Set()
      };
      this._pendingCalls = /* @__PURE__ */ new Set();
      this._lastCallId = 0;
      this._lastToId = 0;
      this._memoizedDuration = 0;
      if (!is.und(arg1) || !is.und(arg2)) {
        const props = is.obj(arg1) ? _extends3({}, arg1) : _extends3({}, arg2, {
          from: arg1
        });
        if (is.und(props.default)) {
          props.default = true;
        }
        this.start(props);
      }
    }
    get idle() {
      return !(isAnimating(this) || this._state.asyncTo) || isPaused(this);
    }
    get goal() {
      return getFluidValue(this.animation.to);
    }
    get velocity() {
      const node = getAnimated(this);
      return node instanceof AnimatedValue ? node.lastVelocity || 0 : node.getPayload().map((node2) => node2.lastVelocity || 0);
    }
    get hasAnimated() {
      return hasAnimated(this);
    }
    get isAnimating() {
      return isAnimating(this);
    }
    get isPaused() {
      return isPaused(this);
    }
    get isDelayed() {
      return this._state.delayed;
    }
    advance(dt) {
      let idle = true;
      let changed = false;
      const anim = this.animation;
      let {
        config: config2,
        toValues
      } = anim;
      const payload = getPayload(anim.to);
      if (!payload && hasFluidValue(anim.to)) {
        toValues = toArray(getFluidValue(anim.to));
      }
      anim.values.forEach((node2, i2) => {
        if (node2.done) return;
        const to2 = node2.constructor == AnimatedString ? 1 : payload ? payload[i2].lastPosition : toValues[i2];
        let finished = anim.immediate;
        let position = to2;
        if (!finished) {
          position = node2.lastPosition;
          if (config2.tension <= 0) {
            node2.done = true;
            return;
          }
          let elapsed = node2.elapsedTime += dt;
          const from = anim.fromValues[i2];
          const v0 = node2.v0 != null ? node2.v0 : node2.v0 = is.arr(config2.velocity) ? config2.velocity[i2] : config2.velocity;
          let velocity;
          const precision = config2.precision || (from == to2 ? 5e-3 : Math.min(1, Math.abs(to2 - from) * 1e-3));
          if (!is.und(config2.duration)) {
            let p3 = 1;
            if (config2.duration > 0) {
              if (this._memoizedDuration !== config2.duration) {
                this._memoizedDuration = config2.duration;
                if (node2.durationProgress > 0) {
                  node2.elapsedTime = config2.duration * node2.durationProgress;
                  elapsed = node2.elapsedTime += dt;
                }
              }
              p3 = (config2.progress || 0) + elapsed / this._memoizedDuration;
              p3 = p3 > 1 ? 1 : p3 < 0 ? 0 : p3;
              node2.durationProgress = p3;
            }
            position = from + config2.easing(p3) * (to2 - from);
            velocity = (position - node2.lastPosition) / dt;
            finished = p3 == 1;
          } else if (config2.decay) {
            const decay = config2.decay === true ? 0.998 : config2.decay;
            const e2 = Math.exp(-(1 - decay) * elapsed);
            position = from + v0 / (1 - decay) * (1 - e2);
            finished = Math.abs(node2.lastPosition - position) <= precision;
            velocity = v0 * e2;
          } else {
            velocity = node2.lastVelocity == null ? v0 : node2.lastVelocity;
            const restVelocity = config2.restVelocity || precision / 10;
            const bounceFactor = config2.clamp ? 0 : config2.bounce;
            const canBounce = !is.und(bounceFactor);
            const isGrowing = from == to2 ? node2.v0 > 0 : from < to2;
            let isMoving;
            let isBouncing = false;
            const step = 1;
            const numSteps = Math.ceil(dt / step);
            for (let n2 = 0; n2 < numSteps; ++n2) {
              isMoving = Math.abs(velocity) > restVelocity;
              if (!isMoving) {
                finished = Math.abs(to2 - position) <= precision;
                if (finished) {
                  break;
                }
              }
              if (canBounce) {
                isBouncing = position == to2 || position > to2 == isGrowing;
                if (isBouncing) {
                  velocity = -velocity * bounceFactor;
                  position = to2;
                }
              }
              const springForce = -config2.tension * 1e-6 * (position - to2);
              const dampingForce = -config2.friction * 1e-3 * velocity;
              const acceleration = (springForce + dampingForce) / config2.mass;
              velocity = velocity + acceleration * step;
              position = position + velocity * step;
            }
          }
          node2.lastVelocity = velocity;
          if (Number.isNaN(position)) {
            console.warn(`Got NaN while animating:`, this);
            finished = true;
          }
        }
        if (payload && !payload[i2].done) {
          finished = false;
        }
        if (finished) {
          node2.done = true;
        } else {
          idle = false;
        }
        if (node2.setValue(position, config2.round)) {
          changed = true;
        }
      });
      const node = getAnimated(this);
      const currVal = node.getValue();
      if (idle) {
        const finalVal = getFluidValue(anim.to);
        if ((currVal !== finalVal || changed) && !config2.decay) {
          node.setValue(finalVal);
          this._onChange(finalVal);
        } else if (changed && config2.decay) {
          this._onChange(currVal);
        }
        this._stop();
      } else if (changed) {
        this._onChange(currVal);
      }
    }
    set(value) {
      raf.batchedUpdates(() => {
        this._stop();
        this._focus(value);
        this._set(value);
      });
      return this;
    }
    pause() {
      this._update({
        pause: true
      });
    }
    resume() {
      this._update({
        pause: false
      });
    }
    finish() {
      if (isAnimating(this)) {
        const {
          to: to2,
          config: config2
        } = this.animation;
        raf.batchedUpdates(() => {
          this._onStart();
          if (!config2.decay) {
            this._set(to2, false);
          }
          this._stop();
        });
      }
      return this;
    }
    update(props) {
      const queue = this.queue || (this.queue = []);
      queue.push(props);
      return this;
    }
    start(to2, arg2) {
      let queue;
      if (!is.und(to2)) {
        queue = [is.obj(to2) ? to2 : _extends3({}, arg2, {
          to: to2
        })];
      } else {
        queue = this.queue || [];
        this.queue = [];
      }
      return Promise.all(queue.map((props) => {
        const up = this._update(props);
        return up;
      })).then((results) => getCombinedResult(this, results));
    }
    stop(cancel) {
      const {
        to: to2
      } = this.animation;
      this._focus(this.get());
      stopAsync(this._state, cancel && this._lastCallId);
      raf.batchedUpdates(() => this._stop(to2, cancel));
      return this;
    }
    reset() {
      this._update({
        reset: true
      });
    }
    eventObserved(event) {
      if (event.type == "change") {
        this._start();
      } else if (event.type == "priority") {
        this.priority = event.priority + 1;
      }
    }
    _prepareNode(props) {
      const key = this.key || "";
      let {
        to: to2,
        from
      } = props;
      to2 = is.obj(to2) ? to2[key] : to2;
      if (to2 == null || isAsyncTo(to2)) {
        to2 = void 0;
      }
      from = is.obj(from) ? from[key] : from;
      if (from == null) {
        from = void 0;
      }
      const range = {
        to: to2,
        from
      };
      if (!hasAnimated(this)) {
        if (props.reverse) [to2, from] = [from, to2];
        from = getFluidValue(from);
        if (!is.und(from)) {
          this._set(from);
        } else if (!getAnimated(this)) {
          this._set(to2);
        }
      }
      return range;
    }
    _update(_ref, isLoop) {
      let props = _extends3({}, _ref);
      const {
        key,
        defaultProps
      } = this;
      if (props.default) Object.assign(defaultProps, getDefaultProps(props, (value, prop) => /^on/.test(prop) ? resolveProp(value, key) : value));
      mergeActiveFn(this, props, "onProps");
      sendEvent(this, "onProps", props, this);
      const range = this._prepareNode(props);
      if (Object.isFrozen(this)) {
        throw Error("Cannot animate a `SpringValue` object that is frozen. Did you forget to pass your component to `animated(...)` before animating its props?");
      }
      const state = this._state;
      return scheduleProps(++this._lastCallId, {
        key,
        props,
        defaultProps,
        state,
        actions: {
          pause: () => {
            if (!isPaused(this)) {
              setPausedBit(this, true);
              flushCalls(state.pauseQueue);
              sendEvent(this, "onPause", getFinishedResult(this, checkFinished(this, this.animation.to)), this);
            }
          },
          resume: () => {
            if (isPaused(this)) {
              setPausedBit(this, false);
              if (isAnimating(this)) {
                this._resume();
              }
              flushCalls(state.resumeQueue);
              sendEvent(this, "onResume", getFinishedResult(this, checkFinished(this, this.animation.to)), this);
            }
          },
          start: this._merge.bind(this, range)
        }
      }).then((result) => {
        if (props.loop && result.finished && !(isLoop && result.noop)) {
          const nextProps = createLoopUpdate(props);
          if (nextProps) {
            return this._update(nextProps, true);
          }
        }
        return result;
      });
    }
    _merge(range, props, resolve) {
      if (props.cancel) {
        this.stop(true);
        return resolve(getCancelledResult(this));
      }
      const hasToProp = !is.und(range.to);
      const hasFromProp = !is.und(range.from);
      if (hasToProp || hasFromProp) {
        if (props.callId > this._lastToId) {
          this._lastToId = props.callId;
        } else {
          return resolve(getCancelledResult(this));
        }
      }
      const {
        key,
        defaultProps,
        animation: anim
      } = this;
      const {
        to: prevTo,
        from: prevFrom
      } = anim;
      let {
        to: to2 = prevTo,
        from = prevFrom
      } = range;
      if (hasFromProp && !hasToProp && (!props.default || is.und(to2))) {
        to2 = from;
      }
      if (props.reverse) [to2, from] = [from, to2];
      const hasFromChanged = !isEqual(from, prevFrom);
      if (hasFromChanged) {
        anim.from = from;
      }
      from = getFluidValue(from);
      const hasToChanged = !isEqual(to2, prevTo);
      if (hasToChanged) {
        this._focus(to2);
      }
      const hasAsyncTo = isAsyncTo(props.to);
      const {
        config: config2
      } = anim;
      const {
        decay,
        velocity
      } = config2;
      if (hasToProp || hasFromProp) {
        config2.velocity = 0;
      }
      if (props.config && !hasAsyncTo) {
        mergeConfig(config2, callProp(props.config, key), props.config !== defaultProps.config ? callProp(defaultProps.config, key) : void 0);
      }
      let node = getAnimated(this);
      if (!node || is.und(to2)) {
        return resolve(getFinishedResult(this, true));
      }
      const reset = is.und(props.reset) ? hasFromProp && !props.default : !is.und(from) && matchProp(props.reset, key);
      const value = reset ? from : this.get();
      const goal = computeGoal(to2);
      const isAnimatable = is.num(goal) || is.arr(goal) || isAnimatedString(goal);
      const immediate = !hasAsyncTo && (!isAnimatable || matchProp(defaultProps.immediate || props.immediate, key));
      if (hasToChanged) {
        const nodeType = getAnimatedType(to2);
        if (nodeType !== node.constructor) {
          if (immediate) {
            node = this._set(goal);
          } else throw Error(`Cannot animate between ${node.constructor.name} and ${nodeType.name}, as the "to" prop suggests`);
        }
      }
      const goalType = node.constructor;
      let started = hasFluidValue(to2);
      let finished = false;
      if (!started) {
        const hasValueChanged = reset || !hasAnimated(this) && hasFromChanged;
        if (hasToChanged || hasValueChanged) {
          finished = isEqual(computeGoal(value), goal);
          started = !finished;
        }
        if (!isEqual(anim.immediate, immediate) && !immediate || !isEqual(config2.decay, decay) || !isEqual(config2.velocity, velocity)) {
          started = true;
        }
      }
      if (finished && isAnimating(this)) {
        if (anim.changed && !reset) {
          started = true;
        } else if (!started) {
          this._stop(prevTo);
        }
      }
      if (!hasAsyncTo) {
        if (started || hasFluidValue(prevTo)) {
          anim.values = node.getPayload();
          anim.toValues = hasFluidValue(to2) ? null : goalType == AnimatedString ? [1] : toArray(goal);
        }
        if (anim.immediate != immediate) {
          anim.immediate = immediate;
          if (!immediate && !reset) {
            this._set(prevTo);
          }
        }
        if (started) {
          const {
            onRest
          } = anim;
          each(ACTIVE_EVENTS, (type) => mergeActiveFn(this, props, type));
          const result = getFinishedResult(this, checkFinished(this, prevTo));
          flushCalls(this._pendingCalls, result);
          this._pendingCalls.add(resolve);
          if (anim.changed) raf.batchedUpdates(() => {
            anim.changed = !reset;
            onRest == null ? void 0 : onRest(result, this);
            if (reset) {
              callProp(defaultProps.onRest, result);
            } else {
              anim.onStart == null ? void 0 : anim.onStart(result, this);
            }
          });
        }
      }
      if (reset) {
        this._set(value);
      }
      if (hasAsyncTo) {
        resolve(runAsync(props.to, props, this._state, this));
      } else if (started) {
        this._start();
      } else if (isAnimating(this) && !hasToChanged) {
        this._pendingCalls.add(resolve);
      } else {
        resolve(getNoopResult(value));
      }
    }
    _focus(value) {
      const anim = this.animation;
      if (value !== anim.to) {
        if (getFluidObservers(this)) {
          this._detach();
        }
        anim.to = value;
        if (getFluidObservers(this)) {
          this._attach();
        }
      }
    }
    _attach() {
      let priority2 = 0;
      const {
        to: to2
      } = this.animation;
      if (hasFluidValue(to2)) {
        addFluidObserver(to2, this);
        if (isFrameValue(to2)) {
          priority2 = to2.priority + 1;
        }
      }
      this.priority = priority2;
    }
    _detach() {
      const {
        to: to2
      } = this.animation;
      if (hasFluidValue(to2)) {
        removeFluidObserver(to2, this);
      }
    }
    _set(arg, idle = true) {
      const value = getFluidValue(arg);
      if (!is.und(value)) {
        const oldNode = getAnimated(this);
        if (!oldNode || !isEqual(value, oldNode.getValue())) {
          const nodeType = getAnimatedType(value);
          if (!oldNode || oldNode.constructor != nodeType) {
            setAnimated(this, nodeType.create(value));
          } else {
            oldNode.setValue(value);
          }
          if (oldNode) {
            raf.batchedUpdates(() => {
              this._onChange(value, idle);
            });
          }
        }
      }
      return getAnimated(this);
    }
    _onStart() {
      const anim = this.animation;
      if (!anim.changed) {
        anim.changed = true;
        sendEvent(this, "onStart", getFinishedResult(this, checkFinished(this, anim.to)), this);
      }
    }
    _onChange(value, idle) {
      if (!idle) {
        this._onStart();
        callProp(this.animation.onChange, value, this);
      }
      callProp(this.defaultProps.onChange, value, this);
      super._onChange(value, idle);
    }
    _start() {
      const anim = this.animation;
      getAnimated(this).reset(getFluidValue(anim.to));
      if (!anim.immediate) {
        anim.fromValues = anim.values.map((node) => node.lastPosition);
      }
      if (!isAnimating(this)) {
        setActiveBit(this, true);
        if (!isPaused(this)) {
          this._resume();
        }
      }
    }
    _resume() {
      if (globals.skipAnimation) {
        this.finish();
      } else {
        frameLoop.start(this);
      }
    }
    _stop(goal, cancel) {
      if (isAnimating(this)) {
        setActiveBit(this, false);
        const anim = this.animation;
        each(anim.values, (node) => {
          node.done = true;
        });
        if (anim.toValues) {
          anim.onChange = anim.onPause = anim.onResume = void 0;
        }
        callFluidObservers(this, {
          type: "idle",
          parent: this
        });
        const result = cancel ? getCancelledResult(this.get()) : getFinishedResult(this.get(), checkFinished(this, goal != null ? goal : anim.to));
        flushCalls(this._pendingCalls, result);
        if (anim.changed) {
          anim.changed = false;
          sendEvent(this, "onRest", result, this);
        }
      }
    }
  };
  function checkFinished(target, to2) {
    const goal = computeGoal(to2);
    const value = computeGoal(target.get());
    return isEqual(value, goal);
  }
  function createLoopUpdate(props, loop2 = props.loop, to2 = props.to) {
    let loopRet = callProp(loop2);
    if (loopRet) {
      const overrides = loopRet !== true && inferTo(loopRet);
      const reverse = (overrides || props).reverse;
      const reset = !overrides || overrides.reset;
      return createUpdate(_extends3({}, props, {
        loop: loop2,
        default: false,
        pause: void 0,
        to: !reverse || isAsyncTo(to2) ? to2 : void 0,
        from: reset ? props.from : void 0,
        reset
      }, overrides));
    }
  }
  function createUpdate(props) {
    const {
      to: to2,
      from
    } = props = inferTo(props);
    const keys = /* @__PURE__ */ new Set();
    if (is.obj(to2)) findDefined(to2, keys);
    if (is.obj(from)) findDefined(from, keys);
    props.keys = keys.size ? Array.from(keys) : null;
    return props;
  }
  function findDefined(values, keys) {
    eachProp(values, (value, key) => value != null && keys.add(key));
  }
  var ACTIVE_EVENTS = ["onStart", "onRest", "onChange", "onPause", "onResume"];
  function mergeActiveFn(target, props, type) {
    target.animation[type] = props[type] !== getDefaultProp(props, type) ? resolveProp(props[type], target.key) : void 0;
  }
  function sendEvent(target, type, ...args) {
    var _target$animation$typ, _target$animation, _target$defaultProps$, _target$defaultProps;
    (_target$animation$typ = (_target$animation = target.animation)[type]) == null ? void 0 : _target$animation$typ.call(_target$animation, ...args);
    (_target$defaultProps$ = (_target$defaultProps = target.defaultProps)[type]) == null ? void 0 : _target$defaultProps$.call(_target$defaultProps, ...args);
  }
  var BATCHED_EVENTS = ["onStart", "onChange", "onRest"];
  var nextId = 1;
  var Controller = class {
    constructor(props, flush2) {
      this.id = nextId++;
      this.springs = {};
      this.queue = [];
      this.ref = void 0;
      this._flush = void 0;
      this._initialProps = void 0;
      this._lastAsyncId = 0;
      this._active = /* @__PURE__ */ new Set();
      this._changed = /* @__PURE__ */ new Set();
      this._started = false;
      this._item = void 0;
      this._state = {
        paused: false,
        pauseQueue: /* @__PURE__ */ new Set(),
        resumeQueue: /* @__PURE__ */ new Set(),
        timeouts: /* @__PURE__ */ new Set()
      };
      this._events = {
        onStart: /* @__PURE__ */ new Map(),
        onChange: /* @__PURE__ */ new Map(),
        onRest: /* @__PURE__ */ new Map()
      };
      this._onFrame = this._onFrame.bind(this);
      if (flush2) {
        this._flush = flush2;
      }
      if (props) {
        this.start(_extends3({
          default: true
        }, props));
      }
    }
    get idle() {
      return !this._state.asyncTo && Object.values(this.springs).every((spring) => {
        return spring.idle && !spring.isDelayed && !spring.isPaused;
      });
    }
    get item() {
      return this._item;
    }
    set item(item) {
      this._item = item;
    }
    get() {
      const values = {};
      this.each((spring, key) => values[key] = spring.get());
      return values;
    }
    set(values) {
      for (const key in values) {
        const value = values[key];
        if (!is.und(value)) {
          this.springs[key].set(value);
        }
      }
    }
    update(props) {
      if (props) {
        this.queue.push(createUpdate(props));
      }
      return this;
    }
    start(props) {
      let {
        queue
      } = this;
      if (props) {
        queue = toArray(props).map(createUpdate);
      } else {
        this.queue = [];
      }
      if (this._flush) {
        return this._flush(this, queue);
      }
      prepareKeys(this, queue);
      return flushUpdateQueue(this, queue);
    }
    stop(arg, keys) {
      if (arg !== !!arg) {
        keys = arg;
      }
      if (keys) {
        const springs = this.springs;
        each(toArray(keys), (key) => springs[key].stop(!!arg));
      } else {
        stopAsync(this._state, this._lastAsyncId);
        this.each((spring) => spring.stop(!!arg));
      }
      return this;
    }
    pause(keys) {
      if (is.und(keys)) {
        this.start({
          pause: true
        });
      } else {
        const springs = this.springs;
        each(toArray(keys), (key) => springs[key].pause());
      }
      return this;
    }
    resume(keys) {
      if (is.und(keys)) {
        this.start({
          pause: false
        });
      } else {
        const springs = this.springs;
        each(toArray(keys), (key) => springs[key].resume());
      }
      return this;
    }
    each(iterator) {
      eachProp(this.springs, iterator);
    }
    _onFrame() {
      const {
        onStart,
        onChange,
        onRest
      } = this._events;
      const active = this._active.size > 0;
      const changed = this._changed.size > 0;
      if (active && !this._started || changed && !this._started) {
        this._started = true;
        flush(onStart, ([onStart2, result]) => {
          result.value = this.get();
          onStart2(result, this, this._item);
        });
      }
      const idle = !active && this._started;
      const values = changed || idle && onRest.size ? this.get() : null;
      if (changed && onChange.size) {
        flush(onChange, ([onChange2, result]) => {
          result.value = values;
          onChange2(result, this, this._item);
        });
      }
      if (idle) {
        this._started = false;
        flush(onRest, ([onRest2, result]) => {
          result.value = values;
          onRest2(result, this, this._item);
        });
      }
    }
    eventObserved(event) {
      if (event.type == "change") {
        this._changed.add(event.parent);
        if (!event.idle) {
          this._active.add(event.parent);
        }
      } else if (event.type == "idle") {
        this._active.delete(event.parent);
      } else return;
      raf.onFrame(this._onFrame);
    }
  };
  function flushUpdateQueue(ctrl, queue) {
    return Promise.all(queue.map((props) => flushUpdate(ctrl, props))).then((results) => getCombinedResult(ctrl, results));
  }
  async function flushUpdate(ctrl, props, isLoop) {
    const {
      keys,
      to: to2,
      from,
      loop: loop2,
      onRest,
      onResolve
    } = props;
    const defaults2 = is.obj(props.default) && props.default;
    if (loop2) {
      props.loop = false;
    }
    if (to2 === false) props.to = null;
    if (from === false) props.from = null;
    const asyncTo = is.arr(to2) || is.fun(to2) ? to2 : void 0;
    if (asyncTo) {
      props.to = void 0;
      props.onRest = void 0;
      if (defaults2) {
        defaults2.onRest = void 0;
      }
    } else {
      each(BATCHED_EVENTS, (key) => {
        const handler = props[key];
        if (is.fun(handler)) {
          const queue = ctrl["_events"][key];
          props[key] = ({
            finished,
            cancelled
          }) => {
            const result2 = queue.get(handler);
            if (result2) {
              if (!finished) result2.finished = false;
              if (cancelled) result2.cancelled = true;
            } else {
              queue.set(handler, {
                value: null,
                finished: finished || false,
                cancelled: cancelled || false
              });
            }
          };
          if (defaults2) {
            defaults2[key] = props[key];
          }
        }
      });
    }
    const state = ctrl["_state"];
    if (props.pause === !state.paused) {
      state.paused = props.pause;
      flushCalls(props.pause ? state.pauseQueue : state.resumeQueue);
    } else if (state.paused) {
      props.pause = true;
    }
    const promises = (keys || Object.keys(ctrl.springs)).map((key) => ctrl.springs[key].start(props));
    const cancel = props.cancel === true || getDefaultProp(props, "cancel") === true;
    if (asyncTo || cancel && state.asyncId) {
      promises.push(scheduleProps(++ctrl["_lastAsyncId"], {
        props,
        state,
        actions: {
          pause: noop4,
          resume: noop4,
          start(props2, resolve) {
            if (cancel) {
              stopAsync(state, ctrl["_lastAsyncId"]);
              resolve(getCancelledResult(ctrl));
            } else {
              props2.onRest = onRest;
              resolve(runAsync(asyncTo, props2, state, ctrl));
            }
          }
        }
      }));
    }
    if (state.paused) {
      await new Promise((resume) => {
        state.resumeQueue.add(resume);
      });
    }
    const result = getCombinedResult(ctrl, await Promise.all(promises));
    if (loop2 && result.finished && !(isLoop && result.noop)) {
      const nextProps = createLoopUpdate(props, loop2, to2);
      if (nextProps) {
        prepareKeys(ctrl, [nextProps]);
        return flushUpdate(ctrl, nextProps, true);
      }
    }
    if (onResolve) {
      raf.batchedUpdates(() => onResolve(result, ctrl, ctrl.item));
    }
    return result;
  }
  function createSpring(key, observer) {
    const spring = new SpringValue();
    spring.key = key;
    if (observer) {
      addFluidObserver(spring, observer);
    }
    return spring;
  }
  function prepareSprings(springs, props, create) {
    if (props.keys) {
      each(props.keys, (key) => {
        const spring = springs[key] || (springs[key] = create(key));
        spring["_prepareNode"](props);
      });
    }
  }
  function prepareKeys(ctrl, queue) {
    each(queue, (props) => {
      prepareSprings(ctrl.springs, props, (key) => {
        return createSpring(key, ctrl);
      });
    });
  }
  function _objectWithoutPropertiesLoose(source, excluded) {
    if (source == null) return {};
    var target = {};
    var sourceKeys = Object.keys(source);
    var key, i2;
    for (i2 = 0; i2 < sourceKeys.length; i2++) {
      key = sourceKeys[i2];
      if (excluded.indexOf(key) >= 0) continue;
      target[key] = source[key];
    }
    return target;
  }
  var _excluded$3 = ["children"];
  var SpringContext = (_ref) => {
    let {
      children
    } = _ref, props = _objectWithoutPropertiesLoose(_ref, _excluded$3);
    const inherited = (0, import_react14.useContext)(ctx);
    const pause = props.pause || !!inherited.pause, immediate = props.immediate || !!inherited.immediate;
    props = useMemoOne(() => ({
      pause,
      immediate
    }), [pause, immediate]);
    const {
      Provider: Provider2
    } = ctx;
    return React58.createElement(Provider2, {
      value: props
    }, children);
  };
  var ctx = makeContext(SpringContext, {});
  SpringContext.Provider = ctx.Provider;
  SpringContext.Consumer = ctx.Consumer;
  function makeContext(target, init2) {
    Object.assign(target, React58.createContext(init2));
    target.Provider._context = target;
    target.Consumer._context = target;
    return target;
  }
  var TransitionPhase;
  (function(TransitionPhase2) {
    TransitionPhase2["MOUNT"] = "mount";
    TransitionPhase2["ENTER"] = "enter";
    TransitionPhase2["UPDATE"] = "update";
    TransitionPhase2["LEAVE"] = "leave";
  })(TransitionPhase || (TransitionPhase = {}));
  var Interpolation = class extends FrameValue {
    constructor(source, args) {
      super();
      this.key = void 0;
      this.idle = true;
      this.calc = void 0;
      this._active = /* @__PURE__ */ new Set();
      this.source = source;
      this.calc = createInterpolator(...args);
      const value = this._get();
      const nodeType = getAnimatedType(value);
      setAnimated(this, nodeType.create(value));
    }
    advance(_dt) {
      const value = this._get();
      const oldValue = this.get();
      if (!isEqual(value, oldValue)) {
        getAnimated(this).setValue(value);
        this._onChange(value, this.idle);
      }
      if (!this.idle && checkIdle(this._active)) {
        becomeIdle(this);
      }
    }
    _get() {
      const inputs = is.arr(this.source) ? this.source.map(getFluidValue) : toArray(getFluidValue(this.source));
      return this.calc(...inputs);
    }
    _start() {
      if (this.idle && !checkIdle(this._active)) {
        this.idle = false;
        each(getPayload(this), (node) => {
          node.done = false;
        });
        if (globals.skipAnimation) {
          raf.batchedUpdates(() => this.advance());
          becomeIdle(this);
        } else {
          frameLoop.start(this);
        }
      }
    }
    _attach() {
      let priority2 = 1;
      each(toArray(this.source), (source) => {
        if (hasFluidValue(source)) {
          addFluidObserver(source, this);
        }
        if (isFrameValue(source)) {
          if (!source.idle) {
            this._active.add(source);
          }
          priority2 = Math.max(priority2, source.priority + 1);
        }
      });
      this.priority = priority2;
      this._start();
    }
    _detach() {
      each(toArray(this.source), (source) => {
        if (hasFluidValue(source)) {
          removeFluidObserver(source, this);
        }
      });
      this._active.clear();
      becomeIdle(this);
    }
    eventObserved(event) {
      if (event.type == "change") {
        if (event.idle) {
          this.advance();
        } else {
          this._active.add(event.parent);
          this._start();
        }
      } else if (event.type == "idle") {
        this._active.delete(event.parent);
      } else if (event.type == "priority") {
        this.priority = toArray(this.source).reduce((highest, parent) => Math.max(highest, (isFrameValue(parent) ? parent.priority : 0) + 1), 0);
      }
    }
  };
  function isIdle(source) {
    return source.idle !== false;
  }
  function checkIdle(active) {
    return !active.size || Array.from(active).every(isIdle);
  }
  function becomeIdle(self2) {
    if (!self2.idle) {
      self2.idle = true;
      each(getPayload(self2), (node) => {
        node.done = true;
      });
      callFluidObservers(self2, {
        type: "idle",
        parent: self2
      });
    }
  }
  globals.assign({
    createStringInterpolator,
    to: (source, args) => new Interpolation(source, args)
  });
  var update3 = frameLoop.advance;

  // node_modules/@react-spring/web/dist/react-spring-web.esm.js
  var import_react_dom4 = __toESM(require_react_dom());
  function _objectWithoutPropertiesLoose2(source, excluded) {
    if (source == null) return {};
    var target = {};
    var sourceKeys = Object.keys(source);
    var key, i2;
    for (i2 = 0; i2 < sourceKeys.length; i2++) {
      key = sourceKeys[i2];
      if (excluded.indexOf(key) >= 0) continue;
      target[key] = source[key];
    }
    return target;
  }
  var _excluded$2 = ["style", "children", "scrollTop", "scrollLeft"];
  var isCustomPropRE = /^--/;
  function dangerousStyleValue(name2, value) {
    if (value == null || typeof value === "boolean" || value === "") return "";
    if (typeof value === "number" && value !== 0 && !isCustomPropRE.test(name2) && !(isUnitlessNumber.hasOwnProperty(name2) && isUnitlessNumber[name2])) return value + "px";
    return ("" + value).trim();
  }
  var attributeCache = {};
  function applyAnimatedValues(instance, props) {
    if (!instance.nodeType || !instance.setAttribute) {
      return false;
    }
    const isFilterElement = instance.nodeName === "filter" || instance.parentNode && instance.parentNode.nodeName === "filter";
    const _ref = props, {
      style,
      children,
      scrollTop,
      scrollLeft
    } = _ref, attributes = _objectWithoutPropertiesLoose2(_ref, _excluded$2);
    const values = Object.values(attributes);
    const names = Object.keys(attributes).map((name2) => isFilterElement || instance.hasAttribute(name2) ? name2 : attributeCache[name2] || (attributeCache[name2] = name2.replace(/([A-Z])/g, (n2) => "-" + n2.toLowerCase())));
    if (children !== void 0) {
      instance.textContent = children;
    }
    for (let name2 in style) {
      if (style.hasOwnProperty(name2)) {
        const value = dangerousStyleValue(name2, style[name2]);
        if (isCustomPropRE.test(name2)) {
          instance.style.setProperty(name2, value);
        } else {
          instance.style[name2] = value;
        }
      }
    }
    names.forEach((name2, i2) => {
      instance.setAttribute(name2, values[i2]);
    });
    if (scrollTop !== void 0) {
      instance.scrollTop = scrollTop;
    }
    if (scrollLeft !== void 0) {
      instance.scrollLeft = scrollLeft;
    }
  }
  var isUnitlessNumber = {
    animationIterationCount: true,
    borderImageOutset: true,
    borderImageSlice: true,
    borderImageWidth: true,
    boxFlex: true,
    boxFlexGroup: true,
    boxOrdinalGroup: true,
    columnCount: true,
    columns: true,
    flex: true,
    flexGrow: true,
    flexPositive: true,
    flexShrink: true,
    flexNegative: true,
    flexOrder: true,
    gridRow: true,
    gridRowEnd: true,
    gridRowSpan: true,
    gridRowStart: true,
    gridColumn: true,
    gridColumnEnd: true,
    gridColumnSpan: true,
    gridColumnStart: true,
    fontWeight: true,
    lineClamp: true,
    lineHeight: true,
    opacity: true,
    order: true,
    orphans: true,
    tabSize: true,
    widows: true,
    zIndex: true,
    zoom: true,
    fillOpacity: true,
    floodOpacity: true,
    stopOpacity: true,
    strokeDasharray: true,
    strokeDashoffset: true,
    strokeMiterlimit: true,
    strokeOpacity: true,
    strokeWidth: true
  };
  var prefixKey = (prefix2, key) => prefix2 + key.charAt(0).toUpperCase() + key.substring(1);
  var prefixes = ["Webkit", "Ms", "Moz", "O"];
  isUnitlessNumber = Object.keys(isUnitlessNumber).reduce((acc, prop) => {
    prefixes.forEach((prefix2) => acc[prefixKey(prefix2, prop)] = acc[prop]);
    return acc;
  }, isUnitlessNumber);
  var _excluded$1 = ["x", "y", "z"];
  var domTransforms = /^(matrix|translate|scale|rotate|skew)/;
  var pxTransforms = /^(translate)/;
  var degTransforms = /^(rotate|skew)/;
  var addUnit = (value, unit) => is.num(value) && value !== 0 ? value + unit : value;
  var isValueIdentity = (value, id) => is.arr(value) ? value.every((v2) => isValueIdentity(v2, id)) : is.num(value) ? value === id : parseFloat(value) === id;
  var AnimatedStyle = class extends AnimatedObject {
    constructor(_ref) {
      let {
        x: x2,
        y: y2,
        z
      } = _ref, style = _objectWithoutPropertiesLoose2(_ref, _excluded$1);
      const inputs = [];
      const transforms = [];
      if (x2 || y2 || z) {
        inputs.push([x2 || 0, y2 || 0, z || 0]);
        transforms.push((xyz) => [`translate3d(${xyz.map((v2) => addUnit(v2, "px")).join(",")})`, isValueIdentity(xyz, 0)]);
      }
      eachProp(style, (value, key) => {
        if (key === "transform") {
          inputs.push([value || ""]);
          transforms.push((transform) => [transform, transform === ""]);
        } else if (domTransforms.test(key)) {
          delete style[key];
          if (is.und(value)) return;
          const unit = pxTransforms.test(key) ? "px" : degTransforms.test(key) ? "deg" : "";
          inputs.push(toArray(value));
          transforms.push(key === "rotate3d" ? ([x3, y3, z2, deg]) => [`rotate3d(${x3},${y3},${z2},${addUnit(deg, unit)})`, isValueIdentity(deg, 0)] : (input) => [`${key}(${input.map((v2) => addUnit(v2, unit)).join(",")})`, isValueIdentity(input, key.startsWith("scale") ? 1 : 0)]);
        }
      });
      if (inputs.length) {
        style.transform = new FluidTransform(inputs, transforms);
      }
      super(style);
    }
  };
  var FluidTransform = class extends FluidValue {
    constructor(inputs, transforms) {
      super();
      this._value = null;
      this.inputs = inputs;
      this.transforms = transforms;
    }
    get() {
      return this._value || (this._value = this._get());
    }
    _get() {
      let transform = "";
      let identity2 = true;
      each(this.inputs, (input, i2) => {
        const arg1 = getFluidValue(input[0]);
        const [t3, id] = this.transforms[i2](is.arr(arg1) ? arg1 : input.map(getFluidValue));
        transform += " " + t3;
        identity2 = identity2 && id;
      });
      return identity2 ? "none" : transform;
    }
    observerAdded(count) {
      if (count == 1) each(this.inputs, (input) => each(input, (value) => hasFluidValue(value) && addFluidObserver(value, this)));
    }
    observerRemoved(count) {
      if (count == 0) each(this.inputs, (input) => each(input, (value) => hasFluidValue(value) && removeFluidObserver(value, this)));
    }
    eventObserved(event) {
      if (event.type == "change") {
        this._value = null;
      }
      callFluidObservers(this, event);
    }
  };
  var primitives = ["a", "abbr", "address", "area", "article", "aside", "audio", "b", "base", "bdi", "bdo", "big", "blockquote", "body", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "img", "input", "ins", "kbd", "keygen", "label", "legend", "li", "link", "main", "map", "mark", "menu", "menuitem", "meta", "meter", "nav", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "small", "source", "span", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "u", "ul", "var", "video", "wbr", "circle", "clipPath", "defs", "ellipse", "foreignObject", "g", "image", "line", "linearGradient", "mask", "path", "pattern", "polygon", "polyline", "radialGradient", "rect", "stop", "svg", "text", "tspan"];
  var _excluded = ["scrollTop", "scrollLeft"];
  globals.assign({
    batchedUpdates: import_react_dom4.unstable_batchedUpdates,
    createStringInterpolator,
    colors
  });
  var host = createHost(primitives, {
    applyAnimatedValues,
    createAnimatedStyle: (style) => new AnimatedStyle(style),
    getComponentProps: (_ref) => {
      let props = _objectWithoutPropertiesLoose2(_ref, _excluded);
      return props;
    }
  });
  var animated = host.animated;

  // packages/edit-site/build-module/components/layout/animation.mjs
  var import_element41 = __toESM(require_element(), 1);
  function getAbsolutePosition(element) {
    return {
      top: element.offsetTop,
      left: element.offsetLeft
    };
  }
  var ANIMATION_DURATION = 400;
  function useMovingAnimation({ triggerAnimationOnChange }) {
    const ref = (0, import_element41.useRef)();
    const { previous, prevRect } = (0, import_element41.useMemo)(
      () => ({
        previous: ref.current && getAbsolutePosition(ref.current),
        prevRect: ref.current && ref.current.getBoundingClientRect()
      }),
      [triggerAnimationOnChange]
    );
    (0, import_element41.useLayoutEffect)(() => {
      if (!previous || !ref.current) {
        return;
      }
      const disableAnimation = window.matchMedia(
        "(prefers-reduced-motion: reduce)"
      ).matches;
      if (disableAnimation) {
        return;
      }
      const controller = new Controller({
        x: 0,
        y: 0,
        width: prevRect.width,
        height: prevRect.height,
        config: {
          duration: ANIMATION_DURATION,
          easing: easings.easeInOutQuint
        },
        onChange({ value }) {
          if (!ref.current) {
            return;
          }
          let { x: x22, y: y22, width: width2, height: height2 } = value;
          x22 = Math.round(x22);
          y22 = Math.round(y22);
          width2 = Math.round(width2);
          height2 = Math.round(height2);
          const finishedMoving = x22 === 0 && y22 === 0;
          ref.current.style.transformOrigin = "center center";
          ref.current.style.transform = finishedMoving ? null : `translate3d(${x22}px,${y22}px,0)`;
          ref.current.style.width = finishedMoving ? null : `${width2}px`;
          ref.current.style.height = finishedMoving ? null : `${height2}px`;
        }
      });
      ref.current.style.transform = void 0;
      const destination = ref.current.getBoundingClientRect();
      const x2 = Math.round(prevRect.left - destination.left);
      const y2 = Math.round(prevRect.top - destination.top);
      const width = destination.width;
      const height = destination.height;
      controller.start({
        x: 0,
        y: 0,
        width,
        height,
        from: { x: x2, y: y2, width: prevRect.width, height: prevRect.height }
      });
      return () => {
        controller.stop();
        controller.set({
          x: 0,
          y: 0,
          width: prevRect.width,
          height: prevRect.height
        });
      };
    }, [previous, prevRect]);
    return ref;
  }
  var animation_default = useMovingAnimation;

  // packages/edit-site/build-module/components/save-hub/index.mjs
  var import_data9 = __toESM(require_data(), 1);
  var import_core_data8 = __toESM(require_core_data(), 1);

  // packages/edit-site/build-module/components/save-button/index.mjs
  var import_data8 = __toESM(require_data(), 1);
  var import_components4 = __toESM(require_components(), 1);
  var import_i18n5 = __toESM(require_i18n(), 1);
  var import_core_data7 = __toESM(require_core_data(), 1);
  var import_keycodes = __toESM(require_keycodes(), 1);
  var import_router3 = __toESM(require_router(), 1);
  var import_editor4 = __toESM(require_editor(), 1);

  // packages/edit-site/build-module/utils/is-previewing-theme.mjs
  var import_url2 = __toESM(require_url(), 1);
  function isPreviewingTheme() {
    return !!(0, import_url2.getQueryArg)(window.location.href, "wp_theme_preview");
  }
  function currentlyPreviewingTheme() {
    if (isPreviewingTheme()) {
      return (0, import_url2.getQueryArg)(window.location.href, "wp_theme_preview");
    }
    return null;
  }

  // packages/edit-site/build-module/components/save-button/index.mjs
  var import_jsx_runtime101 = __toESM(require_jsx_runtime(), 1);
  var { useLocation: useLocation3 } = unlock(import_router3.privateApis);
  function SaveButton({
    className = "edit-site-save-button__button",
    variant = "primary",
    showTooltip = true,
    showReviewMessage,
    icon,
    size: size4,
    __next40pxDefaultSize = false
  }) {
    const { params } = useLocation3();
    const { setIsSaveViewOpened: setIsSaveViewOpened2 } = (0, import_data8.useDispatch)(store);
    const { saveDirtyEntities } = unlock((0, import_data8.useDispatch)(import_editor4.store));
    const { dirtyEntityRecords } = (0, import_editor4.useEntitiesSavedStatesIsDirty)();
    const { isSaving, isSaveViewOpen, previewingThemeName } = (0, import_data8.useSelect)(
      (select4) => {
        const { isSavingEntityRecord, isResolving } = select4(import_core_data7.store);
        const { isSaveViewOpened: isSaveViewOpened2 } = select4(store);
        const isActivatingTheme = isResolving("activateTheme");
        const currentlyPreviewingThemeId = currentlyPreviewingTheme();
        return {
          isSaving: dirtyEntityRecords.some(
            (record) => isSavingEntityRecord(
              record.kind,
              record.name,
              record.key
            )
          ) || isActivatingTheme,
          isSaveViewOpen: isSaveViewOpened2(),
          // Do not call `getTheme` with null, it will cause a request to
          // the server.
          previewingThemeName: currentlyPreviewingThemeId ? select4(import_core_data7.store).getTheme(currentlyPreviewingThemeId)?.name?.rendered : void 0
        };
      },
      [dirtyEntityRecords]
    );
    const hasDirtyEntities = !!dirtyEntityRecords.length;
    let isOnlyCurrentEntityDirty;
    if (dirtyEntityRecords.length === 1) {
      if (params.postId) {
        isOnlyCurrentEntityDirty = `${dirtyEntityRecords[0].key}` === params.postId && dirtyEntityRecords[0].name === params.postType;
      } else if (params.path?.includes("wp_global_styles")) {
        isOnlyCurrentEntityDirty = dirtyEntityRecords[0].name === "globalStyles";
      }
    }
    const disabled2 = isSaving || !hasDirtyEntities && !isPreviewingTheme();
    const getLabel = () => {
      if (isPreviewingTheme()) {
        if (isSaving) {
          return (0, import_i18n5.sprintf)(
            /* translators: %s: The name of theme to be activated. */
            (0, import_i18n5.__)("Activating %s"),
            previewingThemeName
          );
        } else if (disabled2) {
          return (0, import_i18n5.__)("Saved");
        } else if (hasDirtyEntities) {
          return (0, import_i18n5.sprintf)(
            /* translators: %s: The name of theme to be activated. */
            (0, import_i18n5.__)("Activate %s & Save"),
            previewingThemeName
          );
        }
        return (0, import_i18n5.sprintf)(
          /* translators: %s: The name of theme to be activated. */
          (0, import_i18n5.__)("Activate %s"),
          previewingThemeName
        );
      }
      if (isSaving) {
        return (0, import_i18n5.__)("Saving");
      }
      if (disabled2) {
        return (0, import_i18n5.__)("Saved");
      }
      if (!isOnlyCurrentEntityDirty && showReviewMessage) {
        return (0, import_i18n5.sprintf)(
          // translators: %d: number of unsaved changes (number).
          (0, import_i18n5._n)(
            "Review %d change\u2026",
            "Review %d changes\u2026",
            dirtyEntityRecords.length
          ),
          dirtyEntityRecords.length
        );
      }
      return (0, import_i18n5.__)("Save");
    };
    const label = getLabel();
    const onClick = isOnlyCurrentEntityDirty ? () => saveDirtyEntities({ dirtyEntityRecords }) : () => setIsSaveViewOpened2(true);
    return /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
      import_components4.Button,
      {
        variant,
        className,
        "aria-disabled": disabled2,
        "aria-expanded": isSaveViewOpen,
        isBusy: isSaving,
        onClick: disabled2 ? void 0 : onClick,
        label,
        shortcut: disabled2 ? void 0 : import_keycodes.displayShortcut.primary("s"),
        showTooltip,
        icon,
        __next40pxDefaultSize,
        size: size4,
        children: label
      }
    );
  }

  // packages/edit-site/build-module/components/save-hub/index.mjs
  var import_jsx_runtime102 = __toESM(require_jsx_runtime(), 1);
  function SaveHub() {
    const { isDisabled, isSaving } = (0, import_data9.useSelect)((select4) => {
      const { __experimentalGetDirtyEntityRecords, isSavingEntityRecord } = select4(import_core_data8.store);
      const dirtyEntityRecords = __experimentalGetDirtyEntityRecords();
      const _isSaving = dirtyEntityRecords.some(
        (record) => isSavingEntityRecord(record.kind, record.name, record.key)
      );
      return {
        isSaving: _isSaving,
        isDisabled: _isSaving || !dirtyEntityRecords.length && !isPreviewingTheme()
      };
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Stack, { className: "edit-site-save-hub", gap: "lg", children: /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(
      SaveButton,
      {
        className: "edit-site-save-hub__button",
        variant: isDisabled && !isSaving ? null : "primary",
        showTooltip: false,
        icon: isDisabled && !isSaving ? check_default : null,
        showReviewMessage: true,
        __next40pxDefaultSize: true
      }
    ) });
  }

  // packages/edit-site/build-module/components/save-panel/index.mjs
  var import_components5 = __toESM(require_components(), 1);
  var import_editor5 = __toESM(require_editor(), 1);
  var import_data11 = __toESM(require_data(), 1);
  var import_i18n6 = __toESM(require_i18n(), 1);
  var import_core_data10 = __toESM(require_core_data(), 1);
  var import_router5 = __toESM(require_router(), 1);
  var import_element43 = __toESM(require_element(), 1);

  // packages/edit-site/build-module/utils/use-activate-theme.mjs
  var import_core_data9 = __toESM(require_core_data(), 1);
  var import_data10 = __toESM(require_data(), 1);
  var import_router4 = __toESM(require_router(), 1);
  var import_url3 = __toESM(require_url(), 1);
  var { useHistory: useHistory3, useLocation: useLocation4 } = unlock(import_router4.privateApis);
  function useActivateTheme() {
    const history = useHistory3();
    const { path } = useLocation4();
    const { startResolution, finishResolution } = (0, import_data10.useDispatch)(import_core_data9.store);
    return async () => {
      if (isPreviewingTheme()) {
        const activationURL = "themes.php?action=activate&stylesheet=" + currentlyPreviewingTheme() + "&_wpnonce=" + window.WP_BLOCK_THEME_ACTIVATE_NONCE;
        startResolution("activateTheme");
        await window.fetch(activationURL);
        finishResolution("activateTheme");
        history.navigate((0, import_url3.addQueryArgs)(path, { wp_theme_preview: "" }));
      }
    };
  }

  // packages/edit-site/build-module/utils/use-actual-current-theme.mjs
  var import_api_fetch = __toESM(require_api_fetch(), 1);
  var import_element42 = __toESM(require_element(), 1);
  var import_url4 = __toESM(require_url(), 1);
  var ACTIVE_THEMES_URL = "/wp/v2/themes?status=active";
  function useActualCurrentTheme() {
    const [currentTheme, setCurrentTheme] = (0, import_element42.useState)();
    (0, import_element42.useEffect)(() => {
      const path = (0, import_url4.addQueryArgs)(ACTIVE_THEMES_URL, {
        context: "edit",
        wp_theme_preview: ""
      });
      (0, import_api_fetch.default)({ path }).then((activeThemes) => setCurrentTheme(activeThemes[0])).catch(() => {
      });
    }, []);
    return currentTheme;
  }

  // packages/edit-site/build-module/components/save-panel/index.mjs
  var import_jsx_runtime103 = __toESM(require_jsx_runtime(), 1);
  var { EntitiesSavedStatesExtensible } = unlock(import_editor5.privateApis);
  var { useLocation: useLocation5 } = unlock(import_router5.privateApis);
  var EntitiesSavedStatesForPreview = ({
    onClose,
    renderDialog,
    variant
  }) => {
    const isDirtyProps = (0, import_editor5.useEntitiesSavedStatesIsDirty)();
    let activateSaveLabel, successNoticeContent;
    if (isDirtyProps.isDirty) {
      activateSaveLabel = (0, import_i18n6.__)("Activate & Save");
      successNoticeContent = (0, import_i18n6.__)("Theme activated and site updated.");
    } else {
      activateSaveLabel = (0, import_i18n6.__)("Activate");
      successNoticeContent = (0, import_i18n6.__)("Theme activated.");
    }
    const currentTheme = useActualCurrentTheme();
    const previewingTheme = (0, import_data11.useSelect)(
      (select4) => select4(import_core_data10.store).getCurrentTheme(),
      []
    );
    const additionalPrompt = /* @__PURE__ */ (0, import_jsx_runtime103.jsx)("p", { children: (0, import_i18n6.sprintf)(
      /* translators: 1: The name of active theme, 2: The name of theme to be activated. */
      (0, import_i18n6.__)(
        "Saving your changes will change your active theme from %1$s to %2$s."
      ),
      currentTheme?.name?.rendered ?? "...",
      previewingTheme?.name?.rendered ?? "..."
    ) });
    const activateTheme = useActivateTheme();
    const onSave = async () => {
      await activateTheme();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
      EntitiesSavedStatesExtensible,
      {
        ...{
          ...isDirtyProps,
          additionalPrompt,
          close: onClose,
          onSave,
          saveEnabled: true,
          saveLabel: activateSaveLabel,
          renderDialog,
          variant,
          successNoticeContent
        }
      }
    );
  };
  var _EntitiesSavedStates = ({ onClose, renderDialog, variant }) => {
    if (isPreviewingTheme()) {
      return /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
        EntitiesSavedStatesForPreview,
        {
          onClose,
          renderDialog,
          variant
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
      import_editor5.EntitiesSavedStates,
      {
        close: onClose,
        renderDialog,
        variant
      }
    );
  };
  function SavePanel() {
    const { query } = useLocation5();
    const { canvas = "view" } = query;
    const { isSaveViewOpen, isDirty, isSaving } = (0, import_data11.useSelect)((select4) => {
      const {
        __experimentalGetDirtyEntityRecords,
        isSavingEntityRecord,
        isResolving
      } = select4(import_core_data10.store);
      const dirtyEntityRecords = __experimentalGetDirtyEntityRecords();
      const isActivatingTheme = isResolving("activateTheme");
      const { isSaveViewOpened: isSaveViewOpened2 } = unlock(select4(store));
      return {
        isSaveViewOpen: isSaveViewOpened2(),
        isDirty: dirtyEntityRecords.length > 0,
        isSaving: dirtyEntityRecords.some(
          (record) => isSavingEntityRecord(record.kind, record.name, record.key)
        ) || isActivatingTheme
      };
    }, []);
    const { setIsSaveViewOpened: setIsSaveViewOpened2 } = (0, import_data11.useDispatch)(store);
    const onClose = () => setIsSaveViewOpened2(false);
    (0, import_element43.useEffect)(() => {
      setIsSaveViewOpened2(false);
    }, [canvas, setIsSaveViewOpened2]);
    if (canvas === "view") {
      return isSaveViewOpen ? /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
        import_components5.Modal,
        {
          className: "edit-site-save-panel__modal",
          onRequestClose: onClose,
          title: (0, import_i18n6.__)("Review changes"),
          size: "small",
          children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(_EntitiesSavedStates, { onClose, variant: "inline" })
        }
      ) : null;
    }
    const activateSaveEnabled = isPreviewingTheme() || isDirty;
    const disabled2 = isSaving || !activateSaveEnabled;
    return /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)(
      navigable_region_default,
      {
        className: clsx_default("edit-site-layout__actions", {
          "is-entity-save-view-open": isSaveViewOpen
        }),
        ariaLabel: (0, import_i18n6.__)("Save panel"),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
            "div",
            {
              className: clsx_default("edit-site-editor__toggle-save-panel", {
                "screen-reader-text": isSaveViewOpen
              }),
              children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
                import_components5.Button,
                {
                  __next40pxDefaultSize: true,
                  variant: "secondary",
                  className: "edit-site-editor__toggle-save-panel-button",
                  onClick: () => setIsSaveViewOpened2(true),
                  "aria-haspopup": "dialog",
                  disabled: disabled2,
                  accessibleWhenDisabled: true,
                  children: (0, import_i18n6.__)("Open save panel")
                }
              )
            }
          ),
          isSaveViewOpen && /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(_EntitiesSavedStates, { onClose, renderDialog: true })
        ]
      }
    );
  }

  // packages/edit-site/build-module/components/layout/index.mjs
  var import_jsx_runtime104 = __toESM(require_jsx_runtime(), 1);
  var { useLocation: useLocation6 } = unlock(import_router6.privateApis);
  var { useStyle, UploadProgressSnackbar } = unlock(import_editor6.privateApis);
  var ANIMATION_DURATION2 = 0.3;
  var CONTENT_COLOR = { background: "#ffffff" };
  function Layout() {
    const { query, name: routeKey, areas: areas2, widths } = useLocation6();
    const canvas = routeKey === "notfound" ? "view" : query?.canvas ?? "view";
    const showMobileSiteHub = !!areas2.mobileContent;
    const hasMobileAreas = areas2.mobileSidebar || areas2.mobileContent || areas2.preview;
    const isMobileViewport = (0, import_compose2.useViewportMatch)("medium", "<");
    const mobileToggleRef = (0, import_element44.useRef)();
    const sidebarRegionRef = (0, import_element44.useRef)();
    const navigateRegionsProps = (0, import_components6.__unstableUseNavigateRegions)();
    const disableMotion = (0, import_compose2.useReducedMotion)();
    const [canvasResizer, canvasSize] = (0, import_compose2.useResizeObserver)();
    const isEditorLoading = useIsSiteEditorLoading();
    const [isResizableFrameOversized, setIsResizableFrameOversized] = (0, import_element44.useState)(false);
    const animationRef = animation_default({
      triggerAnimationOnChange: routeKey + "-" + canvas
    });
    const { showIconLabels } = (0, import_data12.useSelect)((select4) => {
      return {
        showIconLabels: select4(import_preferences3.store).get(
          "core",
          "showIconLabels"
        )
      };
    });
    const backgroundColor = useStyle("color.background");
    const gradientValue = useStyle("color.gradient");
    const previousCanvaMode = (0, import_compose2.usePrevious)(canvas);
    (0, import_element44.useEffect)(() => {
      if (previousCanvaMode === "edit") {
        const desktopToggle = sidebarRegionRef.current ? (
          // We're typically expecting the `<DashboardBackButton />` component as the first tabbable element.
          import_dom23.focus.tabbable.find(sidebarRegionRef.current)[0]
        ) : void 0;
        (desktopToggle ?? mobileToggleRef.current)?.focus();
      }
    }, [canvas]);
    return /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(import_jsx_runtime104.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_editor6.UnsavedChangesWarning, {}),
      canvas === "view" && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SaveKeyboardShortcut, {}),
      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
        "div",
        {
          ...navigateRegionsProps,
          ref: navigateRegionsProps.ref,
          className: clsx_default(
            "edit-site-layout",
            navigateRegionsProps.className,
            {
              "is-full-canvas": canvas === "edit",
              "show-icon-labels": showIconLabels
            }
          ),
          children: /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "edit-site-layout__content", children: [
            (!isMobileViewport || !hasMobileAreas) && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
              navigable_region_default,
              {
                ref: sidebarRegionRef,
                ariaLabel: (0, import_i18n7.__)("Navigation"),
                className: "edit-site-layout__sidebar-region",
                children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_components6.__unstableAnimatePresence, { children: canvas === "view" && /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(
                  import_components6.__unstableMotion.div,
                  {
                    initial: { opacity: 0 },
                    animate: { opacity: 1 },
                    exit: { opacity: 0 },
                    transition: {
                      type: "tween",
                      duration: (
                        // Disable transition in mobile to emulate a full page transition.
                        disableMotion || isMobileViewport ? 0 : ANIMATION_DURATION2
                      ),
                      ease: "easeOut"
                    },
                    className: "edit-site-layout__sidebar",
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SidebarNavigationProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
                        SidebarContent,
                        {
                          shouldAnimate: routeKey !== "styles" && routeKey !== "identity",
                          routeKey,
                          children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_editor6.ErrorBoundary, { children: areas2.sidebar })
                        }
                      ) }),
                      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SaveHub, {}),
                      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SavePanel, {})
                    ]
                  }
                ) })
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_notices.SnackbarNotices, { className: "edit-site-layout__snackbar" }),
            /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(UploadProgressSnackbar, {}),
            isMobileViewport && hasMobileAreas && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "edit-site-layout__mobile", children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SidebarNavigationProvider, { children: canvas !== "edit" ? /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(import_jsx_runtime104.Fragment, { children: [
              showMobileSiteHub && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
                SiteHubMobile,
                {
                  ref: mobileToggleRef
                }
              ),
              areas2.mobileContent ? (
                /*
                 * ThemeProvider wraps SidebarContent (rather than
                 * just the content) so the scroll wrapper it renders
                 * inherits the content background tokens. See
                 * `.edit-site-sidebar__screen-wrapper` in style.scss.
                 */
                /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
                  import_theme.ThemeProvider,
                  {
                    color: CONTENT_COLOR,
                    children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
                      SidebarContent,
                      {
                        routeKey,
                        children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)("div", { className: "edit-site-layout__mobile-content", children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_editor6.ErrorBoundary, { children: areas2.mobileContent }) })
                      }
                    )
                  }
                )
              ) : /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
                SidebarContent,
                {
                  routeKey,
                  children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_editor6.ErrorBoundary, { children: areas2.mobileSidebar })
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SaveHub, {}),
              /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(SavePanel, {})
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_theme.ThemeProvider, { color: CONTENT_COLOR, children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_editor6.ErrorBoundary, { children: areas2.preview }) }) }) }),
            !isMobileViewport && areas2.content && canvas !== "edit" && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
              "div",
              {
                className: "edit-site-layout__area",
                style: {
                  maxWidth: widths?.content
                },
                children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_theme.ThemeProvider, { color: CONTENT_COLOR, children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_editor6.ErrorBoundary, { children: areas2.content }) })
              }
            ),
            !isMobileViewport && areas2.edit && canvas !== "edit" && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
              "div",
              {
                className: "edit-site-layout__area",
                style: {
                  maxWidth: widths?.edit
                },
                children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_theme.ThemeProvider, { color: CONTENT_COLOR, children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_editor6.ErrorBoundary, { children: areas2.edit }) })
              }
            ),
            !isMobileViewport && areas2.preview && /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)("div", { className: "edit-site-layout__canvas-container", children: [
              canvasResizer,
              !!canvasSize.width && /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
                "div",
                {
                  className: clsx_default(
                    "edit-site-layout__canvas",
                    {
                      "is-right-aligned": isResizableFrameOversized
                    }
                  ),
                  ref: animationRef,
                  children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_editor6.ErrorBoundary, { children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
                    resizable_frame_default,
                    {
                      isReady: !isEditorLoading,
                      isFullWidth: canvas === "edit",
                      defaultSize: {
                        width: canvasSize.width - 24,
                        height: canvasSize.height
                      },
                      isOversized: isResizableFrameOversized,
                      setIsOversized: setIsResizableFrameOversized,
                      innerContentStyle: {
                        background: gradientValue ?? backgroundColor
                      },
                      children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
                        import_theme.ThemeProvider,
                        {
                          color: CONTENT_COLOR,
                          children: areas2.preview
                        }
                      )
                    }
                  ) })
                }
              )
            ] })
          ] })
        }
      )
    ] });
  }
  function LayoutWithGlobalStylesProvider(props) {
    const themeColors = (0, import_element44.useMemo)(getAdminThemeColors, []);
    const { createErrorNotice } = (0, import_data12.useDispatch)(import_notices.store);
    function onPluginAreaError(name2) {
      createErrorNotice(
        (0, import_i18n7.sprintf)(
          /* translators: %s: plugin name */
          (0, import_i18n7.__)(
            'The "%s" plugin has encountered an error and cannot be rendered.'
          ),
          name2
        )
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_components6.SlotFillProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(tooltip_exports.Provider, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_plugins2.PluginArea, { onError: onPluginAreaError }),
      /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(import_theme.ThemeProvider, { color: themeColors, children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Layout, { ...props }) })
    ] }) });
  }

  // packages/edit-site/build-module/hooks/commands/use-common-commands.mjs
  var import_element45 = __toESM(require_element(), 1);
  var import_data13 = __toESM(require_data(), 1);
  var import_i18n8 = __toESM(require_i18n(), 1);
  var import_commands = __toESM(require_commands(), 1);
  var import_router7 = __toESM(require_router(), 1);
  var import_preferences4 = __toESM(require_preferences(), 1);
  var import_core_data11 = __toESM(require_core_data(), 1);
  var import_editor7 = __toESM(require_editor(), 1);
  var { useHistory: useHistory4, useLocation: useLocation7 } = unlock(import_router7.privateApis);
  var { useGlobalStyles } = unlock(import_editor7.privateApis);
  var getGlobalStylesToggleWelcomeGuideCommands = () => function useGlobalStylesToggleWelcomeGuideCommands() {
    const { openGeneralSidebar: openGeneralSidebar2 } = unlock((0, import_data13.useDispatch)(store));
    const { params } = useLocation7();
    const { canvas = "view" } = params;
    const { set: set3 } = (0, import_data13.useDispatch)(import_preferences4.store);
    const history = useHistory4();
    const isBlockBasedTheme = (0, import_data13.useSelect)((select4) => {
      return select4(import_core_data11.store).getCurrentTheme().is_block_theme;
    }, []);
    const commands = (0, import_element45.useMemo)(() => {
      if (!isBlockBasedTheme) {
        return [];
      }
      return [
        {
          name: "core/edit-site/toggle-styles-welcome-guide",
          label: (0, import_i18n8.__)("Learn about styles"),
          callback: ({ close }) => {
            close();
            if (canvas !== "edit") {
              history.navigate("/styles?canvas=edit", {
                transition: "canvas-mode-edit-transition"
              });
            }
            openGeneralSidebar2("edit-site/global-styles");
            set3("core/edit-site", "welcomeGuideStyles", true);
            setTimeout(() => {
              set3("core/edit-site", "welcomeGuideStyles", true);
            }, 500);
          },
          icon: help_default
        }
      ];
    }, [history, openGeneralSidebar2, canvas, isBlockBasedTheme, set3]);
    return {
      isLoading: false,
      commands
    };
  };
  var getGlobalStylesResetCommands = () => function useGlobalStylesResetCommands() {
    const { user, setUser } = useGlobalStyles();
    const canReset = !!user && (Object.keys(user?.styles ?? {}).length > 0 || Object.keys(user?.settings ?? {}).length > 0);
    const commands = (0, import_element45.useMemo)(() => {
      if (!canReset) {
        return [];
      }
      return [
        {
          name: "core/edit-site/reset-global-styles",
          label: (0, import_i18n8.__)("Reset styles"),
          icon: (0, import_i18n8.isRTL)() ? rotate_right_default : rotate_left_default,
          callback: ({ close }) => {
            close();
            setUser({ styles: {}, settings: {} });
          }
        }
      ];
    }, [canReset, setUser]);
    return {
      isLoading: false,
      commands
    };
  };
  var getGlobalStylesOpenRevisionsCommands = () => function useGlobalStylesOpenRevisionsCommands() {
    const { openGeneralSidebar: openGeneralSidebar2 } = unlock((0, import_data13.useDispatch)(store));
    const { setStylesPath } = unlock((0, import_data13.useDispatch)(import_editor7.store));
    const { params } = useLocation7();
    const { canvas = "view" } = params;
    const history = useHistory4();
    const hasRevisions = (0, import_data13.useSelect)((select4) => {
      const { getEntityRecord, __experimentalGetCurrentGlobalStylesId } = select4(import_core_data11.store);
      const globalStylesId = __experimentalGetCurrentGlobalStylesId();
      const globalStyles = globalStylesId ? getEntityRecord("root", "globalStyles", globalStylesId) : void 0;
      return !!globalStyles?._links?.["version-history"]?.[0]?.count;
    }, []);
    const commands = (0, import_element45.useMemo)(() => {
      if (!hasRevisions) {
        return [];
      }
      return [
        {
          name: "core/edit-site/open-styles-revisions",
          label: (0, import_i18n8.__)("Open style revisions"),
          icon: backup_default,
          callback: ({ close }) => {
            close();
            if (canvas !== "edit") {
              history.navigate("/styles?canvas=edit", {
                transition: "canvas-mode-edit-transition"
              });
            }
            openGeneralSidebar2("edit-site/global-styles");
            setStylesPath("/revisions");
          }
        }
      ];
    }, [
      history,
      openGeneralSidebar2,
      setStylesPath,
      hasRevisions,
      canvas
    ]);
    return {
      isLoading: false,
      commands
    };
  };
  function useCommonCommands() {
    (0, import_commands.useCommandLoader)({
      name: "core/edit-site/toggle-styles-welcome-guide",
      hook: getGlobalStylesToggleWelcomeGuideCommands()
    });
    (0, import_commands.useCommandLoader)({
      name: "core/edit-site/reset-global-styles",
      hook: getGlobalStylesResetCommands()
    });
    (0, import_commands.useCommandLoader)({
      name: "core/edit-site/open-styles-revisions",
      hook: getGlobalStylesOpenRevisionsCommands()
    });
  }

  // packages/edit-site/build-module/hooks/commands/use-set-command-context.mjs
  var import_data14 = __toESM(require_data(), 1);
  var import_commands2 = __toESM(require_commands(), 1);
  var import_block_editor3 = __toESM(require_block_editor(), 1);
  var import_router8 = __toESM(require_router(), 1);
  var { useCommandContext } = unlock(import_commands2.privateApis);
  var { useLocation: useLocation8 } = unlock(import_router8.privateApis);
  function useSetCommandContext() {
    const { query = {} } = useLocation8();
    const { canvas = "view" } = query;
    const hasBlockSelected = (0, import_data14.useSelect)((select4) => {
      return select4(import_block_editor3.store).getBlockSelectionStart();
    }, []);
    let commandContext = "site-editor";
    if (canvas === "edit") {
      commandContext = "entity-edit";
    }
    if (hasBlockSelected) {
      commandContext = "block-selection-edit";
    }
    useCommandContext(commandContext);
  }

  // packages/edit-site/build-module/components/site-editor-routes/index.mjs
  var import_data87 = __toESM(require_data(), 1);
  var import_element198 = __toESM(require_element(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-main/index.mjs
  var import_components10 = __toESM(require_components(), 1);
  var import_i18n11 = __toESM(require_i18n(), 1);
  var import_data16 = __toESM(require_data(), 1);
  var import_core_data13 = __toESM(require_core_data(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen/index.mjs
  var import_components8 = __toESM(require_components(), 1);
  var import_i18n9 = __toESM(require_i18n(), 1);
  var import_core_data12 = __toESM(require_core_data(), 1);
  var import_data15 = __toESM(require_data(), 1);
  var import_router9 = __toESM(require_router(), 1);
  var import_element46 = __toESM(require_element(), 1);

  // packages/edit-site/build-module/components/sidebar-button/index.mjs
  var import_components7 = __toESM(require_components(), 1);
  var import_jsx_runtime105 = __toESM(require_jsx_runtime(), 1);
  function SidebarButton(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(
      import_components7.Button,
      {
        size: "compact",
        ...props,
        className: clsx_default("edit-site-sidebar-button", props.className)
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen/index.mjs
  var import_jsx_runtime106 = __toESM(require_jsx_runtime(), 1);
  var { useHistory: useHistory5, useLocation: useLocation9 } = unlock(import_router9.privateApis);
  function SidebarNavigationScreen({
    isRoot,
    title,
    actions,
    content,
    footer,
    description,
    backPath: backPathProp
  }) {
    const { dashboardLink, dashboardLinkText, previewingThemeName } = (0, import_data15.useSelect)(
      (select4) => {
        const { getSettings: getSettings7 } = unlock(select4(store));
        const currentlyPreviewingThemeId = currentlyPreviewingTheme();
        return {
          dashboardLink: getSettings7().__experimentalDashboardLink,
          dashboardLinkText: getSettings7().__experimentalDashboardLinkText,
          // Do not call `getTheme` with null, it will cause a request to
          // the server.
          previewingThemeName: currentlyPreviewingThemeId ? select4(import_core_data12.store).getTheme(currentlyPreviewingThemeId)?.name?.rendered : void 0
        };
      },
      []
    );
    const location = useLocation9();
    const history = useHistory5();
    const { navigate } = (0, import_element46.useContext)(SidebarNavigationContext);
    const backPath = backPathProp ?? location.state?.backPath;
    const icon = (0, import_i18n9.isRTL)() ? chevron_right_default : chevron_left_default;
    return /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(import_jsx_runtime106.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(
        import_components8.__experimentalVStack,
        {
          className: clsx_default("edit-site-sidebar-navigation-screen__main", {
            "has-footer": !!footer
          }),
          spacing: 0,
          justify: "flex-start",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(
              import_components8.__experimentalHStack,
              {
                spacing: 3,
                alignment: "flex-start",
                className: "edit-site-sidebar-navigation-screen__title-icon",
                children: [
                  !isRoot && /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(
                    SidebarButton,
                    {
                      onClick: () => {
                        history.navigate(backPath);
                        navigate("back");
                      },
                      icon,
                      label: (0, import_i18n9.__)("Back"),
                      showTooltip: false
                    }
                  ),
                  isRoot && /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(
                    SidebarButton,
                    {
                      icon,
                      label: dashboardLinkText || (0, import_i18n9.__)("Go to the Dashboard"),
                      href: dashboardLink
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(
                    import_components8.__experimentalHeading,
                    {
                      className: "edit-site-sidebar-navigation-screen__title",
                      level: 1,
                      size: 20,
                      children: !isPreviewingTheme() ? title : (0, import_i18n9.sprintf)(
                        /* translators: 1: theme name. 2: title */
                        (0, import_i18n9.__)("Previewing %1$s: %2$s"),
                        previewingThemeName,
                        title
                      )
                    }
                  ),
                  actions && /* @__PURE__ */ (0, import_jsx_runtime106.jsx)("div", { className: "edit-site-sidebar-navigation-screen__actions", children: actions })
                ]
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)("div", { className: "edit-site-sidebar-navigation-screen__content", children: [
              description && /* @__PURE__ */ (0, import_jsx_runtime106.jsx)("div", { className: "edit-site-sidebar-navigation-screen__description", children: description }),
              content
            ] })
          ]
        }
      ),
      footer && /* @__PURE__ */ (0, import_jsx_runtime106.jsx)("footer", { className: "edit-site-sidebar-navigation-screen__footer", children: footer })
    ] });
  }

  // packages/edit-site/build-module/components/sidebar-navigation-item/index.mjs
  var import_components9 = __toESM(require_components(), 1);
  var import_i18n10 = __toESM(require_i18n(), 1);
  var import_router10 = __toESM(require_router(), 1);
  var import_element47 = __toESM(require_element(), 1);
  var import_jsx_runtime107 = __toESM(require_jsx_runtime(), 1);
  var { useHistory: useHistory6, useLink, useLocation: useLocation10 } = unlock(import_router10.privateApis);
  function SidebarNavigationItem({
    isHidden: isHidden2 = false,
    ...props
  }) {
    if (isHidden2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(SidebarNavigationItemContent, { ...props });
  }
  function SidebarNavigationItemContent({
    className,
    icon,
    withChevron = false,
    suffix,
    uid,
    to: to2,
    onClick,
    activeOnRouteName,
    children,
    ...props
  }) {
    const history = useHistory6();
    const linkProps = useLink(to2);
    const { name: name2 } = useLocation10();
    const { navigate } = (0, import_element47.useContext)(SidebarNavigationContext);
    const isActive = activeOnRouteName && name2 === activeOnRouteName;
    function handleClick(e2) {
      if (onClick) {
        onClick(e2);
        navigate("forward");
      } else if (to2) {
        e2.preventDefault();
        history.navigate(to2);
        navigate("forward", `[id="${uid}"]`);
      }
    }
    return /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(
      import_components9.__experimentalItem,
      {
        className: clsx_default(
          "edit-site-sidebar-navigation-item",
          { "with-suffix": !withChevron && suffix },
          className
        ),
        id: uid,
        onClick: handleClick,
        href: to2 ? linkProps.href : void 0,
        "aria-current": isActive ? true : void 0,
        ...props,
        children: /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(Stack, { direction: "row", align: "center", justify: "start", gap: "sm", children: [
          icon && /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(
            icon_default,
            {
              style: { fill: "currentcolor" },
              icon,
              size: 24
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(import_components9.FlexBlock, { children }),
          withChevron && /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(
            icon_default,
            {
              icon: (0, import_i18n10.isRTL)() ? chevron_left_small_default : chevron_right_small_default,
              className: "edit-site-sidebar-navigation-item__drilldown-indicator",
              size: 24
            }
          ),
          !withChevron && suffix
        ] })
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-main/index.mjs
  var import_jsx_runtime108 = __toESM(require_jsx_runtime(), 1);
  function MainSidebarNavigationContent({ isBlockBasedTheme = true }) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsxs)(import_components10.__experimentalItemGroup, { className: "edit-site-sidebar-navigation-screen-main", children: [
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
        SidebarNavigationItem,
        {
          to: "/identity",
          uid: "identity-navigation-item",
          icon: site_logo_default,
          activeOnRouteName: "identity",
          isHidden: !isBlockBasedTheme,
          children: (0, import_i18n11._x)("Identity", "site identity")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
        SidebarNavigationItem,
        {
          to: isBlockBasedTheme ? "/styles" : "/stylebook",
          uid: isBlockBasedTheme ? "global-styles-navigation-item" : "stylebook-navigation-item",
          icon: styles_default,
          activeOnRouteName: isBlockBasedTheme ? "styles" : void 0,
          withChevron: !isBlockBasedTheme,
          children: (0, import_i18n11.__)("Styles")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
        SidebarNavigationItem,
        {
          uid: "page-navigation-item",
          to: "/page",
          withChevron: true,
          icon: page_default,
          isHidden: !isBlockBasedTheme,
          children: (0, import_i18n11.__)("Pages")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
        SidebarNavigationItem,
        {
          uid: "navigation-navigation-item",
          to: "/navigation",
          withChevron: true,
          icon: navigation_default,
          isHidden: !isBlockBasedTheme,
          children: (0, import_i18n11.__)("Navigation")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
        SidebarNavigationItem,
        {
          uid: "patterns-navigation-item",
          to: "/pattern",
          withChevron: true,
          icon: symbol_default,
          children: (0, import_i18n11.__)("Patterns")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
        SidebarNavigationItem,
        {
          uid: "template-navigation-item",
          to: "/template",
          withChevron: true,
          icon: layout_default,
          isHidden: !isBlockBasedTheme,
          children: (0, import_i18n11.__)("Templates")
        }
      )
    ] });
  }
  function SidebarNavigationScreenMain({ customDescription }) {
    const isBlockBasedTheme = (0, import_data16.useSelect)(
      (select4) => select4(import_core_data13.store).getCurrentTheme()?.is_block_theme,
      []
    );
    let description;
    if (customDescription) {
      description = customDescription;
    } else if (isBlockBasedTheme) {
      description = (0, import_i18n11.__)(
        "Customize the appearance of your website using the block editor."
      );
    } else {
      description = (0, import_i18n11.__)(
        "Explore block styles and patterns to refine your site."
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      SidebarNavigationScreen,
      {
        isRoot: true,
        title: (0, import_i18n11.__)("Design"),
        description,
        content: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
          MainSidebarNavigationContent,
          {
            isBlockBasedTheme
          }
        )
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-unsupported/index.mjs
  var import_i18n12 = __toESM(require_i18n(), 1);
  var import_components11 = __toESM(require_components(), 1);
  var import_jsx_runtime109 = __toESM(require_jsx_runtime(), 1);
  function SidebarNavigationScreenUnsupported() {
    return /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(import_components11.__experimentalSpacer, { padding: 3, children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(import_components11.Notice, { status: "warning", isDismissible: false, children: (0, import_i18n12.__)(
      "The theme you are currently using does not support this screen."
    ) }) });
  }

  // packages/edit-site/build-module/components/editor/index.mjs
  var import_data34 = __toESM(require_data(), 1);
  var import_components19 = __toESM(require_components(), 1);
  var import_compose4 = __toESM(require_compose(), 1);
  var import_editor19 = __toESM(require_editor(), 1);
  var import_i18n22 = __toESM(require_i18n(), 1);
  var import_core_data22 = __toESM(require_core_data(), 1);
  var import_block_library = __toESM(require_block_library(), 1);
  var import_element56 = __toESM(require_element(), 1);
  var import_notices3 = __toESM(require_notices(), 1);
  var import_router17 = __toESM(require_router(), 1);
  var import_html_entities3 = __toESM(require_html_entities(), 1);
  var import_block_editor5 = __toESM(require_block_editor(), 1);
  var import_url8 = __toESM(require_url(), 1);

  // packages/edit-site/build-module/components/welcome-guide/editor.mjs
  var import_data17 = __toESM(require_data(), 1);
  var import_components12 = __toESM(require_components(), 1);
  var import_i18n13 = __toESM(require_i18n(), 1);
  var import_element48 = __toESM(require_element(), 1);
  var import_preferences5 = __toESM(require_preferences(), 1);
  var import_core_data14 = __toESM(require_core_data(), 1);

  // packages/edit-site/build-module/components/welcome-guide/image.mjs
  var import_jsx_runtime110 = __toESM(require_jsx_runtime(), 1);
  function WelcomeGuideImage({ nonAnimatedSrc, animatedSrc }) {
    return /* @__PURE__ */ (0, import_jsx_runtime110.jsxs)("picture", { className: "edit-site-welcome-guide__image", children: [
      /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(
        "source",
        {
          srcSet: nonAnimatedSrc,
          media: "(prefers-reduced-motion: reduce)"
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime110.jsx)("img", { src: animatedSrc, width: "312", height: "240", alt: "" })
    ] });
  }

  // packages/edit-site/build-module/components/welcome-guide/editor.mjs
  var import_jsx_runtime111 = __toESM(require_jsx_runtime(), 1);
  function WelcomeGuideEditor() {
    const { toggle } = (0, import_data17.useDispatch)(import_preferences5.store);
    const { isActive, isBlockBasedTheme } = (0, import_data17.useSelect)((select4) => {
      return {
        isActive: !!select4(import_preferences5.store).get(
          "core/edit-site",
          "welcomeGuide"
        ),
        isBlockBasedTheme: select4(import_core_data14.store).getCurrentTheme()?.is_block_theme
      };
    }, []);
    if (!isActive || !isBlockBasedTheme) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
      import_components12.Guide,
      {
        className: "edit-site-welcome-guide guide-editor",
        contentLabel: (0, import_i18n13.__)("Welcome to the site editor"),
        finishButtonText: (0, import_i18n13.__)("Get started"),
        onFinish: () => toggle("core/edit-site", "welcomeGuide"),
        pages: [
          {
            image: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
              WelcomeGuideImage,
              {
                nonAnimatedSrc: "https://s.w.org/images/block-editor/edit-your-site.svg?1",
                animatedSrc: "https://s.w.org/images/block-editor/edit-your-site.gif?1"
              }
            ),
            content: /* @__PURE__ */ (0, import_jsx_runtime111.jsxs)(import_jsx_runtime111.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime111.jsx)("h1", { className: "edit-site-welcome-guide__heading", children: (0, import_i18n13.__)("Edit your site") }),
              /* @__PURE__ */ (0, import_jsx_runtime111.jsx)("p", { className: "edit-site-welcome-guide__text", children: (0, import_i18n13.__)(
                "Design everything on your site \u2014 from the header right down to the footer \u2014 using blocks."
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime111.jsx)("p", { className: "edit-site-welcome-guide__text", children: (0, import_element48.createInterpolateElement)(
                (0, import_i18n13.__)(
                  "Click <StylesIconImage /> to start designing your blocks, and choose your typography, layout, and colors."
                ),
                {
                  StylesIconImage: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
                    "img",
                    {
                      alt: (0, import_i18n13.__)("styles"),
                      src: "data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 24 24' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12 4c-4.4 0-8 3.6-8 8v.1c0 4.1 3.2 7.5 7.2 7.9h.8c4.4 0 8-3.6 8-8s-3.6-8-8-8zm0 15V5c3.9 0 7 3.1 7 7s-3.1 7-7 7z' fill='%231E1E1E'/%3E%3C/svg%3E%0A"
                    }
                  )
                }
              ) })
            ] })
          }
        ]
      }
    );
  }

  // packages/edit-site/build-module/components/welcome-guide/page.mjs
  var import_data18 = __toESM(require_data(), 1);
  var import_components13 = __toESM(require_components(), 1);
  var import_i18n14 = __toESM(require_i18n(), 1);
  var import_preferences6 = __toESM(require_preferences(), 1);
  var import_jsx_runtime112 = __toESM(require_jsx_runtime(), 1);
  function WelcomeGuidePage() {
    const { toggle } = (0, import_data18.useDispatch)(import_preferences6.store);
    const isVisible2 = (0, import_data18.useSelect)((select4) => {
      const isPageActive = !!select4(import_preferences6.store).get(
        "core/edit-site",
        "welcomeGuidePage"
      );
      const isEditorActive = !!select4(import_preferences6.store).get(
        "core/edit-site",
        "welcomeGuide"
      );
      return isPageActive && !isEditorActive;
    }, []);
    if (!isVisible2) {
      return null;
    }
    const heading = (0, import_i18n14.__)("Editing a page");
    return /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(
      import_components13.Guide,
      {
        className: "edit-site-welcome-guide guide-page",
        contentLabel: heading,
        finishButtonText: (0, import_i18n14.__)("Continue"),
        onFinish: () => toggle("core/edit-site", "welcomeGuidePage"),
        pages: [
          {
            image: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(
              "video",
              {
                className: "edit-site-welcome-guide__video",
                autoPlay: true,
                loop: true,
                muted: true,
                width: "312",
                height: "240",
                children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(
                  "source",
                  {
                    src: "https://s.w.org/images/block-editor/editing-your-page.mp4",
                    type: "video/mp4"
                  }
                )
              }
            ),
            content: /* @__PURE__ */ (0, import_jsx_runtime112.jsxs)(import_jsx_runtime112.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime112.jsx)("h1", { className: "edit-site-welcome-guide__heading", children: heading }),
              /* @__PURE__ */ (0, import_jsx_runtime112.jsx)("p", { className: "edit-site-welcome-guide__text", children: (0, import_i18n14.__)(
                // eslint-disable-next-line no-restricted-syntax -- 'sidebar' is a common web design term for layouts
                "It\u2019s now possible to edit page content in the site editor. To customize other parts of the page like the header and footer switch to editing the template using the settings sidebar."
              ) })
            ] })
          }
        ]
      }
    );
  }

  // packages/edit-site/build-module/components/welcome-guide/template.mjs
  var import_data19 = __toESM(require_data(), 1);
  var import_components14 = __toESM(require_components(), 1);
  var import_i18n15 = __toESM(require_i18n(), 1);
  var import_preferences7 = __toESM(require_preferences(), 1);
  var import_editor8 = __toESM(require_editor(), 1);
  var import_jsx_runtime113 = __toESM(require_jsx_runtime(), 1);
  function WelcomeGuideTemplate() {
    const { toggle } = (0, import_data19.useDispatch)(import_preferences7.store);
    const { isActive, hasPreviousEntity } = (0, import_data19.useSelect)((select4) => {
      const { getEditorSettings } = select4(import_editor8.store);
      const { get } = select4(import_preferences7.store);
      return {
        isActive: get("core/edit-site", "welcomeGuideTemplate"),
        hasPreviousEntity: !!getEditorSettings().onNavigateToPreviousEntityRecord
      };
    }, []);
    const isVisible2 = isActive && hasPreviousEntity;
    if (!isVisible2) {
      return null;
    }
    const heading = (0, import_i18n15.__)("Editing a template");
    return /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(
      import_components14.Guide,
      {
        className: "edit-site-welcome-guide guide-template",
        contentLabel: heading,
        finishButtonText: (0, import_i18n15.__)("Continue"),
        onFinish: () => toggle("core/edit-site", "welcomeGuideTemplate"),
        pages: [
          {
            image: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(
              "video",
              {
                className: "edit-site-welcome-guide__video",
                autoPlay: true,
                loop: true,
                muted: true,
                width: "312",
                height: "240",
                children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(
                  "source",
                  {
                    src: "https://s.w.org/images/block-editor/editing-your-template.mp4",
                    type: "video/mp4"
                  }
                )
              }
            ),
            content: /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(import_jsx_runtime113.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime113.jsx)("h1", { className: "edit-site-welcome-guide__heading", children: heading }),
              /* @__PURE__ */ (0, import_jsx_runtime113.jsx)("p", { className: "edit-site-welcome-guide__text", children: (0, import_i18n15.__)(
                "Note that the same template can be used by multiple pages, so any changes made here may affect other pages on the site. To switch back to editing the page content click the \u2018Back\u2019 button in the toolbar."
              ) })
            ] })
          }
        ]
      }
    );
  }

  // packages/edit-site/build-module/components/welcome-guide/index.mjs
  var import_jsx_runtime114 = __toESM(require_jsx_runtime(), 1);
  function WelcomeGuide({ postType: postType2 }) {
    return /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(import_jsx_runtime114.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(WelcomeGuideEditor, {}),
      postType2 === "page" && /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(WelcomeGuidePage, {}),
      postType2 === "wp_template" && /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(WelcomeGuideTemplate, {})
    ] });
  }

  // packages/edit-site/build-module/components/canvas-loader/index.mjs
  var import_components15 = __toESM(require_components(), 1);
  var import_core_data15 = __toESM(require_core_data(), 1);
  var import_data20 = __toESM(require_data(), 1);
  var import_editor10 = __toESM(require_editor(), 1);
  var import_jsx_runtime115 = __toESM(require_jsx_runtime(), 1);
  var { Theme } = unlock(import_components15.privateApis);
  var { useStyle: useStyle2 } = unlock(import_editor10.privateApis);
  function CanvasLoader({ id }) {
    const textColor = useStyle2("color.text");
    const backgroundColor = useStyle2("color.background");
    const { elapsed, total } = (0, import_data20.useSelect)((select4) => {
      const selectorsByStatus = select4(import_core_data15.store).countSelectorsByStatus();
      const resolving = selectorsByStatus.resolving ?? 0;
      const finished = selectorsByStatus.finished ?? 0;
      return {
        elapsed: finished,
        total: finished + resolving
      };
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime115.jsx)("div", { className: "edit-site-canvas-loader", children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Theme, { accent: textColor, background: backgroundColor, children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(import_components15.ProgressBar, { id, max: total, value: elapsed }) }) });
  }

  // packages/edit-site/build-module/components/block-editor/use-site-editor-settings.mjs
  var import_data24 = __toESM(require_data(), 1);
  var import_element51 = __toESM(require_element(), 1);
  var import_router13 = __toESM(require_router(), 1);
  var import_compose3 = __toESM(require_compose(), 1);
  var import_editor13 = __toESM(require_editor(), 1);

  // packages/global-styles-engine/build-module/utils/object.mjs
  function setImmutably(object, path, value) {
    path = Array.isArray(path) ? [...path] : [path];
    object = Array.isArray(object) ? [...object] : { ...object };
    const leaf = path.pop();
    let prev = object;
    for (const key of path) {
      const lvl = prev[key];
      prev = prev[key] = Array.isArray(lvl) ? [...lvl] : { ...lvl };
    }
    prev[leaf] = value;
    return object;
  }
  var getValueFromObjectPath = (object, path, defaultValue2) => {
    const arrayPath = Array.isArray(path) ? path : path.split(".");
    let value = object;
    arrayPath.forEach((fieldName) => {
      value = value?.[fieldName];
    });
    return value ?? defaultValue2;
  };

  // packages/global-styles-engine/build-module/settings/get-setting.mjs
  var VALID_SETTINGS = [
    "appearanceTools",
    "useRootPaddingAwareAlignments",
    "background.backgroundImage",
    "background.backgroundRepeat",
    "background.backgroundSize",
    "background.backgroundPosition",
    "background.gradient",
    "border.color",
    "border.radius",
    "border.radiusSizes",
    "border.style",
    "border.width",
    "shadow.presets",
    "shadow.defaultPresets",
    "color.background",
    "color.button",
    "color.caption",
    "color.custom",
    "color.customDuotone",
    "color.customGradient",
    "color.defaultDuotone",
    "color.defaultGradients",
    "color.defaultPalette",
    "color.duotone",
    "color.gradients",
    "color.heading",
    "color.link",
    "color.palette",
    "color.text",
    "custom",
    "dimensions.aspectRatio",
    "dimensions.height",
    "dimensions.minHeight",
    "dimensions.minWidth",
    "dimensions.width",
    "dimensions.dimensionSizes",
    "layout.contentSize",
    "layout.definitions",
    "layout.wideSize",
    "lightbox.enabled",
    "lightbox.allowEditing",
    "position.fixed",
    "position.sticky",
    "spacing.customSpacingSize",
    "spacing.defaultSpacingSizes",
    "spacing.spacingSizes",
    "spacing.spacingScale",
    "spacing.blockGap",
    "spacing.margin",
    "spacing.padding",
    "spacing.units",
    "typography.fluid",
    "typography.customFontSize",
    "typography.defaultFontSizes",
    "typography.dropCap",
    "typography.fontFamilies",
    "typography.fontSizes",
    "typography.fontStyle",
    "typography.fontWeight",
    "typography.letterSpacing",
    "typography.lineHeight",
    "typography.textAlign",
    "typography.textColumns",
    "typography.textDecoration",
    "typography.textIndent",
    "typography.textTransform",
    "typography.writingMode",
    "viewport.mobile",
    "viewport.tablet"
  ];
  function getSetting(globalStyles, path, blockName) {
    const appendedBlockPath = blockName ? ".blocks." + blockName : "";
    const appendedPropertyPath = path ? "." + path : "";
    const contextualPath = `settings${appendedBlockPath}${appendedPropertyPath}`;
    const globalPath = `settings${appendedPropertyPath}`;
    if (path) {
      return getValueFromObjectPath(globalStyles, contextualPath) ?? getValueFromObjectPath(globalStyles, globalPath);
    }
    let result = {};
    VALID_SETTINGS.forEach((setting) => {
      const value = getValueFromObjectPath(
        globalStyles,
        `settings${appendedBlockPath}.${setting}`
      ) ?? getValueFromObjectPath(globalStyles, `settings.${setting}`);
      if (value !== void 0) {
        result = setImmutably(result, setting.split("."), value);
      }
    });
    return result;
  }

  // packages/global-styles-engine/build-module/settings/set-setting.mjs
  function setSetting(globalStyles, path, newValue, blockName) {
    const appendedBlockPath = blockName ? ".blocks." + blockName : "";
    const appendedPropertyPath = path ? "." + path : "";
    const finalPath = `settings${appendedBlockPath}${appendedPropertyPath}`;
    return setImmutably(
      globalStyles,
      finalPath.split("."),
      newValue
    );
  }

  // packages/global-styles-engine/build-module/utils/common.mjs
  var import_style_engine = __toESM(require_style_engine(), 1);

  // packages/global-styles-engine/build-module/utils/fluid.mjs
  var DEFAULT_MAXIMUM_VIEWPORT_WIDTH = "1600px";
  var DEFAULT_MINIMUM_VIEWPORT_WIDTH = "320px";
  var DEFAULT_SCALE_FACTOR = 1;
  var DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MIN = 0.25;
  var DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MAX = 0.75;
  var DEFAULT_MINIMUM_FONT_SIZE_LIMIT = "14px";
  function getComputedFluidTypographyValue({
    minimumFontSize,
    maximumFontSize,
    fontSize,
    minimumViewportWidth = DEFAULT_MINIMUM_VIEWPORT_WIDTH,
    maximumViewportWidth = DEFAULT_MAXIMUM_VIEWPORT_WIDTH,
    scaleFactor = DEFAULT_SCALE_FACTOR,
    minimumFontSizeLimit
  }) {
    minimumFontSizeLimit = !!getTypographyValueAndUnit(minimumFontSizeLimit) ? minimumFontSizeLimit : DEFAULT_MINIMUM_FONT_SIZE_LIMIT;
    if (fontSize) {
      const fontSizeParsed = getTypographyValueAndUnit(fontSize);
      if (!fontSizeParsed?.unit || !fontSizeParsed?.value) {
        return null;
      }
      const minimumFontSizeLimitParsed = getTypographyValueAndUnit(
        minimumFontSizeLimit,
        {
          coerceTo: fontSizeParsed.unit
        }
      );
      if (!!minimumFontSizeLimitParsed?.value && !minimumFontSize && !maximumFontSize) {
        if (fontSizeParsed?.value <= minimumFontSizeLimitParsed?.value) {
          return null;
        }
      }
      if (!maximumFontSize) {
        maximumFontSize = `${fontSizeParsed.value}${fontSizeParsed.unit}`;
      }
      if (!minimumFontSize) {
        const fontSizeValueInPx = fontSizeParsed.unit === "px" ? fontSizeParsed.value : fontSizeParsed.value * 16;
        const minimumFontSizeFactor = Math.min(
          Math.max(
            1 - 0.075 * Math.log2(fontSizeValueInPx),
            DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MIN
          ),
          DEFAULT_MINIMUM_FONT_SIZE_FACTOR_MAX
        );
        const calculatedMinimumFontSize = roundToPrecision(
          fontSizeParsed.value * minimumFontSizeFactor,
          3
        );
        if (!!minimumFontSizeLimitParsed?.value && calculatedMinimumFontSize < minimumFontSizeLimitParsed?.value) {
          minimumFontSize = `${minimumFontSizeLimitParsed.value}${minimumFontSizeLimitParsed.unit}`;
        } else {
          minimumFontSize = `${calculatedMinimumFontSize}${fontSizeParsed.unit}`;
        }
      }
    }
    const minimumFontSizeParsed = getTypographyValueAndUnit(minimumFontSize);
    const fontSizeUnit = minimumFontSizeParsed?.unit || "rem";
    const maximumFontSizeParsed = getTypographyValueAndUnit(maximumFontSize, {
      coerceTo: fontSizeUnit
    });
    if (!minimumFontSizeParsed || !maximumFontSizeParsed) {
      return null;
    }
    const minimumFontSizeRem = getTypographyValueAndUnit(minimumFontSize, {
      coerceTo: "rem"
    });
    const maximumViewportWidthParsed = getTypographyValueAndUnit(
      maximumViewportWidth,
      { coerceTo: fontSizeUnit }
    );
    const minimumViewportWidthParsed = getTypographyValueAndUnit(
      minimumViewportWidth,
      { coerceTo: fontSizeUnit }
    );
    if (!maximumViewportWidthParsed || !minimumViewportWidthParsed || !minimumFontSizeRem) {
      return null;
    }
    const linearDenominator = maximumViewportWidthParsed.value - minimumViewportWidthParsed.value;
    if (!linearDenominator) {
      return null;
    }
    const minViewportWidthOffsetValue = roundToPrecision(
      minimumViewportWidthParsed.value / 100,
      3
    );
    const viewportWidthOffset = roundToPrecision(minViewportWidthOffsetValue, 3) + fontSizeUnit;
    const linearFactor = 100 * ((maximumFontSizeParsed.value - minimumFontSizeParsed.value) / linearDenominator);
    const linearFactorScaled = roundToPrecision(
      (linearFactor || 1) * scaleFactor,
      3
    );
    const fluidTargetFontSize = `${minimumFontSizeRem.value}${minimumFontSizeRem.unit} + ((1vw - ${viewportWidthOffset}) * ${linearFactorScaled})`;
    return `clamp(${minimumFontSize}, ${fluidTargetFontSize}, ${maximumFontSize})`;
  }
  function getTypographyValueAndUnit(rawValue, options = {}) {
    if (typeof rawValue !== "string" && typeof rawValue !== "number") {
      return null;
    }
    if (isFinite(rawValue)) {
      rawValue = `${rawValue}px`;
    }
    const { coerceTo, rootSizeValue, acceptableUnits } = {
      coerceTo: "",
      // Default browser font size. Later we could inject some JS to compute this `getComputedStyle( document.querySelector( "html" ) ).fontSize`.
      rootSizeValue: 16,
      acceptableUnits: ["rem", "px", "em"],
      ...options
    };
    const acceptableUnitsGroup = acceptableUnits?.join("|");
    const regexUnits = new RegExp(
      `^(\\d*\\.?\\d+)(${acceptableUnitsGroup}){1,1}$`
    );
    const matches = rawValue.toString().match(regexUnits);
    if (!matches || matches.length < 3) {
      return null;
    }
    let [, value, unit] = matches;
    let returnValue = parseFloat(value);
    if ("px" === coerceTo && ("em" === unit || "rem" === unit)) {
      returnValue = returnValue * rootSizeValue;
      unit = coerceTo;
    }
    if ("px" === unit && ("em" === coerceTo || "rem" === coerceTo)) {
      returnValue = returnValue / rootSizeValue;
      unit = coerceTo;
    }
    if (("em" === coerceTo || "rem" === coerceTo) && ("em" === unit || "rem" === unit)) {
      unit = coerceTo;
    }
    if (!unit) {
      return null;
    }
    return {
      value: roundToPrecision(returnValue, 3),
      unit
    };
  }
  function roundToPrecision(value, digits = 3) {
    const base = Math.pow(10, digits);
    return Math.round(value * base) / base;
  }

  // packages/global-styles-engine/build-module/utils/typography.mjs
  function isFluidTypographyEnabled(typographySettings) {
    const fluidSettings = typographySettings?.fluid;
    return true === fluidSettings || fluidSettings && typeof fluidSettings === "object" && Object.keys(fluidSettings).length > 0;
  }
  function getFluidTypographyOptionsFromSettings(settings2) {
    const typographySettings = settings2?.typography ?? {};
    const layoutSettings = settings2?.layout;
    const defaultMaxViewportWidth = getTypographyValueAndUnit(
      layoutSettings?.wideSize
    ) ? layoutSettings?.wideSize : null;
    return isFluidTypographyEnabled(typographySettings) && defaultMaxViewportWidth ? {
      fluid: {
        maxViewportWidth: defaultMaxViewportWidth,
        ...typeof typographySettings.fluid === "object" ? typographySettings.fluid : {}
      }
    } : {
      fluid: typographySettings?.fluid
    };
  }
  function getTypographyFontSizeValue(preset, settings2) {
    const { size: defaultSize } = preset;
    if (!defaultSize || "0" === defaultSize || false === preset?.fluid) {
      return defaultSize;
    }
    if (!isFluidTypographyEnabled(settings2?.typography) && !isFluidTypographyEnabled(preset)) {
      return defaultSize;
    }
    const fluidTypographySettings = getFluidTypographyOptionsFromSettings(settings2)?.fluid ?? {};
    const fluidFontSizeValue = getComputedFluidTypographyValue({
      minimumFontSize: typeof preset?.fluid === "boolean" ? void 0 : preset?.fluid?.min,
      maximumFontSize: typeof preset?.fluid === "boolean" ? void 0 : preset?.fluid?.max,
      fontSize: defaultSize,
      minimumFontSizeLimit: typeof fluidTypographySettings === "object" ? fluidTypographySettings?.minFontSize : void 0,
      maximumViewportWidth: typeof fluidTypographySettings === "object" ? fluidTypographySettings?.maxViewportWidth : void 0,
      minimumViewportWidth: typeof fluidTypographySettings === "object" ? fluidTypographySettings?.minViewportWidth : void 0
    });
    if (!!fluidFontSizeValue) {
      return fluidFontSizeValue;
    }
    return defaultSize;
  }

  // packages/global-styles-engine/build-module/utils/common.mjs
  var ROOT_BLOCK_SELECTOR = "body";
  var ROOT_CSS_PROPERTIES_SELECTOR = ":root";
  function splitSelectorList(selector2) {
    if (!selector2.includes(",")) {
      return [selector2];
    }
    const selectors3 = [];
    let currentSelector = "";
    let parenthesesDepth = 0;
    for (const char of selector2) {
      if (char === "(") {
        parenthesesDepth++;
      } else if (char === ")" && parenthesesDepth > 0) {
        parenthesesDepth--;
      } else if (char === "," && parenthesesDepth === 0) {
        selectors3.push(currentSelector);
        currentSelector = "";
        continue;
      }
      currentSelector += char;
    }
    selectors3.push(currentSelector);
    return selectors3;
  }
  var PRESET_METADATA = [
    {
      path: ["color", "palette"],
      valueKey: "color",
      cssVarInfix: "color",
      classes: [
        { classSuffix: "color", propertyName: "color" },
        {
          classSuffix: "background-color",
          propertyName: "background-color"
        },
        {
          classSuffix: "border-color",
          propertyName: "border-color"
        }
      ]
    },
    {
      path: ["color", "gradients"],
      valueKey: "gradient",
      cssVarInfix: "gradient",
      classes: [
        {
          classSuffix: "gradient-background",
          propertyName: "background"
        }
      ]
    },
    {
      path: ["color", "duotone"],
      valueKey: "colors",
      cssVarInfix: "duotone",
      valueFunc: ({ slug }) => `url( '#wp-duotone-${slug}' )`,
      classes: []
    },
    {
      path: ["shadow", "presets"],
      valueKey: "shadow",
      cssVarInfix: "shadow",
      classes: []
    },
    {
      path: ["typography", "fontSizes"],
      valueFunc: (preset, settings2) => getTypographyFontSizeValue(preset, settings2),
      valueKey: "size",
      cssVarInfix: "font-size",
      classes: [{ classSuffix: "font-size", propertyName: "font-size" }]
    },
    {
      path: ["typography", "fontFamilies"],
      valueKey: "fontFamily",
      cssVarInfix: "font-family",
      classes: [
        { classSuffix: "font-family", propertyName: "font-family" }
      ]
    },
    {
      path: ["spacing", "spacingSizes"],
      valueKey: "size",
      cssVarInfix: "spacing",
      valueFunc: ({ size: size4 }) => size4,
      classes: []
    },
    {
      path: ["border", "radiusSizes"],
      valueKey: "size",
      cssVarInfix: "border-radius",
      classes: []
    },
    {
      path: ["dimensions", "dimensionSizes"],
      valueKey: "size",
      cssVarInfix: "dimension",
      classes: []
    }
  ];
  function scopeSelector(scope, selector2) {
    if (!scope || !selector2) {
      return selector2;
    }
    const scopes = splitSelectorList(scope);
    const selectors3 = splitSelectorList(selector2);
    const selectorsScoped = [];
    scopes.forEach((outer) => {
      selectors3.forEach((inner) => {
        selectorsScoped.push(`${outer.trim()} ${inner.trim()}`);
      });
    });
    return selectorsScoped.join(", ");
  }
  function scopeFeatureSelectors(scope, selectors3) {
    if (!scope || !selectors3) {
      return;
    }
    const featureSelectors = {};
    Object.entries(selectors3).forEach(([feature, selector2]) => {
      if (typeof selector2 === "string") {
        featureSelectors[feature] = scopeSelector(scope, selector2);
      }
      if (typeof selector2 === "object") {
        featureSelectors[feature] = {};
        Object.entries(selector2).forEach(
          ([subfeature, subfeatureSelector]) => {
            featureSelectors[feature][subfeature] = scopeSelector(
              scope,
              subfeatureSelector
            );
          }
        );
      }
    });
    return featureSelectors;
  }
  function appendToSelector(selector2, toAppend) {
    if (!selector2.includes(",")) {
      return selector2 + toAppend;
    }
    const selectors3 = splitSelectorList(selector2);
    const newSelectors = selectors3.map((sel) => sel + toAppend);
    return newSelectors.join(",");
  }
  function getBlockStyleVariationSelector(variation, blockSelector) {
    const variationClass = `.is-style-${variation}`;
    if (!blockSelector) {
      return variationClass;
    }
    const ancestorRegex = /[^\s:]+/;
    const addVariationClass = (match3) => match3 + variationClass;
    const result = splitSelectorList(blockSelector).map(
      (part) => part.replace(ancestorRegex, addVariationClass)
    );
    return result.join(",");
  }
  function getBlockStyleVariationFeatureSelector(variation, featureSelector) {
    const variationClass = `.is-style-${variation}`;
    const selectorParts = splitSelectorList(featureSelector).map(
      (selector2) => {
        const trimmedSelector = selector2.trim();
        const prefix2 = `${variationClass} `;
        if (trimmedSelector.startsWith(prefix2)) {
          return trimmedSelector.slice(prefix2.length);
        }
        return trimmedSelector;
      }
    );
    return getBlockStyleVariationSelector(
      variation,
      selectorParts.join(",")
    );
  }
  function getResolvedRefValue(ruleValue, tree) {
    if (!ruleValue || !tree) {
      return ruleValue;
    }
    if (typeof ruleValue === "object" && "ref" in ruleValue && ruleValue?.ref) {
      const resolvedRuleValue = (0, import_style_engine.getCSSValueFromRawStyle)(
        getValueFromObjectPath(tree, ruleValue.ref)
      );
      if (typeof resolvedRuleValue === "object" && resolvedRuleValue !== null && "ref" in resolvedRuleValue && resolvedRuleValue?.ref) {
        return void 0;
      }
      if (resolvedRuleValue === void 0) {
        return ruleValue;
      }
      return resolvedRuleValue;
    }
    return ruleValue;
  }
  function getResolvedThemeFilePath(file, themeFileURIs) {
    if (!file || !themeFileURIs || !Array.isArray(themeFileURIs)) {
      return file;
    }
    const uri = themeFileURIs.find(
      (themeFileUri) => themeFileUri?.name === file
    );
    if (!uri?.href) {
      return file;
    }
    return uri?.href;
  }
  function getResolvedValue(ruleValue, tree) {
    if (!ruleValue || !tree) {
      return ruleValue;
    }
    const resolvedValue = getResolvedRefValue(ruleValue, tree);
    if (typeof resolvedValue === "object" && resolvedValue !== null && "url" in resolvedValue && resolvedValue?.url) {
      resolvedValue.url = getResolvedThemeFilePath(
        resolvedValue.url,
        tree?._links?.["wp:theme-file"]
      );
    }
    return resolvedValue;
  }
  function findInPresetsBy(settings2, blockName, presetPath = [], presetProperty = "slug", presetValueValue) {
    const orderedPresetsByOrigin = [
      blockName ? getValueFromObjectPath(settings2, [
        "blocks",
        blockName,
        ...presetPath
      ]) : void 0,
      getValueFromObjectPath(settings2, presetPath)
    ].filter(Boolean);
    for (const presetByOrigin of orderedPresetsByOrigin) {
      if (presetByOrigin) {
        const origins = ["custom", "theme", "default"];
        for (const origin of origins) {
          const presets = presetByOrigin[origin];
          if (presets) {
            const presetObject = presets.find(
              (preset) => preset[presetProperty] === presetValueValue
            );
            if (presetObject) {
              if (presetProperty === "slug") {
                return presetObject;
              }
              const highestPresetObjectWithSameSlug = findInPresetsBy(
                settings2,
                blockName,
                presetPath,
                "slug",
                presetObject.slug
              );
              if (highestPresetObjectWithSameSlug[presetProperty] === presetObject[presetProperty]) {
                return presetObject;
              }
              return void 0;
            }
          }
        }
      }
    }
  }
  function getValueFromPresetVariable(features, blockName, variable, [presetType, slug] = []) {
    const metadata = PRESET_METADATA.find(
      (data) => data.cssVarInfix === presetType
    );
    if (!metadata || !features.settings) {
      return variable;
    }
    const presetObject = findInPresetsBy(
      features.settings,
      blockName,
      metadata.path,
      "slug",
      slug
    );
    if (presetObject) {
      const { valueKey } = metadata;
      const result = presetObject[valueKey];
      return getValueFromVariable(features, blockName, result);
    }
    return variable;
  }
  function getValueFromCustomVariable(features, blockName, variable, path = []) {
    const result = (blockName ? getValueFromObjectPath(features?.settings ?? {}, [
      "blocks",
      blockName,
      "custom",
      ...path
    ]) : void 0) ?? getValueFromObjectPath(features?.settings ?? {}, [
      "custom",
      ...path
    ]);
    if (!result) {
      return variable;
    }
    return getValueFromVariable(features, blockName, result);
  }
  function getValueFromVariable(features, blockName, variable) {
    if (!variable || typeof variable !== "string") {
      if (typeof variable === "object" && variable !== null && "ref" in variable && typeof variable.ref === "string") {
        const resolvedVariable = getValueFromObjectPath(
          features,
          variable.ref
        );
        if (!resolvedVariable || typeof resolvedVariable === "object" && "ref" in resolvedVariable) {
          return resolvedVariable;
        }
        variable = resolvedVariable;
      } else {
        return variable;
      }
    }
    const USER_VALUE_PREFIX = "var:";
    const THEME_VALUE_PREFIX = "var(--wp--";
    const THEME_VALUE_SUFFIX = ")";
    let parsedVar;
    if (variable.startsWith(USER_VALUE_PREFIX)) {
      parsedVar = variable.slice(USER_VALUE_PREFIX.length).split("|");
    } else if (variable.startsWith(THEME_VALUE_PREFIX) && variable.endsWith(THEME_VALUE_SUFFIX)) {
      parsedVar = variable.slice(THEME_VALUE_PREFIX.length, -THEME_VALUE_SUFFIX.length).split("--");
    } else {
      return variable;
    }
    const [type, ...path] = parsedVar;
    if (type === "preset") {
      return getValueFromPresetVariable(
        features,
        blockName,
        variable,
        path
      );
    }
    if (type === "custom") {
      return getValueFromCustomVariable(
        features,
        blockName,
        variable,
        path
      );
    }
    return variable;
  }

  // packages/global-styles-engine/build-module/style-state-back-compat.mjs
  var LEGACY_STYLE_STATE_ALIASES = {
    "@mobile": "mobile",
    "@tablet": "tablet",
    "-current": "@current"
  };
  function isObjectRecord(value) {
    return !!value && typeof value === "object" && !Array.isArray(value);
  }
  function normalizeStyleStateNode(node) {
    if (!isObjectRecord(node)) {
      return node;
    }
    let normalized = node;
    Object.entries(LEGACY_STYLE_STATE_ALIASES).forEach(
      ([state, legacyState]) => {
        if (Object.hasOwn(node, legacyState)) {
          if (normalized === node) {
            normalized = { ...node };
          }
          if (!Object.hasOwn(node, state)) {
            normalized[state] = node[legacyState];
          }
          delete normalized[legacyState];
        }
      }
    );
    Object.entries(normalized).forEach(([key, value]) => {
      if (!isObjectRecord(value)) {
        return;
      }
      const normalizedValue = normalizeStyleStateNode(value);
      if (normalizedValue !== value) {
        if (normalized === node) {
          normalized = { ...node };
        }
        normalized[key] = normalizedValue;
      }
    });
    return normalized;
  }
  function normalizeStyleStateAliases(globalStyles) {
    if (true) {
      return globalStyles;
    }
    if (!globalStyles?.styles) {
      return globalStyles;
    }
    const styles = normalizeStyleStateNode(globalStyles.styles);
    return styles === globalStyles.styles ? globalStyles : { ...globalStyles, styles };
  }
  function getLegacyStyleStatePath(path) {
    if (true) {
      return void 0;
    }
    const pathParts = path.split(".");
    const legacyPathParts = pathParts.map(
      (part) => LEGACY_STYLE_STATE_ALIASES[part] ?? part
    );
    return legacyPathParts.some(
      (part, index2) => part !== pathParts[index2]
    ) ? legacyPathParts.join(".") : void 0;
  }

  // packages/global-styles-engine/build-module/settings/get-style.mjs
  function getStyle(globalStyles, path, blockName, shouldDecodeEncode = true) {
    const appendedPath = path ? "." + path : "";
    const finalPath = !blockName ? `styles${appendedPath}` : `styles.blocks.${blockName}${appendedPath}`;
    if (!globalStyles) {
      return void 0;
    }
    let rawResult = getValueFromObjectPath(globalStyles, finalPath);
    const legacyPath = getLegacyStyleStatePath(finalPath);
    if (rawResult === void 0 && legacyPath) {
      let hasCanonicalPath = true;
      let currentValue = globalStyles;
      for (const pathPart of finalPath.split(".")) {
        if (!currentValue || typeof currentValue !== "object" || !Object.hasOwn(currentValue, pathPart)) {
          hasCanonicalPath = false;
          break;
        }
        currentValue = currentValue[pathPart];
      }
      if (!hasCanonicalPath) {
        rawResult = getValueFromObjectPath(globalStyles, legacyPath);
      }
    }
    const result = shouldDecodeEncode ? getValueFromVariable(globalStyles, blockName, rawResult) : rawResult;
    return result;
  }

  // packages/global-styles-engine/build-module/settings/set-style.mjs
  function setStyle(globalStyles, path, newValue, blockName) {
    const appendedPath = path ? "." + path : "";
    const finalPath = !blockName ? `styles${appendedPath}` : `styles.blocks.${blockName}${appendedPath}`;
    return setImmutably(
      normalizeStyleStateAliases(globalStyles),
      finalPath.split("."),
      newValue
    );
  }

  // packages/global-styles-engine/build-module/core/equal.mjs
  var import_es6 = __toESM(require_es6(), 1);
  function areGlobalStylesEqual(original, variation) {
    if (typeof original !== "object" || typeof variation !== "object") {
      return original === variation;
    }
    return (0, import_es6.default)(original?.styles, variation?.styles) && (0, import_es6.default)(original?.settings, variation?.settings);
  }

  // packages/global-styles-engine/build-module/core/merge.mjs
  var import_deepmerge = __toESM(require_cjs(), 1);

  // node_modules/is-plain-object/dist/is-plain-object.mjs
  function isObject(o3) {
    return Object.prototype.toString.call(o3) === "[object Object]";
  }
  function isPlainObject(o3) {
    var ctor, prot;
    if (isObject(o3) === false) return false;
    ctor = o3.constructor;
    if (ctor === void 0) return true;
    prot = ctor.prototype;
    if (isObject(prot) === false) return false;
    if (prot.hasOwnProperty("isPrototypeOf") === false) {
      return false;
    }
    return true;
  }

  // packages/global-styles-engine/build-module/core/merge.mjs
  function mergeGlobalStyles(base, user) {
    return (0, import_deepmerge.default)(
      normalizeStyleStateAliases(base),
      normalizeStyleStateAliases(user),
      {
        /*
         * We only pass as arrays the presets,
         * in which case we want the new array of values
         * to override the old array (no merging).
         */
        isMergeableObject: isPlainObject,
        /*
         * Exceptions to the above rule.
         * Background images should be replaced, not merged,
         * as they themselves are specific object definitions for the style.
         */
        customMerge: (key) => {
          if (key === "backgroundImage") {
            return (baseConfig, userConfig) => userConfig ?? baseConfig;
          }
          return void 0;
        }
      }
    );
  }

  // packages/global-styles-engine/build-module/core/render.mjs
  var import_blocks3 = __toESM(require_blocks(), 1);
  var import_style_engine2 = __toESM(require_style_engine(), 1);
  var import_data21 = __toESM(require_data(), 1);

  // packages/global-styles-engine/build-module/core/selectors.mjs
  function getBlockSelector(blockType, target = "root", options = {}) {
    if (!target) {
      return null;
    }
    const { fallback = false } = options;
    const { name: name2, selectors: selectors3, supports } = blockType;
    const hasSelectors = selectors3 && Object.keys(selectors3).length > 0;
    const path = Array.isArray(target) ? target.join(".") : target;
    let rootSelector = null;
    if (hasSelectors && selectors3.root) {
      rootSelector = selectors3?.root;
    } else if (supports?.__experimentalSelector) {
      rootSelector = supports.__experimentalSelector;
    } else {
      rootSelector = ".wp-block-" + name2.replace("core/", "").replace("/", "-");
    }
    if (path === "root") {
      return rootSelector;
    }
    const pathArray = Array.isArray(target) ? target : target.split(".");
    if (pathArray.length === 1) {
      const fallbackSelector = fallback ? rootSelector : null;
      if (hasSelectors) {
        const featureSelector2 = getValueFromObjectPath(
          selectors3,
          `${path}.root`,
          null
        ) || getValueFromObjectPath(selectors3, path, null);
        return featureSelector2 || fallbackSelector;
      }
      const featureSelector = supports ? getValueFromObjectPath(
        supports,
        `${path}.__experimentalSelector`,
        null
      ) : void 0;
      if (!featureSelector) {
        return fallbackSelector;
      }
      return scopeSelector(rootSelector, featureSelector);
    }
    let subfeatureSelector;
    if (hasSelectors) {
      subfeatureSelector = getValueFromObjectPath(selectors3, path, null);
    }
    if (subfeatureSelector) {
      return subfeatureSelector;
    }
    if (fallback) {
      return getBlockSelector(blockType, pathArray[0], options);
    }
    return null;
  }

  // node_modules/colord/index.mjs
  var r2 = { grad: 0.9, turn: 360, rad: 360 / (2 * Math.PI) };
  var t = function(r3) {
    return "string" == typeof r3 ? r3.length > 0 : "number" == typeof r3;
  };
  var n = function(r3, t3, n2) {
    return void 0 === t3 && (t3 = 0), void 0 === n2 && (n2 = Math.pow(10, t3)), Math.round(n2 * r3) / n2 + 0;
  };
  var e = function(r3, t3, n2) {
    return void 0 === t3 && (t3 = 0), void 0 === n2 && (n2 = 1), r3 > n2 ? n2 : r3 > t3 ? r3 : t3;
  };
  var u = function(r3) {
    return (r3 = isFinite(r3) ? r3 % 360 : 0) > 0 ? r3 : r3 + 360;
  };
  var a = function(r3) {
    return { r: e(r3.r, 0, 255), g: e(r3.g, 0, 255), b: e(r3.b, 0, 255), a: e(r3.a) };
  };
  var o = function(r3) {
    return { r: n(r3.r), g: n(r3.g), b: n(r3.b), a: n(r3.a, 3) };
  };
  var i = /^#([0-9a-f]{3,8})$/i;
  var s = function(r3) {
    var t3 = r3.toString(16);
    return t3.length < 2 ? "0" + t3 : t3;
  };
  var h = function(r3) {
    var t3 = r3.r, n2 = r3.g, e2 = r3.b, u2 = r3.a, a2 = Math.max(t3, n2, e2), o3 = a2 - Math.min(t3, n2, e2), i2 = o3 ? a2 === t3 ? (n2 - e2) / o3 : a2 === n2 ? 2 + (e2 - t3) / o3 : 4 + (t3 - n2) / o3 : 0;
    return { h: 60 * (i2 < 0 ? i2 + 6 : i2), s: a2 ? o3 / a2 * 100 : 0, v: a2 / 255 * 100, a: u2 };
  };
  var b = function(r3) {
    var t3 = r3.h, n2 = r3.s, e2 = r3.v, u2 = r3.a;
    t3 = t3 / 360 * 6, n2 /= 100, e2 /= 100;
    var a2 = Math.floor(t3), o3 = e2 * (1 - n2), i2 = e2 * (1 - (t3 - a2) * n2), s2 = e2 * (1 - (1 - t3 + a2) * n2), h2 = a2 % 6;
    return { r: 255 * [e2, i2, o3, o3, s2, e2][h2], g: 255 * [s2, e2, e2, i2, o3, o3][h2], b: 255 * [o3, o3, s2, e2, e2, i2][h2], a: u2 };
  };
  var g = function(r3) {
    return { h: u(r3.h), s: e(r3.s, 0, 100), l: e(r3.l, 0, 100), a: e(r3.a) };
  };
  var d = function(r3) {
    return { h: n(r3.h), s: n(r3.s), l: n(r3.l), a: n(r3.a, 3) };
  };
  var f = function(r3) {
    return b((n2 = (t3 = r3).s, { h: t3.h, s: (n2 *= ((e2 = t3.l) < 50 ? e2 : 100 - e2) / 100) > 0 ? 2 * n2 / (e2 + n2) * 100 : 0, v: e2 + n2, a: t3.a }));
    var t3, n2, e2;
  };
  var c = function(r3) {
    return { h: (t3 = h(r3)).h, s: (u2 = (200 - (n2 = t3.s)) * (e2 = t3.v) / 100) > 0 && u2 < 200 ? n2 * e2 / 100 / (u2 <= 100 ? u2 : 200 - u2) * 100 : 0, l: u2 / 2, a: t3.a };
    var t3, n2, e2, u2;
  };
  var l = /^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
  var p2 = /^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
  var v = /^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
  var m = /^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i;
  var y = { string: [[function(r3) {
    var t3 = i.exec(r3);
    return t3 ? (r3 = t3[1]).length <= 4 ? { r: parseInt(r3[0] + r3[0], 16), g: parseInt(r3[1] + r3[1], 16), b: parseInt(r3[2] + r3[2], 16), a: 4 === r3.length ? n(parseInt(r3[3] + r3[3], 16) / 255, 2) : 1 } : 6 === r3.length || 8 === r3.length ? { r: parseInt(r3.substr(0, 2), 16), g: parseInt(r3.substr(2, 2), 16), b: parseInt(r3.substr(4, 2), 16), a: 8 === r3.length ? n(parseInt(r3.substr(6, 2), 16) / 255, 2) : 1 } : null : null;
  }, "hex"], [function(r3) {
    var t3 = v.exec(r3) || m.exec(r3);
    return t3 ? t3[2] !== t3[4] || t3[4] !== t3[6] ? null : a({ r: Number(t3[1]) / (t3[2] ? 100 / 255 : 1), g: Number(t3[3]) / (t3[4] ? 100 / 255 : 1), b: Number(t3[5]) / (t3[6] ? 100 / 255 : 1), a: void 0 === t3[7] ? 1 : Number(t3[7]) / (t3[8] ? 100 : 1) }) : null;
  }, "rgb"], [function(t3) {
    var n2 = l.exec(t3) || p2.exec(t3);
    if (!n2) return null;
    var e2, u2, a2 = g({ h: (e2 = n2[1], u2 = n2[2], void 0 === u2 && (u2 = "deg"), Number(e2) * (r2[u2] || 1)), s: Number(n2[3]), l: Number(n2[4]), a: void 0 === n2[5] ? 1 : Number(n2[5]) / (n2[6] ? 100 : 1) });
    return f(a2);
  }, "hsl"]], object: [[function(r3) {
    var n2 = r3.r, e2 = r3.g, u2 = r3.b, o3 = r3.a, i2 = void 0 === o3 ? 1 : o3;
    return t(n2) && t(e2) && t(u2) ? a({ r: Number(n2), g: Number(e2), b: Number(u2), a: Number(i2) }) : null;
  }, "rgb"], [function(r3) {
    var n2 = r3.h, e2 = r3.s, u2 = r3.l, a2 = r3.a, o3 = void 0 === a2 ? 1 : a2;
    if (!t(n2) || !t(e2) || !t(u2)) return null;
    var i2 = g({ h: Number(n2), s: Number(e2), l: Number(u2), a: Number(o3) });
    return f(i2);
  }, "hsl"], [function(r3) {
    var n2 = r3.h, a2 = r3.s, o3 = r3.v, i2 = r3.a, s2 = void 0 === i2 ? 1 : i2;
    if (!t(n2) || !t(a2) || !t(o3)) return null;
    var h2 = (function(r4) {
      return { h: u(r4.h), s: e(r4.s, 0, 100), v: e(r4.v, 0, 100), a: e(r4.a) };
    })({ h: Number(n2), s: Number(a2), v: Number(o3), a: Number(s2) });
    return b(h2);
  }, "hsv"]] };
  var N = function(r3, t3) {
    for (var n2 = 0; n2 < t3.length; n2++) {
      var e2 = t3[n2][0](r3);
      if (e2) return [e2, t3[n2][1]];
    }
    return [null, void 0];
  };
  var x = function(r3) {
    return "string" == typeof r3 ? N(r3.trim(), y.string) : "object" == typeof r3 && null !== r3 ? N(r3, y.object) : [null, void 0];
  };
  var M = function(r3, t3) {
    var n2 = c(r3);
    return { h: n2.h, s: e(n2.s + 100 * t3, 0, 100), l: n2.l, a: n2.a };
  };
  var H = function(r3) {
    return (299 * r3.r + 587 * r3.g + 114 * r3.b) / 1e3 / 255;
  };
  var $ = function(r3, t3) {
    var n2 = c(r3);
    return { h: n2.h, s: n2.s, l: e(n2.l + 100 * t3, 0, 100), a: n2.a };
  };
  var j = (function() {
    function r3(r4) {
      this.parsed = x(r4)[0], this.rgba = this.parsed || { r: 0, g: 0, b: 0, a: 1 };
    }
    return r3.prototype.isValid = function() {
      return null !== this.parsed;
    }, r3.prototype.brightness = function() {
      return n(H(this.rgba), 2);
    }, r3.prototype.isDark = function() {
      return H(this.rgba) < 0.5;
    }, r3.prototype.isLight = function() {
      return H(this.rgba) >= 0.5;
    }, r3.prototype.toHex = function() {
      return r4 = o(this.rgba), t3 = r4.r, e2 = r4.g, u2 = r4.b, i2 = (a2 = r4.a) < 1 ? s(n(255 * a2)) : "", "#" + s(t3) + s(e2) + s(u2) + i2;
      var r4, t3, e2, u2, a2, i2;
    }, r3.prototype.toRgb = function() {
      return o(this.rgba);
    }, r3.prototype.toRgbString = function() {
      return r4 = o(this.rgba), t3 = r4.r, n2 = r4.g, e2 = r4.b, (u2 = r4.a) < 1 ? "rgba(" + t3 + ", " + n2 + ", " + e2 + ", " + u2 + ")" : "rgb(" + t3 + ", " + n2 + ", " + e2 + ")";
      var r4, t3, n2, e2, u2;
    }, r3.prototype.toHsl = function() {
      return d(c(this.rgba));
    }, r3.prototype.toHslString = function() {
      return r4 = d(c(this.rgba)), t3 = r4.h, n2 = r4.s, e2 = r4.l, (u2 = r4.a) < 1 ? "hsla(" + t3 + ", " + n2 + "%, " + e2 + "%, " + u2 + ")" : "hsl(" + t3 + ", " + n2 + "%, " + e2 + "%)";
      var r4, t3, n2, e2, u2;
    }, r3.prototype.toHsv = function() {
      return r4 = h(this.rgba), { h: n(r4.h), s: n(r4.s), v: n(r4.v), a: n(r4.a, 3) };
      var r4;
    }, r3.prototype.invert = function() {
      return w({ r: 255 - (r4 = this.rgba).r, g: 255 - r4.g, b: 255 - r4.b, a: r4.a });
      var r4;
    }, r3.prototype.saturate = function(r4) {
      return void 0 === r4 && (r4 = 0.1), w(M(this.rgba, r4));
    }, r3.prototype.desaturate = function(r4) {
      return void 0 === r4 && (r4 = 0.1), w(M(this.rgba, -r4));
    }, r3.prototype.grayscale = function() {
      return w(M(this.rgba, -1));
    }, r3.prototype.lighten = function(r4) {
      return void 0 === r4 && (r4 = 0.1), w($(this.rgba, r4));
    }, r3.prototype.darken = function(r4) {
      return void 0 === r4 && (r4 = 0.1), w($(this.rgba, -r4));
    }, r3.prototype.rotate = function(r4) {
      return void 0 === r4 && (r4 = 15), this.hue(this.hue() + r4);
    }, r3.prototype.alpha = function(r4) {
      return "number" == typeof r4 ? w({ r: (t3 = this.rgba).r, g: t3.g, b: t3.b, a: r4 }) : n(this.rgba.a, 3);
      var t3;
    }, r3.prototype.hue = function(r4) {
      var t3 = c(this.rgba);
      return "number" == typeof r4 ? w({ h: r4, s: t3.s, l: t3.l, a: t3.a }) : n(t3.h);
    }, r3.prototype.isEqual = function(r4) {
      return this.toHex() === w(r4).toHex();
    }, r3;
  })();
  var w = function(r3) {
    return r3 instanceof j ? r3 : new j(r3);
  };
  var S = [];
  var k = function(r3) {
    r3.forEach(function(r4) {
      S.indexOf(r4) < 0 && (r4(j, y), S.push(r4));
    });
  };

  // packages/global-styles-engine/build-module/utils/duotone.mjs
  function getValuesFromColors(colors2 = []) {
    const values = {
      r: [],
      g: [],
      b: [],
      a: []
    };
    colors2.forEach((color) => {
      const rgbColor = w(color).toRgb();
      values.r.push(rgbColor.r / 255);
      values.g.push(rgbColor.g / 255);
      values.b.push(rgbColor.b / 255);
      values.a.push(rgbColor.a);
    });
    return values;
  }
  function getDuotoneFilter(id, colors2) {
    const values = getValuesFromColors(colors2);
    return `
<svg
	xmlns:xlink="http://www.w3.org/1999/xlink"
	viewBox="0 0 0 0"
	width="0"
	height="0"
	focusable="false"
	role="none"
	aria-hidden="true"
	style="visibility: hidden; position: absolute; left: -9999px; overflow: hidden;"
>
	<defs>
		<filter id="${id}">
			<!--
				Use sRGB instead of linearRGB so transparency looks correct.
				Use perceptual brightness to convert to grayscale.
			-->
			<feColorMatrix color-interpolation-filters="sRGB" type="matrix" values=" .299 .587 .114 0 0 .299 .587 .114 0 0 .299 .587 .114 0 0 .299 .587 .114 0 0 "></feColorMatrix>
			<!-- Use sRGB instead of linearRGB to be consistent with how CSS gradients work. -->
			<feComponentTransfer color-interpolation-filters="sRGB">
				<feFuncR type="table" tableValues="${values.r.join(" ")}"></feFuncR>
				<feFuncG type="table" tableValues="${values.g.join(" ")}"></feFuncG>
				<feFuncB type="table" tableValues="${values.b.join(" ")}"></feFuncB>
				<feFuncA type="table" tableValues="${values.a.join(" ")}"></feFuncA>
			</feComponentTransfer>
			<!-- Re-mask the image with the original transparency since the feColorMatrix above loses that information. -->
			<feComposite in2="SourceGraphic" operator="in"></feComposite>
		</filter>
	</defs>
</svg>`;
  }

  // packages/global-styles-engine/build-module/utils/string.mjs
  function kebabCase(str) {
    return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/([0-9])([a-zA-Z])/g, "$1-$2").replace(/([a-zA-Z])([0-9])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
  }

  // packages/global-styles-engine/build-module/utils/spacing.mjs
  function getSpacingPresetCssVar(value) {
    if (!value) {
      return;
    }
    const slug = value.match(/var:preset\|spacing\|(.+)/);
    if (!slug) {
      return value;
    }
    return `var(--wp--preset--spacing--${slug[1]})`;
  }

  // packages/global-styles-engine/build-module/utils/gap.mjs
  function getGapBoxControlValueFromStyle(blockGapValue) {
    if (!blockGapValue) {
      return null;
    }
    const isValueString = typeof blockGapValue === "string";
    return {
      top: isValueString ? blockGapValue : blockGapValue?.top,
      left: isValueString ? blockGapValue : blockGapValue?.left
    };
  }
  function getGapCSSValue(blockGapValue, defaultValue2 = "0") {
    const blockGapBoxControlValue = getGapBoxControlValueFromStyle(blockGapValue);
    if (!blockGapBoxControlValue) {
      return null;
    }
    const row = getSpacingPresetCssVar(blockGapBoxControlValue?.top) || defaultValue2;
    const column = getSpacingPresetCssVar(blockGapBoxControlValue?.left) || defaultValue2;
    return row === column ? row : `${row} ${column}`;
  }

  // packages/global-styles-engine/build-module/utils/background.mjs
  var BACKGROUND_BLOCK_DEFAULT_VALUES = {
    backgroundSize: "cover",
    backgroundPosition: "50% 50%"
    // used only when backgroundSize is 'contain'.
  };
  function setBackgroundStyleDefaults(backgroundStyle) {
    if (!backgroundStyle || // @ts-expect-error
    !backgroundStyle?.backgroundImage?.url) {
      return;
    }
    let backgroundStylesWithDefaults;
    if (!backgroundStyle?.backgroundSize) {
      backgroundStylesWithDefaults = {
        backgroundSize: BACKGROUND_BLOCK_DEFAULT_VALUES.backgroundSize
      };
    }
    if ("contain" === backgroundStyle?.backgroundSize && !backgroundStyle?.backgroundPosition) {
      backgroundStylesWithDefaults = {
        backgroundPosition: BACKGROUND_BLOCK_DEFAULT_VALUES.backgroundPosition
      };
    }
    return backgroundStylesWithDefaults;
  }

  // packages/global-styles-engine/build-module/utils/layout.mjs
  var LAYOUT_DEFINITIONS = {
    default: {
      name: "default",
      slug: "flow",
      className: "is-layout-flow",
      baseStyles: [
        {
          selector: " > .alignleft",
          rules: {
            float: "left",
            "margin-inline-start": "0",
            "margin-inline-end": "2em"
          }
        },
        {
          selector: " > .alignright",
          rules: {
            float: "right",
            "margin-inline-start": "2em",
            "margin-inline-end": "0"
          }
        },
        {
          selector: " > .aligncenter",
          rules: {
            "margin-left": "auto !important",
            "margin-right": "auto !important"
          }
        }
      ],
      spacingStyles: [
        {
          selector: " > :first-child",
          rules: {
            "margin-block-start": "0"
          }
        },
        {
          selector: " > :last-child",
          rules: {
            "margin-block-end": "0"
          }
        },
        {
          selector: " > *",
          rules: {
            "margin-block-start": null,
            "margin-block-end": "0"
          }
        }
      ]
    },
    constrained: {
      name: "constrained",
      slug: "constrained",
      className: "is-layout-constrained",
      baseStyles: [
        {
          selector: " > .alignleft",
          rules: {
            float: "left",
            "margin-inline-start": "0",
            "margin-inline-end": "2em"
          }
        },
        {
          selector: " > .alignright",
          rules: {
            float: "right",
            "margin-inline-start": "2em",
            "margin-inline-end": "0"
          }
        },
        {
          selector: " > .aligncenter",
          rules: {
            "margin-left": "auto !important",
            "margin-right": "auto !important"
          }
        },
        {
          selector: " > :where(:not(.alignleft):not(.alignright):not(.alignfull))",
          rules: {
            "max-width": "var(--wp--style--global--content-size)",
            "margin-left": "auto !important",
            "margin-right": "auto !important"
          }
        },
        {
          selector: " > .alignwide",
          rules: {
            "max-width": "var(--wp--style--global--wide-size)"
          }
        }
      ],
      spacingStyles: [
        {
          selector: " > :first-child",
          rules: {
            "margin-block-start": "0"
          }
        },
        {
          selector: " > :last-child",
          rules: {
            "margin-block-end": "0"
          }
        },
        {
          selector: " > *",
          rules: {
            "margin-block-start": null,
            "margin-block-end": "0"
          }
        }
      ]
    },
    flex: {
      name: "flex",
      slug: "flex",
      className: "is-layout-flex",
      displayMode: "flex",
      baseStyles: [
        {
          selector: "",
          rules: {
            "flex-wrap": "wrap",
            "align-items": "center"
          }
        },
        {
          selector: " > :is(*, div)",
          // :is(*, div) instead of just * increases the specificity by 001.
          rules: {
            margin: "0"
          }
        }
      ],
      spacingStyles: [
        {
          selector: "",
          rules: {
            gap: null
          }
        }
      ]
    },
    grid: {
      name: "grid",
      slug: "grid",
      className: "is-layout-grid",
      displayMode: "grid",
      baseStyles: [
        {
          selector: " > :is(*, div)",
          // :is(*, div) instead of just * increases the specificity by 001.
          rules: {
            margin: "0"
          }
        }
      ],
      spacingStyles: [
        {
          selector: "",
          rules: {
            gap: null
          }
        }
      ]
    }
  };

  // packages/global-styles-engine/build-module/utils/viewport.mjs
  var DEFAULT_VIEWPORT_BREAKPOINTS = {
    mobile: "480px",
    tablet: "782px"
  };
  var VIEWPORT_SIZE_REGEXP = /^(\d+|\d*\.\d+)(px|em|rem)$/;
  var DEFAULT_FONT_SIZE = 16;
  function isViewportSettings(configOrSettings) {
    return "mobile" in configOrSettings || "tablet" in configOrSettings;
  }
  function getViewportSettings(configOrSettings) {
    if (!configOrSettings || typeof configOrSettings !== "object") {
      return {};
    }
    if (isViewportSettings(configOrSettings)) {
      return configOrSettings;
    }
    return configOrSettings.settings?.viewport ?? {};
  }
  function isValidViewportSize(value) {
    return typeof value === "string" && VIEWPORT_SIZE_REGEXP.test(value.trim());
  }
  function getViewportBreakpointValueInPixels(value) {
    if (typeof value === "number") {
      return value;
    }
    if (typeof value !== "string") {
      return void 0;
    }
    const match3 = value.trim().match(VIEWPORT_SIZE_REGEXP);
    if (!match3) {
      return void 0;
    }
    const numericValue = Number.parseFloat(match3[1]);
    const unit = match3[2];
    return unit === "px" ? numericValue : numericValue * DEFAULT_FONT_SIZE;
  }
  function getViewportBreakpoints(configOrSettings) {
    const viewportSettings = getViewportSettings(configOrSettings);
    const breakpoints = {};
    const breakpointValuesInPixels = {};
    Object.keys(DEFAULT_VIEWPORT_BREAKPOINTS).forEach((breakpoint) => {
      const key = breakpoint;
      const value = viewportSettings[key];
      const px = getViewportBreakpointValueInPixels(value);
      if (px !== void 0 && isValidViewportSize(value)) {
        breakpoints[key] = value.trim();
        breakpointValuesInPixels[key] = px;
      }
    });
    const breakpointNames = Object.keys(breakpoints);
    if (!breakpointNames.length) {
      return { ...DEFAULT_VIEWPORT_BREAKPOINTS };
    }
    if (1 === breakpointNames.length) {
      return breakpoints;
    }
    const mobile = breakpoints.mobile;
    const tablet = breakpoints.tablet;
    if (breakpointValuesInPixels.mobile >= breakpointValuesInPixels.tablet) {
      return { mobile };
    }
    return { mobile, tablet };
  }
  function getResponsiveMediaQueries(configOrSettings) {
    const breakpoints = getViewportBreakpoints(configOrSettings);
    const mediaQueries = {};
    if (breakpoints.mobile) {
      mediaQueries["@mobile"] = `@media (width <= ${breakpoints.mobile})`;
    }
    if (breakpoints.tablet) {
      mediaQueries["@tablet"] = breakpoints.mobile ? `@media (${breakpoints.mobile} < width <= ${breakpoints.tablet})` : `@media (width <= ${breakpoints.tablet})`;
    }
    return mediaQueries;
  }

  // packages/global-styles-engine/build-module/core/render.mjs
  var ELEMENT_CLASS_NAMES = {
    button: "wp-element-button",
    caption: "wp-element-caption"
  };
  var BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = {
    __experimentalBorder: "border",
    color: "color",
    dimensions: "dimensions",
    spacing: "spacing",
    typography: "typography"
  };
  var VALID_BLOCK_PSEUDO_SELECTORS = {
    "core/button": [":hover", ":focus", ":focus-visible", ":active"],
    "core/navigation-link": [":hover", ":focus", ":focus-visible", ":active"]
  };
  var VALID_ELEMENT_PSEUDO_SELECTORS = {
    link: [
      ":link",
      ":any-link",
      ":visited",
      ":hover",
      ":focus",
      ":focus-visible",
      ":active"
    ],
    button: [
      ":link",
      ":any-link",
      ":visited",
      ":hover",
      ":focus",
      ":focus-visible",
      ":active"
    ]
  };
  function getPresetsClasses(blockSelector = "*", blockPresets = {}) {
    return PRESET_METADATA.reduce(
      (declarations, { path, cssVarInfix, classes }) => {
        if (!classes) {
          return declarations;
        }
        const presetByOrigin = getValueFromObjectPath(
          blockPresets,
          path,
          []
        );
        ["default", "theme", "custom"].forEach((origin) => {
          if (presetByOrigin[origin]) {
            presetByOrigin[origin].forEach(
              ({ slug }) => {
                classes.forEach(
                  ({
                    classSuffix,
                    propertyName
                  }) => {
                    const classSelectorToUse = `.has-${kebabCase(
                      slug
                    )}-${classSuffix}`;
                    const selectorToUse = blockSelector ? `:where(${blockSelector})${classSelectorToUse}` : classSelectorToUse;
                    const value = `var(--wp--preset--${cssVarInfix}--${kebabCase(
                      slug
                    )})`;
                    declarations += `${selectorToUse}{${propertyName}: ${value} !important;}`;
                  }
                );
              }
            );
          }
        });
        return declarations;
      },
      ""
    );
  }
  function getPresetsSvgFilters(blockPresets = {}) {
    return PRESET_METADATA.filter(
      // Duotone are the only type of filters for now.
      (metadata) => metadata.path.at(-1) === "duotone"
    ).flatMap((metadata) => {
      const presetByOrigin = getValueFromObjectPath(
        blockPresets,
        metadata.path,
        {}
      );
      return ["default", "theme"].filter((origin) => presetByOrigin[origin]).flatMap(
        (origin) => presetByOrigin[origin].map(
          (preset) => getDuotoneFilter(
            `wp-duotone-${preset.slug}`,
            preset.colors
          )
        )
      ).join("");
    });
  }
  function flattenTree(input = {}, prefix2, token) {
    let result = [];
    Object.keys(input).forEach((key) => {
      const newKey = prefix2 + kebabCase(key.replace("/", "-"));
      const newLeaf = input[key];
      if (newLeaf instanceof Object) {
        const newPrefix = newKey + token;
        result = [...result, ...flattenTree(newLeaf, newPrefix, token)];
      } else {
        result.push(`${newKey}: ${newLeaf}`);
      }
    });
    return result;
  }
  var updateParagraphTextIndentSelector = (featureDeclarations, settings2, blockName) => {
    if (blockName !== "core/paragraph") {
      return featureDeclarations;
    }
    const blockSettings = settings2?.blocks?.["core/paragraph"];
    const textIndentSetting = blockSettings?.typography?.textIndent ?? settings2?.typography?.textIndent ?? "subsequent";
    if (textIndentSetting !== "all") {
      return featureDeclarations;
    }
    const oldSelector = ".wp-block-paragraph + .wp-block-paragraph";
    const newSelector = ".wp-block-paragraph";
    if (oldSelector in featureDeclarations) {
      const declarations = featureDeclarations[oldSelector];
      const updated = { ...featureDeclarations };
      delete updated[oldSelector];
      updated[newSelector] = declarations;
      return updated;
    }
    return featureDeclarations;
  };
  var updateButtonWidthDeclarations = (featureDeclarations, settings2) => {
    const buttonSelector = ".wp-block-button";
    if (!(buttonSelector in featureDeclarations)) {
      return featureDeclarations;
    }
    const updated = { ...featureDeclarations };
    updated[buttonSelector] = updated[buttonSelector].map(
      (declaration) => {
        const match3 = declaration.match(/^width:\s*(.+)$/);
        if (!match3) {
          return declaration;
        }
        const value = match3[1];
        let percentage = null;
        if (value.endsWith("%")) {
          percentage = parseFloat(value);
        }
        const presetPrefix = "var(--wp--preset--dimension--";
        if (percentage === null && value.startsWith(presetPrefix) && value.endsWith(")")) {
          const slug = value.slice(presetPrefix.length, -1);
          const dimensionSizes = {
            ...settings2?.dimensions?.dimensionSizes ?? {},
            ...settings2?.blocks?.["core/button"]?.dimensions?.dimensionSizes ?? {}
          };
          for (const origin of Object.values(dimensionSizes)) {
            if (!Array.isArray(origin)) {
              continue;
            }
            for (const preset of origin) {
              if (preset.slug === slug && typeof preset.size === "string" && preset.size.endsWith("%")) {
                percentage = parseFloat(preset.size);
                break;
              }
            }
            if (percentage !== null) {
              break;
            }
          }
        }
        if (percentage === null || isNaN(percentage)) {
          return declaration;
        }
        return `width: calc(${percentage} * 1% - (var(--wp--style--block-gap, 0.5em) * (1 - ${percentage} / 100)))`;
      }
    );
    return updated;
  };
  var getFeatureDeclarations = (selectors3, styles) => {
    const declarations = {};
    Object.entries(selectors3).forEach(([feature, selector2]) => {
      if (feature === "root" || !styles?.[feature]) {
        return;
      }
      const isShorthand = typeof selector2 === "string";
      if (!isShorthand && typeof selector2 === "object" && selector2 !== null) {
        Object.entries(selector2).forEach(
          ([subfeature, subfeatureSelector]) => {
            if (subfeature === "root" || !styles?.[feature][subfeature]) {
              return;
            }
            const subfeatureStyles = {
              [feature]: {
                [subfeature]: styles[feature][subfeature]
              }
            };
            const newDeclarations = getStylesDeclarations(subfeatureStyles);
            declarations[subfeatureSelector] = [
              ...declarations[subfeatureSelector] || [],
              ...newDeclarations
            ];
            delete styles[feature][subfeature];
          }
        );
      }
      if (isShorthand || typeof selector2 === "object" && selector2 !== null && "root" in selector2) {
        const featureSelector = isShorthand ? selector2 : selector2.root;
        const featureStyles = { [feature]: styles[feature] };
        const newDeclarations = getStylesDeclarations(featureStyles);
        declarations[featureSelector] = [
          ...declarations[featureSelector] || [],
          ...newDeclarations
        ];
        delete styles[feature];
      }
    });
    return declarations;
  };
  function getStylesDeclarations(blockStyles = {}, selector2 = "", useRootPaddingAlign, tree = {}, disableRootPadding = false) {
    const isRoot = ROOT_BLOCK_SELECTOR === selector2;
    const output = Object.entries(
      import_blocks3.__EXPERIMENTAL_STYLE_PROPERTY
    ).reduce(
      (declarations, [key, { value, properties, useEngine, rootOnly }]) => {
        if (rootOnly && !isRoot) {
          return declarations;
        }
        const pathToValue = value;
        if (pathToValue[0] === "elements" || useEngine) {
          return declarations;
        }
        const styleValue = getValueFromObjectPath(
          blockStyles,
          pathToValue
        );
        if (key === "--wp--style--root--padding" && (typeof styleValue === "string" || !useRootPaddingAlign)) {
          return declarations;
        }
        if (properties && typeof styleValue !== "string") {
          Object.entries(properties).forEach((entry) => {
            const [name2, prop] = entry;
            if (!getValueFromObjectPath(styleValue, [prop], false)) {
              return;
            }
            const cssProperty = name2.startsWith("--") ? name2 : kebabCase(name2);
            declarations.push(
              `${cssProperty}: ${(0, import_style_engine2.getCSSValueFromRawStyle)(
                getValueFromObjectPath(styleValue, [prop])
              )}`
            );
          });
        } else if (getValueFromObjectPath(blockStyles, pathToValue, false)) {
          const cssProperty = key.startsWith("--") ? key : kebabCase(key);
          declarations.push(
            `${cssProperty}: ${(0, import_style_engine2.getCSSValueFromRawStyle)(
              getValueFromObjectPath(blockStyles, pathToValue)
            )}`
          );
        }
        return declarations;
      },
      []
    );
    if (!!blockStyles.background) {
      if (blockStyles.background?.backgroundImage) {
        blockStyles.background.backgroundImage = getResolvedValue(
          blockStyles.background.backgroundImage,
          tree
        );
      }
      if (!isRoot && !!blockStyles.background?.backgroundImage?.id) {
        blockStyles = {
          ...blockStyles,
          background: {
            ...blockStyles.background,
            ...setBackgroundStyleDefaults(blockStyles.background)
          }
        };
      }
    }
    const extraRules = (0, import_style_engine2.getCSSRules)(blockStyles);
    extraRules.forEach((rule) => {
      if (isRoot && (useRootPaddingAlign || disableRootPadding) && rule.key.startsWith("padding")) {
        return;
      }
      const cssProperty = rule.key.startsWith("--") ? rule.key : kebabCase(rule.key);
      let ruleValue = getResolvedValue(rule.value, tree);
      if (cssProperty === "font-size") {
        ruleValue = getTypographyFontSizeValue(
          { name: "", slug: "", size: ruleValue },
          tree?.settings
        );
      }
      if (cssProperty === "aspect-ratio") {
        output.push("min-height: unset");
      }
      output.push(`${cssProperty}: ${ruleValue}`);
    });
    return output;
  }
  function getLayoutStyles({
    layoutDefinitions = LAYOUT_DEFINITIONS,
    style,
    selector: selector2,
    hasBlockGapSupport,
    hasFallbackGapSupport,
    fallbackGapValue
  }) {
    let ruleset = "";
    let gapValue = hasBlockGapSupport ? getGapCSSValue(style?.spacing?.blockGap) : "";
    if (hasFallbackGapSupport) {
      if (selector2 === ROOT_BLOCK_SELECTOR) {
        gapValue = !gapValue ? "0.5em" : gapValue;
      } else if (!hasBlockGapSupport && fallbackGapValue) {
        gapValue = fallbackGapValue;
      }
    }
    if (gapValue && layoutDefinitions) {
      Object.values(layoutDefinitions).forEach(
        ({ className, name: name2, spacingStyles }) => {
          if (!hasBlockGapSupport && "flex" !== name2 && "grid" !== name2) {
            return;
          }
          if (spacingStyles?.length) {
            spacingStyles.forEach((spacingStyle) => {
              const declarations = [];
              if (spacingStyle.rules) {
                Object.entries(spacingStyle.rules).forEach(
                  ([cssProperty, cssValue]) => {
                    declarations.push(
                      `${cssProperty}: ${cssValue ? cssValue : gapValue}`
                    );
                  }
                );
              }
              if (declarations.length) {
                let combinedSelector = "";
                if (!hasBlockGapSupport) {
                  combinedSelector = selector2 === ROOT_BLOCK_SELECTOR ? `:where(.${className}${spacingStyle?.selector || ""})` : `:where(${selector2}.${className}${spacingStyle?.selector || ""})`;
                } else {
                  combinedSelector = selector2 === ROOT_BLOCK_SELECTOR ? `:root :where(.${className})${spacingStyle?.selector || ""}` : `:root :where(${selector2}-${className})${spacingStyle?.selector || ""}`;
                }
                ruleset += `${combinedSelector} { ${declarations.join(
                  "; "
                )}; }`;
              }
            });
          }
        }
      );
      if (selector2 === ROOT_BLOCK_SELECTOR && hasBlockGapSupport) {
        ruleset += `${ROOT_CSS_PROPERTIES_SELECTOR} { --wp--style--block-gap: ${gapValue}; }`;
      }
    }
    if (selector2 === ROOT_BLOCK_SELECTOR && layoutDefinitions) {
      const validDisplayModes = ["block", "flex", "grid"];
      Object.values(layoutDefinitions).forEach(
        ({ className, displayMode, baseStyles }) => {
          if (displayMode && validDisplayModes.includes(displayMode)) {
            ruleset += `${selector2} .${className} { display:${displayMode}; }`;
          }
          if (baseStyles?.length) {
            baseStyles.forEach((baseStyle) => {
              const declarations = [];
              if (baseStyle.rules) {
                Object.entries(baseStyle.rules).forEach(
                  ([cssProperty, cssValue]) => {
                    declarations.push(
                      `${cssProperty}: ${cssValue}`
                    );
                  }
                );
              }
              if (declarations.length) {
                const combinedSelector = `.${className}${baseStyle?.selector || ""}`;
                ruleset += `${combinedSelector} { ${declarations.join(
                  "; "
                )}; }`;
              }
            });
          }
        }
      );
    }
    return ruleset;
  }
  var STYLE_KEYS = [
    "border",
    "color",
    "dimensions",
    "spacing",
    "typography",
    "filter",
    "outline",
    "shadow",
    "background"
  ];
  function pickStyleKeys(treeToPickFrom, responsiveMediaQueries) {
    return pickStyleAndPseudoKeys(
      treeToPickFrom,
      void 0,
      responsiveMediaQueries
    );
  }
  function pickStyleAndPseudoKeys(treeToPickFrom, blockName, responsiveMediaQueries) {
    if (!treeToPickFrom) {
      return {};
    }
    const entries = Object.entries(treeToPickFrom);
    const allowedPseudoSelectors = blockName ? VALID_BLOCK_PSEUDO_SELECTORS[blockName] ?? [] : [];
    const pickedEntries = entries.filter(
      ([key]) => STYLE_KEYS.includes(key) || allowedPseudoSelectors.includes(key) || responsiveMediaQueries[key]
    );
    const clonedEntries = pickedEntries.map(([key, style]) => [
      key,
      JSON.parse(JSON.stringify(style))
    ]);
    return Object.fromEntries(clonedEntries);
  }
  function getPseudoStyleNodes(node) {
    const {
      styles,
      selector: selector2,
      featureSelectors,
      name: name2,
      elementName,
      mediaQuery,
      variationName
    } = node;
    const pseudoSelectors = name2 ? VALID_BLOCK_PSEUDO_SELECTORS[name2] ?? [] : VALID_ELEMENT_PSEUDO_SELECTORS[elementName ?? ""] ?? [];
    if (!pseudoSelectors.length) {
      return [];
    }
    return pseudoSelectors.flatMap((pseudoSelector) => {
      const pseudoStyles = styles?.[pseudoSelector];
      if (!pseudoStyles || typeof pseudoStyles !== "object") {
        return [];
      }
      return [
        {
          styles: JSON.parse(JSON.stringify(pseudoStyles)),
          selector: selector2,
          selectorSuffix: pseudoSelector,
          mediaQuery,
          featureSelectors: featureSelectors && typeof featureSelectors !== "string" ? featureSelectors : void 0,
          name: name2,
          elementName,
          variationName
        }
      ];
    });
  }
  function getResponsiveStyleNodes(node, responsiveMediaQueries) {
    const {
      styles,
      selector: selector2,
      fallbackGapValue,
      featureSelectors,
      hasLayoutSupport,
      layoutHasBlockGapSupport,
      layoutSelector,
      name: name2,
      elementName,
      isStyleVariation,
      variationName
    } = node;
    if (!name2 && !elementName) {
      return [];
    }
    return Object.entries(responsiveMediaQueries).flatMap(
      ([breakpointKey, mediaQuery]) => {
        const breakpointStyles = styles?.[breakpointKey];
        if (!breakpointStyles || typeof breakpointStyles !== "object") {
          return [];
        }
        return [
          {
            styles: JSON.parse(JSON.stringify(breakpointStyles)),
            selector: selector2,
            mediaQuery,
            featureSelectors: featureSelectors && typeof featureSelectors !== "string" ? featureSelectors : void 0,
            fallbackGapValue,
            hasLayoutSupport,
            name: name2,
            elementName,
            isStyleVariation,
            variationName,
            layoutSelector,
            layoutHasBlockGapSupport
          }
        ];
      }
    );
  }
  var getNodesWithStyles = (tree, blockSelectors) => {
    const nodes = [];
    if (!tree?.styles) {
      return nodes;
    }
    const responsiveMediaQueries = getResponsiveMediaQueries(tree);
    const styles = pickStyleKeys(tree.styles, responsiveMediaQueries);
    if (styles) {
      nodes.push({
        styles,
        selector: ROOT_BLOCK_SELECTOR,
        // Root selector (body) styles should not be wrapped in `:root where()` to keep
        // specificity at (0,0,1) and maintain backwards compatibility.
        skipSelectorWrapper: true
      });
    }
    Object.entries(import_blocks3.__EXPERIMENTAL_ELEMENTS).forEach(([name2, selector2]) => {
      if (tree.styles?.elements?.[name2]) {
        nodes.push({
          styles: tree.styles?.elements?.[name2] ?? {},
          selector: selector2,
          elementName: name2,
          // Top level elements that don't use a class name should not receive the
          // `:root :where()` wrapper to maintain backwards compatibility.
          skipSelectorWrapper: !ELEMENT_CLASS_NAMES[name2]
        });
      }
    });
    Object.entries(tree.styles?.blocks ?? {}).forEach(
      ([blockName, node]) => {
        const blockStyles = pickStyleAndPseudoKeys(
          node,
          blockName,
          responsiveMediaQueries
        );
        const typedNode = node;
        const variationNodesToAdd = [];
        const variationStyleNodesToAdd = [];
        if (typedNode?.variations) {
          Object.entries(typedNode.variations).forEach(
            ([variationName, variation]) => {
              const typedVariation = variation;
              const variationStyles = pickStyleAndPseudoKeys(
                typedVariation,
                blockName,
                responsiveMediaQueries
              );
              if (typedVariation?.css) {
                variationStyles.css = typedVariation.css;
              }
              const variationSelector = typeof blockSelectors !== "string" ? blockSelectors[blockName]?.styleVariationSelectors?.[variationName] : void 0;
              if (variationSelector && typeof blockSelectors !== "string") {
                const blockSelector = blockSelectors[blockName];
                variationStyleNodesToAdd.push({
                  styles: variationStyles,
                  selector: variationSelector,
                  featureSelectors: blockSelector?.featureSelectors,
                  fallbackGapValue: blockSelector?.fallbackGapValue,
                  hasLayoutSupport: blockSelector?.hasLayoutSupport,
                  isStyleVariation: true,
                  variationName,
                  layoutSelector: variationSelector + blockSelector.selector,
                  layoutHasBlockGapSupport: true,
                  name: blockName
                });
              }
              Object.entries(
                typedVariation?.elements ?? {}
              ).forEach(([element, elementStyles]) => {
                if (elementStyles && import_blocks3.__EXPERIMENTAL_ELEMENTS[element]) {
                  variationNodesToAdd.push({
                    styles: elementStyles,
                    selector: scopeSelector(
                      variationSelector,
                      import_blocks3.__EXPERIMENTAL_ELEMENTS[element]
                    ),
                    elementName: element,
                    isStyleVariation: true
                  });
                }
              });
              Object.entries(typedVariation?.blocks ?? {}).forEach(
                ([
                  variationBlockName,
                  variationBlockStyles
                ]) => {
                  const variationBlockSelector = typeof blockSelectors !== "string" ? scopeSelector(
                    variationSelector,
                    blockSelectors[variationBlockName]?.selector
                  ) : void 0;
                  const variationDuotoneSelector = typeof blockSelectors !== "string" ? scopeSelector(
                    variationSelector,
                    blockSelectors[variationBlockName]?.duotoneSelector
                  ) : void 0;
                  const variationFeatureSelectors = typeof blockSelectors !== "string" ? scopeFeatureSelectors(
                    variationSelector,
                    blockSelectors[variationBlockName]?.featureSelectors ?? {}
                  ) : void 0;
                  const variationBlockStyleNodes = pickStyleAndPseudoKeys(
                    variationBlockStyles,
                    variationBlockName,
                    responsiveMediaQueries
                  );
                  if (variationBlockStyles?.css) {
                    variationBlockStyleNodes.css = variationBlockStyles.css;
                  }
                  if (!variationBlockSelector || typeof blockSelectors === "string") {
                    return;
                  }
                  variationNodesToAdd.push({
                    selector: variationBlockSelector,
                    name: variationBlockName,
                    isStyleVariation: true,
                    duotoneSelector: variationDuotoneSelector,
                    featureSelectors: variationFeatureSelectors,
                    fallbackGapValue: blockSelectors[variationBlockName]?.fallbackGapValue,
                    hasLayoutSupport: blockSelectors[variationBlockName]?.hasLayoutSupport,
                    styles: variationBlockStyleNodes
                  });
                  Object.entries(
                    variationBlockStyles.elements ?? {}
                  ).forEach(
                    ([
                      variationBlockElement,
                      variationBlockElementStyles
                    ]) => {
                      if (variationBlockElementStyles && import_blocks3.__EXPERIMENTAL_ELEMENTS[variationBlockElement]) {
                        variationNodesToAdd.push({
                          styles: variationBlockElementStyles,
                          selector: scopeSelector(
                            variationBlockSelector,
                            import_blocks3.__EXPERIMENTAL_ELEMENTS[variationBlockElement]
                          ),
                          elementName: variationBlockElement,
                          isStyleVariation: true
                        });
                      }
                    }
                  );
                }
              );
            }
          );
        }
        if (typeof blockSelectors !== "string" && blockSelectors?.[blockName]?.selector) {
          nodes.push({
            duotoneSelector: blockSelectors[blockName].duotoneSelector,
            fallbackGapValue: blockSelectors[blockName].fallbackGapValue,
            hasLayoutSupport: blockSelectors[blockName].hasLayoutSupport,
            selector: blockSelectors[blockName].selector,
            styles: blockStyles,
            featureSelectors: blockSelectors[blockName].featureSelectors,
            name: blockName
          });
        }
        nodes.push(...variationStyleNodesToAdd);
        Object.entries(typedNode?.elements ?? {}).forEach(
          ([elementName, value]) => {
            if (typeof blockSelectors !== "string" && value && blockSelectors?.[blockName] && import_blocks3.__EXPERIMENTAL_ELEMENTS[elementName]) {
              nodes.push({
                styles: value,
                selector: blockSelectors[blockName]?.selector.split(",").map((sel) => {
                  const elementSelectors = import_blocks3.__EXPERIMENTAL_ELEMENTS[elementName].split(",");
                  return elementSelectors.map(
                    (elementSelector) => sel + " " + elementSelector
                  );
                }).join(","),
                elementName
              });
            }
          }
        );
        nodes.push(...variationNodesToAdd);
      }
    );
    return nodes;
  };
  var getNodesWithSettings = (tree, blockSelectors) => {
    const nodes = [];
    if (!tree?.settings) {
      return nodes;
    }
    const pickPresets = (treeToPickFrom) => {
      let presets2 = {};
      PRESET_METADATA.forEach(({ path }) => {
        const value = getValueFromObjectPath(treeToPickFrom, path, false);
        if (value !== false) {
          presets2 = setImmutably(presets2, path, value);
        }
      });
      return presets2;
    };
    const presets = pickPresets(tree.settings);
    const custom = tree.settings?.custom;
    if (Object.keys(presets).length > 0 || custom) {
      nodes.push({
        presets,
        custom,
        selector: ROOT_CSS_PROPERTIES_SELECTOR
      });
    }
    Object.entries(tree.settings?.blocks ?? {}).forEach(
      ([blockName, node]) => {
        const blockCustom = node.custom;
        if (typeof blockSelectors === "string" || !blockSelectors[blockName]) {
          return;
        }
        const blockPresets = pickPresets(node);
        if (Object.keys(blockPresets).length > 0 || blockCustom) {
          nodes.push({
            presets: blockPresets,
            custom: blockCustom,
            selector: blockSelectors[blockName]?.selector,
            featureSelectors: blockSelectors[blockName]?.featureSelectors
          });
        }
      }
    );
    return nodes;
  };
  function resolveFeatureSelector(featureSelectors, featureKey, fallback) {
    if (!featureSelectors || typeof featureSelectors === "string") {
      return fallback;
    }
    const feature = featureSelectors[featureKey];
    if (typeof feature === "string") {
      return feature;
    }
    if (typeof feature === "object" && feature.root) {
      return feature.root;
    }
    return fallback;
  }
  function getPresetVarDeclarations(presets, mergedSettings, { path, valueKey, valueFunc, cssVarInfix }) {
    const presetByOrigin = getValueFromObjectPath(
      presets,
      path,
      []
    );
    const declarations = [];
    for (const origin of ["default", "theme", "custom"]) {
      if (!presetByOrigin[origin]) {
        continue;
      }
      for (const value of presetByOrigin[origin]) {
        const slug = kebabCase(value.slug);
        if (valueKey && !valueFunc) {
          declarations.push(
            `--wp--preset--${cssVarInfix}--${slug}: ${value[valueKey]}`
          );
        } else if (valueFunc && typeof valueFunc === "function") {
          declarations.push(
            `--wp--preset--${cssVarInfix}--${slug}: ${valueFunc(
              value,
              mergedSettings
            )}`
          );
        }
      }
    }
    return declarations;
  }
  var generateCustomProperties = (tree, blockSelectors) => {
    const nodes = getNodesWithSettings(tree, blockSelectors);
    let ruleset = "";
    for (const { presets, custom, selector: selector2, featureSelectors } of nodes) {
      const defaultSelector = selector2;
      const varsBySelector = {
        [defaultSelector]: []
      };
      if (tree?.settings) {
        for (const metadata of PRESET_METADATA) {
          const declarations = getPresetVarDeclarations(
            presets,
            tree.settings,
            metadata
          );
          if (declarations.length === 0) {
            continue;
          }
          const target = resolveFeatureSelector(
            featureSelectors,
            metadata.path[0],
            defaultSelector
          );
          if (!varsBySelector[target]) {
            varsBySelector[target] = [];
          }
          varsBySelector[target].push(...declarations);
        }
      }
      const customProps = flattenTree(custom, "--wp--custom--", "--");
      if (customProps.length > 0) {
        varsBySelector[defaultSelector].push(...customProps);
      }
      for (const [ruleSelector, declarations] of Object.entries(
        varsBySelector
      )) {
        if (declarations.length > 0) {
          ruleset += `${ruleSelector}{${declarations.join(";")};}`;
        }
      }
    }
    return ruleset;
  };
  function renderStylesNode(node, {
    tree,
    useRootPaddingAlign,
    disableLayoutStyles,
    hasBlockGapSupport,
    hasFallbackGapSupport,
    disableRootPadding
  }) {
    const {
      selector: selector2,
      selectorSuffix,
      mediaQuery,
      duotoneSelector,
      styles,
      fallbackGapValue,
      hasLayoutSupport,
      featureSelectors,
      layoutSelector,
      layoutHasBlockGapSupport,
      skipSelectorWrapper,
      name: name2,
      variationName
    } = node;
    let ruleset = "";
    const effectiveSelector = selectorSuffix ? appendToSelector(selector2, selectorSuffix) : selector2;
    if (featureSelectors && typeof featureSelectors !== "string") {
      let featureDeclarations = getFeatureDeclarations(
        featureSelectors,
        styles
      );
      featureDeclarations = updateParagraphTextIndentSelector(
        featureDeclarations,
        tree.settings,
        name2
      );
      featureDeclarations = updateButtonWidthDeclarations(
        featureDeclarations,
        tree.settings
      );
      Object.entries(featureDeclarations).forEach(
        ([featureSelector, declarations]) => {
          if (declarations.length) {
            let selectorForRule = variationName ? getBlockStyleVariationFeatureSelector(
              variationName,
              featureSelector
            ) : featureSelector;
            selectorForRule = selectorSuffix ? appendToSelector(selectorForRule, selectorSuffix) : selectorForRule;
            const rules = declarations.join(";");
            ruleset += `:root :where(${selectorForRule}){${rules};}`;
          }
        }
      );
    }
    if (duotoneSelector) {
      const duotoneStyles = {};
      if (styles?.filter) {
        duotoneStyles.filter = styles.filter;
        delete styles.filter;
      }
      const duotoneDeclarations = getStylesDeclarations(duotoneStyles);
      if (duotoneDeclarations.length) {
        ruleset += `${duotoneSelector}{${duotoneDeclarations.join(
          ";"
        )};}`;
      }
    }
    const selectorForLayout = layoutSelector ?? effectiveSelector;
    const hasBlockGapSupportForLayout = layoutHasBlockGapSupport ?? hasBlockGapSupport;
    if (!disableLayoutStyles && (ROOT_BLOCK_SELECTOR === selectorForLayout || hasLayoutSupport)) {
      ruleset += getLayoutStyles({
        style: styles,
        selector: selectorForLayout,
        hasBlockGapSupport: hasBlockGapSupportForLayout,
        hasFallbackGapSupport,
        fallbackGapValue
      });
    }
    const styleDeclarations = getStylesDeclarations(
      styles,
      effectiveSelector,
      useRootPaddingAlign,
      tree,
      disableRootPadding
    );
    if (styleDeclarations?.length) {
      const generalSelector = skipSelectorWrapper ? effectiveSelector : `:root :where(${effectiveSelector})`;
      ruleset += `${generalSelector}{${styleDeclarations.join(";")};}`;
    }
    if (styles?.css) {
      ruleset += processCSSNesting(
        styles.css,
        `:root :where(${effectiveSelector})`
      );
    }
    if (mediaQuery && ruleset) {
      return `${mediaQuery}{${ruleset}}`;
    }
    return ruleset;
  }
  var transformToStyles = (tree, blockSelectors, hasBlockGapSupport, hasFallbackGapSupport, disableLayoutStyles = false, disableRootPadding = false, styleOptions = {}) => {
    const options = {
      blockGap: true,
      blockStyles: true,
      layoutStyles: true,
      marginReset: true,
      presets: true,
      rootPadding: true,
      variationStyles: false,
      ...styleOptions
    };
    const normalizedTree = normalizeStyleStateAliases(tree);
    const nodesWithStyles = getNodesWithStyles(
      normalizedTree,
      blockSelectors
    );
    const nodesWithSettings = getNodesWithSettings(
      normalizedTree,
      blockSelectors
    );
    const useRootPaddingAlign = normalizedTree?.settings?.useRootPaddingAwareAlignments;
    const { contentSize, wideSize } = normalizedTree?.settings?.layout || {};
    const hasBodyStyles = options.marginReset || options.rootPadding || options.layoutStyles;
    let ruleset = "";
    if (options.presets && (contentSize || wideSize)) {
      ruleset += `${ROOT_CSS_PROPERTIES_SELECTOR} {`;
      ruleset = contentSize ? ruleset + ` --wp--style--global--content-size: ${contentSize};` : ruleset;
      ruleset = wideSize ? ruleset + ` --wp--style--global--wide-size: ${wideSize};` : ruleset;
      ruleset += "}";
    }
    if (hasBodyStyles) {
      ruleset += ":where(body) {margin: 0;";
      if (options.rootPadding && useRootPaddingAlign) {
        ruleset += `padding-right: 0; padding-left: 0; padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom) }
				.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }
				.has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }
				.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) { padding-right: 0; padding-left: 0; }
				.has-global-padding :where(:not(.alignfull.is-layout-flow) > .has-global-padding:not(.wp-block-block, .alignfull)) > .alignfull { margin-left: 0; margin-right: 0;
				`;
      }
      ruleset += "}";
    }
    if (options.blockStyles) {
      const responsiveMediaQueries = getResponsiveMediaQueries(tree);
      nodesWithStyles.forEach((node) => {
        if (node.isStyleVariation && !options.variationStyles) {
          return;
        }
        const responsiveNodes = getResponsiveStyleNodes(
          node,
          responsiveMediaQueries
        );
        [
          node,
          ...responsiveNodes,
          ...getPseudoStyleNodes(node),
          ...responsiveNodes.flatMap(getPseudoStyleNodes)
        ].forEach((expandedNode) => {
          ruleset += renderStylesNode(expandedNode, {
            tree: normalizedTree,
            useRootPaddingAlign,
            disableLayoutStyles,
            hasBlockGapSupport,
            hasFallbackGapSupport,
            disableRootPadding
          });
        });
      });
    }
    if (options.layoutStyles) {
      ruleset = ruleset + ".wp-site-blocks > .alignleft { float: left; margin-right: 2em; }";
      ruleset = ruleset + ".wp-site-blocks > .alignright { float: right; margin-left: 2em; }";
      ruleset = ruleset + ".wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }";
    }
    if (options.blockGap && hasBlockGapSupport) {
      const gapValue = getGapCSSValue(normalizedTree?.styles?.spacing?.blockGap) || "0.5em";
      ruleset = ruleset + `:root :where(.wp-site-blocks) > * { margin-block-start: ${gapValue}; margin-block-end: 0; }`;
      ruleset = ruleset + ":root :where(.wp-site-blocks) > :first-child { margin-block-start: 0; }";
      ruleset = ruleset + ":root :where(.wp-site-blocks) > :last-child { margin-block-end: 0; }";
    }
    if (options.presets) {
      nodesWithSettings.forEach(({ selector: selector2, presets }) => {
        if (ROOT_BLOCK_SELECTOR === selector2 || ROOT_CSS_PROPERTIES_SELECTOR === selector2) {
          selector2 = "";
        }
        const classes = getPresetsClasses(selector2, presets);
        if (classes.length > 0) {
          ruleset += classes;
        }
      });
    }
    return ruleset;
  };
  function generateSvgFilters(tree, blockSelectors) {
    const nodesWithSettings = getNodesWithSettings(tree, blockSelectors);
    return nodesWithSettings.flatMap(({ presets }) => {
      return getPresetsSvgFilters(presets);
    });
  }
  var getSelectorsConfig = (blockType, rootSelector) => {
    if (blockType?.selectors && Object.keys(blockType.selectors).length > 0) {
      return blockType.selectors;
    }
    const config2 = {
      root: rootSelector
    };
    Object.entries(BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS).forEach(
      ([featureKey, featureName]) => {
        const featureSelector = getBlockSelector(blockType, featureKey);
        if (featureSelector) {
          config2[featureName] = featureSelector;
        }
      }
    );
    return config2;
  };
  var getBlockSelectors = (blockTypes, variationInstanceId) => {
    const { getBlockStyles } = (0, import_data21.select)(import_blocks3.store);
    const result = {};
    blockTypes.forEach((blockType) => {
      const name2 = blockType.name;
      const selector2 = getBlockSelector(blockType);
      if (!selector2) {
        return;
      }
      let duotoneSelector = getBlockSelector(blockType, "filter.duotone");
      if (!duotoneSelector) {
        const rootSelector = getBlockSelector(blockType);
        const duotoneSupport = (0, import_blocks3.getBlockSupport)(
          blockType,
          "color.__experimentalDuotone",
          false
        );
        if (typeof duotoneSupport === "string" && rootSelector) {
          duotoneSelector = scopeSelector(rootSelector, duotoneSupport);
        }
      }
      const hasLayoutSupport = !!blockType?.supports?.layout || !!blockType?.supports?.__experimentalLayout;
      const fallbackGapValue = (
        // @ts-expect-error
        blockType?.supports?.spacing?.blockGap?.__experimentalDefault
      );
      const blockStyleVariations = getBlockStyles(name2);
      const styleVariationSelectors = {};
      blockStyleVariations?.forEach((variation) => {
        const variationSuffix = variationInstanceId ? `-${variationInstanceId}` : "";
        const variationName = `${variation.name}${variationSuffix}`;
        const styleVariationSelector = getBlockStyleVariationSelector(
          variationName,
          selector2
        );
        styleVariationSelectors[variationName] = styleVariationSelector;
      });
      const featureSelectors = getSelectorsConfig(blockType, selector2);
      result[name2] = {
        duotoneSelector: duotoneSelector ?? void 0,
        fallbackGapValue,
        featureSelectors: Object.keys(featureSelectors).length ? featureSelectors : void 0,
        hasLayoutSupport,
        name: name2,
        selector: selector2,
        styleVariationSelectors: blockStyleVariations?.length ? styleVariationSelectors : void 0
      };
    });
    return result;
  };
  function updateConfigWithSeparator(config2) {
    const blocks = config2.styles?.blocks;
    const separatorBlock = blocks?.["core/separator"];
    const needsSeparatorStyleUpdate = separatorBlock && separatorBlock.color?.background && !separatorBlock.color?.text && !separatorBlock.border?.color;
    if (needsSeparatorStyleUpdate) {
      return {
        ...config2,
        styles: {
          ...config2.styles,
          blocks: {
            ...blocks,
            "core/separator": {
              ...separatorBlock,
              color: {
                ...separatorBlock.color,
                text: separatorBlock.color?.background
              }
            }
          }
        }
      };
    }
    return config2;
  }
  function processCSSNesting(css, blockSelector) {
    let processedCSS = "";
    if (!css || css.trim() === "") {
      return processedCSS;
    }
    const parts = css.split("&");
    parts.forEach((part) => {
      if (!part || part.trim() === "") {
        return;
      }
      const isRootCss = !part.includes("{");
      if (isRootCss) {
        processedCSS += `:root :where(${blockSelector}){${part.trim()}}`;
      } else {
        const splitPart = part.replace("}", "").split("{");
        if (splitPart.length !== 2) {
          return;
        }
        const [nestedSelector, cssValue] = splitPart;
        const matches = nestedSelector.match(/([>+~\s]*::[a-zA-Z-]+)/);
        const pseudoPart = matches ? matches[1] : "";
        const withoutPseudoElement = matches ? nestedSelector.replace(pseudoPart, "").trim() : nestedSelector.trim();
        let combinedSelector;
        if (withoutPseudoElement === "") {
          combinedSelector = blockSelector;
        } else {
          combinedSelector = nestedSelector.startsWith(" ") ? scopeSelector(blockSelector, withoutPseudoElement) : appendToSelector(blockSelector, withoutPseudoElement);
        }
        processedCSS += `:root :where(${combinedSelector})${pseudoPart}{${cssValue.trim()}}`;
      }
    });
    return processedCSS;
  }
  function generateGlobalStyles(config2 = {}, blockTypes = [], options = {}) {
    const {
      hasBlockGapSupport: hasBlockGapSupportOption,
      hasFallbackGapSupport: hasFallbackGapSupportOption,
      disableLayoutStyles = false,
      disableRootPadding = false,
      styleOptions = {}
    } = options;
    const blocks = blockTypes.length > 0 ? blockTypes : (0, import_blocks3.getBlockTypes)();
    const blockGap = getSetting(config2, "spacing.blockGap");
    const hasBlockGapSupport = hasBlockGapSupportOption ?? blockGap !== null;
    const hasFallbackGapSupport = hasFallbackGapSupportOption ?? !hasBlockGapSupport;
    if (!config2?.styles || !config2?.settings) {
      return [[], {}];
    }
    const updatedConfig = updateConfigWithSeparator(config2);
    const blockSelectors = getBlockSelectors(blocks);
    const customProperties = generateCustomProperties(
      updatedConfig,
      blockSelectors
    );
    const globalStyles = transformToStyles(
      updatedConfig,
      blockSelectors,
      hasBlockGapSupport,
      hasFallbackGapSupport,
      disableLayoutStyles,
      disableRootPadding,
      styleOptions
    );
    const svgs = generateSvgFilters(updatedConfig, blockSelectors);
    const styles = [
      {
        css: customProperties,
        isGlobalStyles: true
      },
      {
        css: globalStyles,
        isGlobalStyles: true
      },
      // Load custom CSS in own stylesheet so that any invalid CSS entered in the input won't break all the global styles in the editor.
      {
        css: updatedConfig?.styles?.css ?? "",
        isGlobalStyles: true
      },
      {
        assets: svgs,
        __unstableType: "svgs",
        isGlobalStyles: true
      }
    ];
    blocks.forEach((blockType) => {
      const blockStyles = updatedConfig?.styles?.blocks?.[blockType.name];
      if (blockStyles?.css) {
        const { featureSelectors } = blockSelectors[blockType.name];
        const cssFeatureSelector = typeof featureSelectors === "object" ? featureSelectors?.css : void 0;
        let resolvedCssSelector;
        if (typeof cssFeatureSelector === "string") {
          resolvedCssSelector = cssFeatureSelector;
        } else if (typeof cssFeatureSelector === "object") {
          resolvedCssSelector = cssFeatureSelector?.root;
        }
        const selector2 = resolvedCssSelector ?? blockSelectors[blockType.name].selector;
        styles.push({
          css: processCSSNesting(blockStyles.css, selector2),
          isGlobalStyles: true
        });
      }
    });
    return [styles, updatedConfig.settings];
  }

  // packages/global-styles-engine/build-module/variation.mjs
  function getVariationStyle(globalStyles, name2, variation, { resolveRefs = true } = {}) {
    if (!globalStyles?.styles?.blocks?.[name2]?.variations?.[variation]) {
      return void 0;
    }
    const replaceRefs = (variationStyles) => {
      Object.keys(variationStyles).forEach((key) => {
        const value = variationStyles[key];
        if (typeof value === "object" && value !== null) {
          if (value.ref !== void 0) {
            if (typeof value.ref !== "string" || value.ref.trim() === "") {
              delete variationStyles[key];
            } else {
              const refValue = getValueFromObjectPath(
                globalStyles,
                value.ref
              );
              if (refValue !== void 0 && refValue !== null) {
                variationStyles[key] = refValue;
              } else {
                delete variationStyles[key];
              }
            }
          } else {
            replaceRefs(value);
            if (Object.keys(value).length === 0) {
              delete variationStyles[key];
            }
          }
        }
      });
    };
    const styles = JSON.parse(
      JSON.stringify(
        globalStyles.styles.blocks[name2].variations[variation]
      )
    );
    if (resolveRefs) {
      replaceRefs(styles);
    }
    return styles;
  }

  // packages/global-styles-engine/build-module/resolve-style.mjs
  var DEFAULT_STATE_VALUE = "default";
  function isDefaultBlockStyleState(selectedState) {
    const viewport = selectedState?.viewport;
    const pseudoState = selectedState?.pseudoState;
    return (!viewport || viewport === DEFAULT_STATE_VALUE) && (!pseudoState || pseudoState === DEFAULT_STATE_VALUE);
  }
  function getStyleStatePath(selectedState) {
    if (isDefaultBlockStyleState(selectedState)) {
      return [];
    }
    return [selectedState.viewport, selectedState.pseudoState].filter(
      (state) => !!state && state !== DEFAULT_STATE_VALUE
    );
  }
  function getStyleForState(style, selectedState) {
    const path = getStyleStatePath(selectedState);
    if (!path.length) {
      return style;
    }
    return getValueFromObjectPath(style, path);
  }
  var TREE_STRUCTURAL_KEYS = /* @__PURE__ */ new Set(["blocks", "variations", "css"]);
  var EMPTY_INHERITANCE = Object.freeze({
    value: {},
    sources: {}
  });
  var SOURCE_DESCRIPTORS = {
    root: { layer: "root" },
    element: { layer: "element" },
    block: { layer: "block" },
    blockVariation: { layer: "blockVariation" }
  };
  function createSourceDescriptor(type) {
    const descriptor = SOURCE_DESCRIPTORS[type];
    if (!descriptor) {
      return null;
    }
    return { ...descriptor };
  }
  function createContribution(styles, source) {
    if (!styles || !source) {
      return null;
    }
    return { styles, source };
  }
  function getPathKey(path) {
    return path.join(".");
  }
  function getSourceForPath(source) {
    return { ...source };
  }
  function isExplicitEmpty(value) {
    if (value === "" || value === null) {
      return true;
    }
    if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) {
      return true;
    }
    return false;
  }
  function isRefObject(value) {
    return value !== null && typeof value === "object" && !Array.isArray(value) && typeof value.ref === "string";
  }
  function pickLayerRootContribution(layer) {
    if (!layer || typeof layer !== "object" || Array.isArray(layer)) {
      return null;
    }
    const contribution = {};
    for (const key of Object.keys(layer)) {
      if (TREE_STRUCTURAL_KEYS.has(key)) {
        continue;
      }
      if (key === "elements") {
        if (layer.elements && typeof layer.elements === "object") {
          contribution.elements = layer.elements;
        }
        continue;
      }
      if (isExplicitEmpty(layer[key])) {
        continue;
      }
      contribution[key] = layer[key];
    }
    return Object.keys(contribution).length === 0 ? null : contribution;
  }
  var ATOMIC_OBJECT_KEYS = /* @__PURE__ */ new Set(["backgroundImage"]);
  function deepMergeDroppingEmpties(target, source, globalStyles, sourceMetadata, sources, path = []) {
    if (!source || typeof source !== "object" || Array.isArray(source)) {
      return target;
    }
    for (const key of Object.keys(source)) {
      let sourceValue = source[key];
      if (isExplicitEmpty(sourceValue)) {
        continue;
      }
      if (isRefObject(sourceValue)) {
        if (sourceValue.ref.trim() === "") {
          continue;
        }
        const resolved = getValueFromObjectPath(
          globalStyles,
          sourceValue.ref
        );
        if (resolved === void 0 || resolved === null || isRefObject(resolved)) {
          continue;
        }
        sourceValue = resolved;
      }
      const nextPath = [...path, key];
      if (!ATOMIC_OBJECT_KEYS.has(key) && sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && !isRefObject(sourceValue)) {
        const existing = target[key] && typeof target[key] === "object" && !Array.isArray(target[key]) ? target[key] : {};
        target[key] = deepMergeDroppingEmpties(
          { ...existing },
          sourceValue,
          globalStyles,
          sourceMetadata,
          sources,
          nextPath
        );
      } else {
        target[key] = ATOMIC_OBJECT_KEYS.has(key) && sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) ? { ...sourceValue } : sourceValue;
        if (sourceMetadata && sources) {
          sources[getPathKey(nextPath)] = getSourceForPath(sourceMetadata);
        }
      }
    }
    return target;
  }
  function getStateSlice(layerObject, selectedState) {
    if (!layerObject) {
      return null;
    }
    const slice = getStyleForState(layerObject, selectedState);
    return slice && typeof slice === "object" && !Array.isArray(slice) ? slice : null;
  }
  var NON_CASCADING_ROOT_PREFIXES = [
    "color.background",
    "color.gradient",
    "background",
    "spacing",
    "dimensions",
    "border",
    "shadow",
    "filter"
  ];
  function isNonCascadingRootPath(pathKey) {
    if (pathKey.startsWith("elements.")) {
      return false;
    }
    return NON_CASCADING_ROOT_PREFIXES.some(
      (prefix2) => pathKey === prefix2 || pathKey.startsWith(`${prefix2}.`)
    );
  }
  function deleteAtPath(target, pathSegments) {
    if (!target || typeof target !== "object") {
      return;
    }
    const [head2, ...rest] = pathSegments;
    if (rest.length === 0) {
      delete target[head2];
      return;
    }
    const child = target[head2];
    if (child && typeof child === "object") {
      deleteAtPath(child, rest);
      if (Object.keys(child).length === 0) {
        delete target[head2];
      }
    }
  }
  function dropNonCascadingRootLeaves(value, sources) {
    for (const pathKey of Object.keys(sources)) {
      if (sources[pathKey].layer === "root" && isNonCascadingRootPath(pathKey)) {
        deleteAtPath(value, pathKey.split("."));
        delete sources[pathKey];
      }
    }
  }
  function resolveThemeFileBackgroundImage(value, globalStyles, links) {
    const image = value?.background?.backgroundImage;
    if (!image) {
      return;
    }
    const resolved = getResolvedValue(image, {
      ...globalStyles,
      _links: links ?? void 0
    });
    if (resolved !== void 0) {
      value.background.backgroundImage = resolved;
    }
  }
  function computeResolvedStyle(globalStyles, {
    blockName,
    variationName = null,
    elements: elements2 = null,
    viewport = null,
    pseudoState = null
  } = {}) {
    if (!globalStyles || !globalStyles.styles) {
      return EMPTY_INHERITANCE;
    }
    if (!blockName) {
      return EMPTY_INHERITANCE;
    }
    const styles = globalStyles.styles;
    const selectedState = { viewport, pseudoState };
    const root = styles;
    const block = styles.blocks?.[blockName] ?? null;
    const elementLayers = (elements2 ?? []).map((elementName) => styles.elements?.[elementName] ?? null).filter((layer) => !!layer);
    const variation = variationName ? getVariationStyle(globalStyles, blockName, variationName) ?? null : null;
    const contributions = [
      createContribution(
        pickLayerRootContribution(root),
        createSourceDescriptor("root")
      ),
      ...elementLayers.map(
        (layer) => createContribution(
          pickLayerRootContribution(layer),
          createSourceDescriptor("element")
        )
      ),
      block ? createContribution(
        pickLayerRootContribution(block),
        createSourceDescriptor("block")
      ) : null,
      variation ? createContribution(
        pickLayerRootContribution(variation),
        createSourceDescriptor("blockVariation")
      ) : null
    ];
    if (!isDefaultBlockStyleState(selectedState)) {
      contributions.push(
        createContribution(
          pickLayerRootContribution(
            getStateSlice(root, selectedState)
          ),
          createSourceDescriptor("root")
        ),
        ...elementLayers.map(
          (layer) => createContribution(
            pickLayerRootContribution(
              getStateSlice(layer, selectedState)
            ),
            createSourceDescriptor("element")
          )
        ),
        block ? createContribution(
          pickLayerRootContribution(
            getStateSlice(block, selectedState)
          ),
          createSourceDescriptor("block")
        ) : null,
        variation ? createContribution(
          pickLayerRootContribution(
            getStateSlice(variation, selectedState)
          ),
          createSourceDescriptor("blockVariation")
        ) : null
      );
    }
    const filteredContributions = contributions.filter(
      Boolean
    );
    if (filteredContributions.length === 0) {
      return EMPTY_INHERITANCE;
    }
    const sources = {};
    const value = filteredContributions.reduce(
      (mergedValue, contribution) => deepMergeDroppingEmpties(
        mergedValue,
        contribution.styles,
        globalStyles,
        contribution.source,
        sources
      ),
      {}
    );
    dropNonCascadingRootLeaves(value, sources);
    resolveThemeFileBackgroundImage(
      value,
      globalStyles,
      globalStyles._links ?? null
    );
    return { value, sources };
  }
  var NO_LINKS = {};
  var memo2 = /* @__PURE__ */ new WeakMap();
  function resolveStyle2(globalStyles, context = {}) {
    const styleData = globalStyles?.styles;
    if (!styleData || typeof styleData !== "object") {
      return computeResolvedStyle(globalStyles, context);
    }
    let byLinks = memo2.get(styleData);
    if (!byLinks) {
      byLinks = /* @__PURE__ */ new WeakMap();
      memo2.set(styleData, byLinks);
    }
    const linksKey = globalStyles?._links ?? NO_LINKS;
    let inner = byLinks.get(linksKey);
    if (!inner) {
      inner = /* @__PURE__ */ new Map();
      byLinks.set(linksKey, inner);
    }
    const sliceKey = `${context.elements?.join(",") ?? ""}:${context.viewport ?? ""}:${context.pseudoState ?? ""}`;
    const key = (context.blockName || "") + "" + (context.variationName || "") + "" + sliceKey;
    if (inner.has(key)) {
      return inner.get(key);
    }
    const result = computeResolvedStyle(globalStyles, context);
    inner.set(key, result);
    return result;
  }

  // packages/global-styles-engine/build-module/lock-unlock.mjs
  var import_private_apis3 = __toESM(require_private_apis(), 1);
  var { lock: lock3, unlock: unlock3 } = (0, import_private_apis3.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
    "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
    "@wordpress/global-styles-engine"
  );

  // packages/global-styles-engine/build-module/private-apis.mjs
  var privateApis2 = {};
  lock3(privateApis2, {
    getResponsiveMediaQueries,
    getViewportBreakpoints,
    getViewportBreakpointValueInPixels,
    resolveStyle: resolveStyle2,
    getVariationStyle
  });

  // packages/edit-site/build-module/components/block-editor/use-navigate-to-entity-record.mjs
  var import_data23 = __toESM(require_data(), 1);
  var import_router12 = __toESM(require_router(), 1);
  var import_element50 = __toESM(require_element(), 1);
  var import_url5 = __toESM(require_url(), 1);
  var import_core_data16 = __toESM(require_core_data(), 1);
  var import_editor12 = __toESM(require_editor(), 1);

  // packages/edit-site/build-module/components/block-editor/use-viewport-sync.mjs
  var import_element49 = __toESM(require_element(), 1);
  var import_data22 = __toESM(require_data(), 1);
  var import_router11 = __toESM(require_router(), 1);
  var import_editor11 = __toESM(require_editor(), 1);
  var { useLocation: useLocation11 } = unlock(import_router11.privateApis);
  var DEFAULT_DEVICE_TYPE = "Desktop";
  var VALID_DEVICE_TYPES = ["desktop", "tablet", "mobile"];
  var capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
  function useViewportSync() {
    const { query } = useLocation11();
    const { setDeviceType } = (0, import_data22.useDispatch)(import_editor11.store);
    (0, import_element49.useEffect)(() => {
      const viewport = query?.viewport?.toLowerCase();
      const isValid2 = VALID_DEVICE_TYPES.includes(viewport);
      setDeviceType(isValid2 ? capitalize(viewport) : DEFAULT_DEVICE_TYPE);
    }, [query?.viewport, setDeviceType]);
  }
  function ViewportSync() {
    useViewportSync();
    return null;
  }

  // packages/edit-site/build-module/components/block-editor/use-navigate-to-entity-record.mjs
  var { useHistory: useHistory7, useLocation: useLocation12 } = unlock(import_router12.privateApis);
  var VALID_VIEWPORTS = ["desktop", "tablet", "mobile"];
  function useNavigateToEntityRecord() {
    const history = useHistory7();
    const location = useLocation12();
    const { query, path } = location;
    const registry = (0, import_data23.useRegistry)();
    const currentDeviceType = (0, import_data23.useSelect)(
      (select4) => select4(import_editor12.store).getDeviceType(),
      []
    );
    const onNavigateToEntityRecord = (0, import_element50.useCallback)(
      (params) => {
        const currentPostType = registry.select(import_editor12.store).getCurrentPostType();
        const currentPostId = registry.select(import_editor12.store).getCurrentPostId();
        const entityEdits = registry.select(import_core_data16.store).getEntityRecordEdits(
          "postType",
          currentPostType,
          currentPostId
        );
        const externalClientId = entityEdits?.selection?.selectionStart?.clientId;
        const urlUpdates = { ...query };
        if (externalClientId) {
          urlUpdates.selectedBlock = externalClientId;
        }
        const requestedViewport = typeof params.viewport === "string" ? params.viewport.toLowerCase() : void 0;
        const isValidRequestedViewport = VALID_VIEWPORTS.includes(requestedViewport);
        if (isValidRequestedViewport) {
          const currentViewportLower = (currentDeviceType || DEFAULT_DEVICE_TYPE).toLowerCase();
          if (currentViewportLower === DEFAULT_DEVICE_TYPE.toLowerCase()) {
            delete urlUpdates.viewport;
          } else {
            urlUpdates.viewport = currentViewportLower;
          }
        }
        const hasUpdatesToSave = externalClientId || isValidRequestedViewport;
        if (hasUpdatesToSave) {
          history.navigate((0, import_url5.addQueryArgs)(path, urlUpdates), {
            replace: true
          });
        }
        const queryArgs = {
          canvas: "edit",
          focusMode: true
        };
        if (isValidRequestedViewport) {
          queryArgs.viewport = requestedViewport;
        }
        const url = (0, import_url5.addQueryArgs)(
          `/${params.postType}/${params.postId}`,
          queryArgs
        );
        history.navigate(url);
      },
      [history, path, query, registry, currentDeviceType]
    );
    return onNavigateToEntityRecord;
  }

  // packages/edit-site/build-module/components/block-editor/use-site-editor-settings.mjs
  var { useLocation: useLocation13, useHistory: useHistory8 } = unlock(import_router13.privateApis);
  var { useGlobalStyles: useGlobalStyles2 } = unlock(import_editor13.privateApis);
  function useNavigateToPreviousEntityRecord() {
    const location = useLocation13();
    const previousCanvas = (0, import_compose3.usePrevious)(location.query.canvas);
    const history = useHistory8();
    const goBack = (0, import_element51.useMemo)(() => {
      const isFocusMode = location.query.focusMode || location?.params?.postId && FOCUSABLE_ENTITIES.includes(location?.params?.postType);
      const didComeFromEditorCanvas = previousCanvas === "edit";
      const showBackButton = isFocusMode && didComeFromEditorCanvas;
      return showBackButton ? () => history.back() : void 0;
    }, [location, history, previousCanvas]);
    return goBack;
  }
  function useSpecificEditorSettings() {
    const { query } = useLocation13();
    const { canvas = "view" } = query;
    const onNavigateToEntityRecord = useNavigateToEntityRecord();
    const { merged: mergedConfig } = useGlobalStyles2();
    const { settings: settings2, currentPostIsTrashed } = (0, import_data24.useSelect)((select4) => {
      const { getSettings: getSettings7 } = select4(store);
      const { getCurrentPostAttribute } = select4(import_editor13.store);
      return {
        settings: getSettings7(),
        currentPostIsTrashed: getCurrentPostAttribute("status") === "trash"
      };
    }, []);
    const onNavigateToPreviousEntityRecord = useNavigateToPreviousEntityRecord();
    const [globalStyles, globalSettings] = (0, import_element51.useMemo)(() => {
      return generateGlobalStyles(mergedConfig, [], {
        disableRootPadding: false
      });
    }, [mergedConfig]);
    const defaultEditorSettings = (0, import_element51.useMemo)(() => {
      const nonGlobalStyles = (settings2?.styles ?? []).filter(
        (style) => !style.isGlobalStyles
      );
      return {
        ...settings2,
        styles: [
          ...nonGlobalStyles,
          ...globalStyles,
          {
            // Forming a "block formatting context" to prevent margin collapsing.
            // @see https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context
            css: canvas === "view" ? `body{min-height: 100vh; ${currentPostIsTrashed ? "" : "cursor: pointer;"}}` : void 0
          }
        ],
        __experimentalFeatures: globalSettings,
        richEditingEnabled: true,
        supportsTemplateMode: true,
        focusMode: canvas !== "view",
        onNavigateToEntityRecord,
        onNavigateToPreviousEntityRecord,
        isPreviewMode: canvas === "view"
      };
    }, [
      settings2,
      globalStyles,
      globalSettings,
      canvas,
      currentPostIsTrashed,
      onNavigateToEntityRecord,
      onNavigateToPreviousEntityRecord
    ]);
    return defaultEditorSettings;
  }

  // packages/edit-site/build-module/components/plugin-template-setting-panel/index.mjs
  var import_editor14 = __toESM(require_editor(), 1);
  var import_data25 = __toESM(require_data(), 1);
  var import_components16 = __toESM(require_components(), 1);
  var import_deprecated3 = __toESM(require_deprecated(), 1);
  var import_jsx_runtime116 = __toESM(require_jsx_runtime(), 1);
  var { Fill, Slot } = (0, import_components16.createSlotFill)("PluginTemplateSettingPanel");
  var PluginTemplateSettingPanel = ({ children }) => {
    (0, import_deprecated3.default)("wp.editSite.PluginTemplateSettingPanel", {
      since: "6.6",
      version: "6.8",
      alternative: "wp.editor.PluginDocumentSettingPanel"
    });
    const isCurrentEntityTemplate = (0, import_data25.useSelect)(
      (select4) => select4(import_editor14.store).getCurrentPostType() === "wp_template",
      []
    );
    if (!isCurrentEntityTemplate) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Fill, { children });
  };
  PluginTemplateSettingPanel.Slot = Slot;
  var plugin_template_setting_panel_default = PluginTemplateSettingPanel;

  // packages/edit-site/build-module/components/more-menu/index.mjs
  var import_editor15 = __toESM(require_editor(), 1);

  // packages/edit-site/build-module/components/more-menu/site-export.mjs
  var import_i18n16 = __toESM(require_i18n(), 1);
  var import_components17 = __toESM(require_components(), 1);
  var import_api_fetch2 = __toESM(require_api_fetch(), 1);
  var import_data26 = __toESM(require_data(), 1);
  var import_blob = __toESM(require_blob(), 1);
  var import_core_data17 = __toESM(require_core_data(), 1);
  var import_notices2 = __toESM(require_notices(), 1);
  var import_jsx_runtime117 = __toESM(require_jsx_runtime(), 1);
  function SiteExport() {
    const canExport = (0, import_data26.useSelect)((select4) => {
      const targetHints = select4(import_core_data17.store).getCurrentTheme()?._links?.["wp:export-theme"]?.[0]?.targetHints ?? {};
      return !!targetHints.allow?.includes("GET");
    }, []);
    const { createErrorNotice } = (0, import_data26.useDispatch)(import_notices2.store);
    if (!canExport) {
      return null;
    }
    async function handleExport() {
      try {
        const response = await (0, import_api_fetch2.default)({
          path: "/wp-block-editor/v1/export",
          parse: false,
          headers: {
            Accept: "application/zip"
          }
        });
        const blob = await response.blob();
        const contentDisposition = response.headers.get(
          "content-disposition"
        );
        const contentDispositionMatches = contentDisposition.match(/=(.+)\.zip/);
        const fileName = contentDispositionMatches[1] ? contentDispositionMatches[1] : "edit-site-export";
        (0, import_blob.downloadBlob)(fileName + ".zip", blob, "application/zip");
      } catch (errorResponse) {
        let error2 = {};
        try {
          error2 = await errorResponse.json();
        } catch {
        }
        const errorMessage = error2.message && error2.code !== "unknown_error" ? error2.message : (0, import_i18n16.__)("An error occurred while creating the site export.");
        createErrorNotice(errorMessage, { type: "snackbar" });
      }
    }
    return /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(
      import_components17.MenuItem,
      {
        role: "menuitem",
        icon: download_default,
        onClick: handleExport,
        info: (0, import_i18n16.__)(
          "Download your theme with updated templates and styles."
        ),
        children: (0, import_i18n16._x)("Export", "site exporter menu item")
      }
    );
  }

  // packages/edit-site/build-module/components/more-menu/welcome-guide-menu-item.mjs
  var import_i18n17 = __toESM(require_i18n(), 1);
  var import_data27 = __toESM(require_data(), 1);
  var import_components18 = __toESM(require_components(), 1);
  var import_preferences8 = __toESM(require_preferences(), 1);
  var import_jsx_runtime118 = __toESM(require_jsx_runtime(), 1);
  function WelcomeGuideMenuItem() {
    const { toggle } = (0, import_data27.useDispatch)(import_preferences8.store);
    return /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(import_components18.MenuItem, { onClick: () => toggle("core/edit-site", "welcomeGuide"), children: (0, import_i18n17.__)("Welcome Guide") });
  }

  // packages/edit-site/build-module/components/more-menu/index.mjs
  var import_jsx_runtime119 = __toESM(require_jsx_runtime(), 1);
  var { ToolsMoreMenuGroup, PreferencesModal } = unlock(import_editor15.privateApis);
  function MoreMenu() {
    return /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)(import_jsx_runtime119.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)(ToolsMoreMenuGroup, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(SiteExport, {}),
        /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(WelcomeGuideMenuItem, {})
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(PreferencesModal, {})
    ] });
  }

  // packages/edit-site/build-module/components/block-editor/use-editor-iframe-props.mjs
  var import_data28 = __toESM(require_data(), 1);
  var import_keycodes2 = __toESM(require_keycodes(), 1);
  var import_element52 = __toESM(require_element(), 1);
  var import_i18n18 = __toESM(require_i18n(), 1);
  var import_editor16 = __toESM(require_editor(), 1);
  var import_router14 = __toESM(require_router(), 1);
  var import_url6 = __toESM(require_url(), 1);
  var { useLocation: useLocation14, useHistory: useHistory9 } = unlock(import_router14.privateApis);
  function useEditorIframeProps() {
    const { query, path } = useLocation14();
    const history = useHistory9();
    const { canvas = "view" } = query;
    const currentPostIsTrashed = (0, import_data28.useSelect)((select4) => {
      return select4(import_editor16.store).getCurrentPostAttribute("status") === "trash";
    }, []);
    const [isFocused, setIsFocused] = (0, import_element52.useState)(false);
    (0, import_element52.useEffect)(() => {
      if (canvas === "edit") {
        setIsFocused(false);
      }
    }, [canvas]);
    const viewModeIframeProps = {
      "aria-label": (0, import_i18n18.__)("Edit"),
      "aria-disabled": currentPostIsTrashed,
      title: null,
      role: "button",
      tabIndex: 0,
      onFocus: () => setIsFocused(true),
      onBlur: () => setIsFocused(false),
      onKeyDown: (event) => {
        const { keyCode } = event;
        if ((keyCode === import_keycodes2.ENTER || keyCode === import_keycodes2.SPACE) && !currentPostIsTrashed) {
          event.preventDefault();
          history.navigate((0, import_url6.addQueryArgs)(path, { canvas: "edit" }), {
            transition: "canvas-mode-edit-transition"
          });
        }
      },
      onClick: () => history.navigate((0, import_url6.addQueryArgs)(path, { canvas: "edit" }), {
        transition: "canvas-mode-edit-transition"
      }),
      onClickCapture: (event) => {
        if (currentPostIsTrashed) {
          event.preventDefault();
          event.stopPropagation();
        }
      },
      readonly: true
    };
    return {
      className: clsx_default("edit-site-visual-editor__editor-canvas", {
        "is-focused": isFocused && canvas === "view"
      }),
      ...canvas === "view" ? viewModeIframeProps : {}
    };
  }

  // packages/edit-site/build-module/components/editor/use-editor-title.mjs
  var import_i18n20 = __toESM(require_i18n(), 1);
  var import_data30 = __toESM(require_data(), 1);
  var import_core_data19 = __toESM(require_core_data(), 1);
  var import_html_entities2 = __toESM(require_html_entities(), 1);
  var import_editor17 = __toESM(require_editor(), 1);

  // packages/edit-site/build-module/components/routes/use-title.mjs
  var import_element53 = __toESM(require_element(), 1);
  var import_data29 = __toESM(require_data(), 1);
  var import_core_data18 = __toESM(require_core_data(), 1);
  var import_i18n19 = __toESM(require_i18n(), 1);
  var import_a11y = __toESM(require_a11y(), 1);
  var import_html_entities = __toESM(require_html_entities(), 1);
  var import_router15 = __toESM(require_router(), 1);
  var { useLocation: useLocation15 } = unlock(import_router15.privateApis);
  function useTitle(title) {
    const location = useLocation15();
    const siteTitle = (0, import_data29.useSelect)(
      (select4) => select4(import_core_data18.store).getEntityRecord("root", "site")?.title,
      []
    );
    const isInitialLocationRef = (0, import_element53.useRef)(true);
    (0, import_element53.useEffect)(() => {
      isInitialLocationRef.current = false;
    }, [location]);
    (0, import_element53.useEffect)(() => {
      if (isInitialLocationRef.current) {
        return;
      }
      if (title && siteTitle) {
        const formattedTitle = (0, import_i18n19.sprintf)(
          /* translators: Admin document title. 1: Admin screen name, 2: Network or site name. */
          (0, import_i18n19.__)("%1$s \u2039 %2$s \u2039 Editor \u2014 WordPress"),
          (0, import_html_entities.decodeEntities)(title),
          (0, import_html_entities.decodeEntities)(siteTitle)
        );
        document.title = formattedTitle;
        (0, import_a11y.speak)(title, "assertive");
      }
    }, [title, siteTitle, location]);
  }

  // packages/edit-site/build-module/components/editor/use-editor-title.mjs
  var { getTemplateInfo } = unlock(import_editor17.privateApis);
  function useEditorTitle(postType2, postId) {
    const { title, isLoaded } = (0, import_data30.useSelect)(
      (select4) => {
        const {
          getEditedEntityRecord,
          getCurrentTheme,
          hasFinishedResolution
        } = select4(import_core_data19.store);
        if (!postId) {
          return { isLoaded: false };
        }
        const _record = getEditedEntityRecord(
          "postType",
          postType2,
          postId
        );
        const { default_template_types: templateTypes = [] } = getCurrentTheme() ?? {};
        const templateInfo = getTemplateInfo({
          template: _record,
          templateTypes
        });
        const _isLoaded = hasFinishedResolution("getEditedEntityRecord", [
          "postType",
          postType2,
          postId
        ]);
        return {
          title: templateInfo.title,
          isLoaded: _isLoaded
        };
      },
      [postType2, postId]
    );
    let editorTitle;
    if (isLoaded) {
      editorTitle = (0, import_i18n20.sprintf)(
        // translators: A breadcrumb trail for the Admin document title. 1: title of template being edited, 2: type of template (Template or Template Part).
        (0, import_i18n20._x)("%1$s \u2039 %2$s", "breadcrumb trail"),
        (0, import_html_entities2.decodeEntities)(title),
        POST_TYPE_LABELS[postType2] ?? POST_TYPE_LABELS[TEMPLATE_POST_TYPE]
      );
    }
    useTitle(isLoaded && editorTitle);
  }
  var use_editor_title_default = useEditorTitle;

  // packages/edit-site/build-module/components/editor/use-adapt-editor-to-canvas.mjs
  var import_data31 = __toESM(require_data(), 1);
  var import_block_editor4 = __toESM(require_block_editor(), 1);
  var import_editor18 = __toESM(require_editor(), 1);
  var import_element54 = __toESM(require_element(), 1);
  var import_preferences9 = __toESM(require_preferences(), 1);
  function useAdaptEditorToCanvas(canvas) {
    const { clearSelectedBlock } = (0, import_data31.useDispatch)(import_block_editor4.store);
    const {
      editPost,
      setDeviceType,
      closePublishSidebar,
      setIsListViewOpened: setIsListViewOpened2,
      setIsInserterOpened: setIsInserterOpened2
    } = (0, import_data31.useDispatch)(import_editor18.store);
    const { get: getPreference } = (0, import_data31.useSelect)(import_preferences9.store);
    const { getCurrentPost } = (0, import_data31.useSelect)(import_editor18.store);
    const registry = (0, import_data31.useRegistry)();
    (0, import_element54.useLayoutEffect)(() => {
      const isMediumOrBigger = window.matchMedia("(min-width: 782px)").matches;
      registry.batch(() => {
        clearSelectedBlock();
        if (getCurrentPost()?.type) {
          editPost({ selection: void 0 }, { undoIgnore: true });
        }
        setDeviceType(DEFAULT_DEVICE_TYPE);
        closePublishSidebar();
        setIsInserterOpened2(false);
        if (isMediumOrBigger && canvas === "edit" && getPreference("core", "showListViewByDefault") && !getPreference("core", "distractionFree")) {
          setIsListViewOpened2(true);
        } else {
          setIsListViewOpened2(false);
        }
      });
    }, [
      canvas,
      registry,
      clearSelectedBlock,
      editPost,
      setDeviceType,
      closePublishSidebar,
      setIsInserterOpened2,
      setIsListViewOpened2,
      getPreference,
      getCurrentPost
    ]);
  }

  // packages/edit-site/build-module/components/editor/use-resolve-edited-entity.mjs
  var import_element55 = __toESM(require_element(), 1);
  var import_data32 = __toESM(require_data(), 1);
  var import_core_data20 = __toESM(require_core_data(), 1);
  var import_router16 = __toESM(require_router(), 1);
  var { useLocation: useLocation16 } = unlock(import_router16.privateApis);
  var postTypesWithoutParentTemplate = [
    ATTACHMENT_POST_TYPE,
    TEMPLATE_POST_TYPE,
    TEMPLATE_PART_POST_TYPE,
    NAVIGATION_POST_TYPE,
    PATTERN_TYPES.user
  ];
  var authorizedPostTypes = ["page", "post"];
  function getPostType(name2) {
    let postType2;
    if (name2 === "navigation-item") {
      postType2 = NAVIGATION_POST_TYPE;
    } else if (name2 === "pattern-item") {
      postType2 = PATTERN_TYPES.user;
    } else if (name2 === "template-part-item") {
      postType2 = TEMPLATE_PART_POST_TYPE;
    } else if (name2 === "templates") {
      postType2 = TEMPLATE_POST_TYPE;
    } else if (name2 === "template-item") {
      postType2 = TEMPLATE_POST_TYPE;
    } else if (name2 === "page-item" || name2 === "pages") {
      postType2 = "page";
    } else if (name2 === "post-item" || name2 === "posts") {
      postType2 = "post";
    }
    return postType2;
  }
  function useResolveEditedEntity() {
    const { editEntityRecord } = (0, import_data32.useDispatch)(import_core_data20.store);
    const { hasEntityRecord } = (0, import_data32.useSelect)(import_core_data20.store);
    const { name: name2, params = {}, query } = useLocation16();
    const { postId = query?.postId } = params;
    const postType2 = getPostType(name2, postId) ?? query?.postType;
    const { selectedBlock } = query;
    const appliedSelectionRef = (0, import_element55.useRef)(null);
    const homePage = (0, import_data32.useSelect)((select4) => {
      const { getHomePage } = unlock(select4(import_core_data20.store));
      return getHomePage();
    }, []);
    const resolvedTemplateId = (0, import_data32.useSelect)(
      (select4) => {
        if (postTypesWithoutParentTemplate.includes(postType2) && postId) {
          return;
        }
        if (postId && postId.includes(",")) {
          return;
        }
        const { getTemplateId } = unlock(select4(import_core_data20.store));
        if (postType2 && postId && authorizedPostTypes.includes(postType2)) {
          return getTemplateId(postType2, postId);
        }
        if (homePage?.postType === "page") {
          return getTemplateId("page", homePage?.postId);
        }
        if (homePage?.postType === "wp_template") {
          return homePage?.postId;
        }
      },
      [homePage, postId, postType2]
    );
    const context = (0, import_element55.useMemo)(() => {
      if (postTypesWithoutParentTemplate.includes(postType2) && postId) {
        return {};
      }
      if (postType2 && postId && authorizedPostTypes.includes(postType2)) {
        return { postType: postType2, postId };
      }
      if (homePage?.postType === "page") {
        return { postType: "page", postId: homePage?.postId };
      }
      return {};
    }, [homePage, postType2, postId]);
    let entity;
    if (postTypesWithoutParentTemplate.includes(postType2) && postId) {
      entity = { isReady: true, postType: postType2, postId, context };
    } else if (!!homePage) {
      entity = {
        isReady: resolvedTemplateId !== void 0,
        postType: TEMPLATE_POST_TYPE,
        postId: resolvedTemplateId,
        context
      };
    } else {
      entity = { isReady: false };
    }
    if (selectedBlock && entity.isReady && appliedSelectionRef.current !== selectedBlock) {
      const selectionPostType = entity.context?.postId ? entity.context.postType : entity.postType;
      const selectionPostId = entity.context?.postId ? entity.context.postId : entity.postId;
      if (hasEntityRecord("postType", selectionPostType, selectionPostId)) {
        editEntityRecord(
          "postType",
          selectionPostType,
          selectionPostId,
          {
            selection: {
              selectionStart: { clientId: selectedBlock },
              selectionEnd: { clientId: selectedBlock }
            }
          },
          { undoIgnore: true }
        );
        appliedSelectionRef.current = selectedBlock;
      }
    }
    return entity;
  }
  function useSyncDeprecatedEntityIntoState({
    postType: postType2,
    postId,
    context,
    isReady
  }) {
    const { setEditedEntity: setEditedEntity2 } = (0, import_data32.useDispatch)(store);
    (0, import_element55.useEffect)(() => {
      if (isReady) {
        setEditedEntity2(postType2, String(postId), context);
      }
    }, [isReady, postType2, postId, context, setEditedEntity2]);
  }

  // packages/edit-site/build-module/components/editor/site-preview.mjs
  var import_i18n21 = __toESM(require_i18n(), 1);
  var import_data33 = __toESM(require_data(), 1);
  var import_core_data21 = __toESM(require_core_data(), 1);
  var import_dom24 = __toESM(require_dom(), 1);
  var import_url7 = __toESM(require_url(), 1);
  var import_jsx_runtime120 = __toESM(require_jsx_runtime(), 1);
  function SitePreview() {
    const siteUrl = (0, import_data33.useSelect)((select4) => {
      const { getEntityRecord } = select4(import_core_data21.store);
      const siteData = getEntityRecord("root", "__unstableBase");
      return siteData?.home;
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime120.jsx)(
      "iframe",
      {
        src: (0, import_url7.addQueryArgs)(siteUrl, {
          // Parameter for hiding the admin bar.
          wp_site_preview: 1
        }),
        title: (0, import_i18n21.__)("Site Preview"),
        style: {
          display: "block",
          width: "100%",
          height: "100%",
          backgroundColor: "#fff"
        },
        onLoad: (event) => {
          const document2 = event.target.contentDocument;
          const focusableElements = import_dom24.focus.focusable.find(document2);
          focusableElements.forEach((element) => {
            element.style.pointerEvents = "none";
            element.tabIndex = -1;
            element.setAttribute("aria-hidden", "true");
          });
        }
      }
    );
  }

  // packages/edit-site/build-module/components/editor/index.mjs
  var import_jsx_runtime121 = __toESM(require_jsx_runtime(), 1);
  var { Editor, BackButton } = unlock(import_editor19.privateApis);
  var { useHistory: useHistory10, useLocation: useLocation17 } = unlock(import_router17.privateApis);
  var { BlockKeyboardShortcuts } = unlock(import_block_library.privateApis);
  function getListPathForPostType(postType2) {
    switch (postType2) {
      case "navigation":
        return "/navigation";
      case "wp_block":
        return "/pattern?postType=wp_block";
      case "wp_template_part":
        return "/pattern?postType=wp_template_part";
      case "wp_template":
        return "/template";
      case "page":
        return "/page";
      case "post":
        return "/";
    }
    throw "Unknown post type";
  }
  function getNavigationPath(location, postType2) {
    const { path, name: name2 } = location;
    if ([
      "pattern-item",
      "template-part-item",
      "page-item",
      "template-item",
      "static-template-item",
      "post-item"
    ].includes(name2)) {
      return getListPathForPostType(postType2);
    }
    return (0, import_url8.addQueryArgs)(path, { canvas: void 0 });
  }
  function EditSiteEditor({ isHomeRoute = false }) {
    const location = useLocation17();
    const history = useHistory10();
    const { canvas = "view" } = location.query;
    const isLoading = useIsSiteEditorLoading();
    useAdaptEditorToCanvas(canvas);
    const entity = useResolveEditedEntity();
    useSyncDeprecatedEntityIntoState(entity);
    const { postType: postType2, postId, context } = entity;
    const isBlockBasedTheme = (0, import_data34.useSelect)(
      (select4) => select4(import_core_data22.store).getCurrentTheme()?.is_block_theme,
      []
    );
    const postWithTemplate = !!context?.postId;
    use_editor_title_default(
      postWithTemplate ? context.postType : postType2,
      postWithTemplate ? context.postId : postId
    );
    const _isPreviewingTheme = isPreviewingTheme();
    const iframeProps = useEditorIframeProps();
    const isEditMode = canvas === "edit";
    const loadingProgressId = (0, import_compose4.useInstanceId)(
      CanvasLoader,
      "edit-site-editor__loading-progress"
    );
    const editorSettings = useSpecificEditorSettings();
    const { resetZoomLevel } = unlock((0, import_data34.useDispatch)(import_block_editor5.store));
    const { setCurrentRevisionId } = unlock((0, import_data34.useDispatch)(import_editor19.store));
    const { createSuccessNotice } = (0, import_data34.useDispatch)(import_notices3.store);
    const onActionPerformed = (0, import_element56.useCallback)(
      (actionId, items) => {
        switch (actionId) {
          case "move-to-trash":
          case "delete-post":
            {
              history.navigate(
                getListPathForPostType(
                  postWithTemplate ? context.postType : postType2
                )
              );
            }
            break;
          case "duplicate-post":
            {
              const newItem = items[0];
              const _title = typeof newItem.title === "string" ? newItem.title : newItem.title?.rendered;
              createSuccessNotice(
                (0, import_i18n22.sprintf)(
                  // translators: %s: Title of the created post or template, e.g: "Hello world".
                  (0, import_i18n22.__)('"%s" successfully created.'),
                  (0, import_html_entities3.decodeEntities)(_title) || (0, import_i18n22.__)("(no title)")
                ),
                {
                  type: "snackbar",
                  id: "duplicate-post-action",
                  actions: [
                    {
                      label: (0, import_i18n22.__)("Edit"),
                      onClick: () => {
                        history.navigate(
                          `/${newItem.type}/${newItem.id}?canvas=edit`
                        );
                      }
                    }
                  ]
                }
              );
            }
            break;
        }
      },
      [
        postType2,
        context?.postType,
        postWithTemplate,
        history,
        createSuccessNotice
      ]
    );
    const isReady = !isLoading;
    return !isBlockBasedTheme && isHomeRoute ? /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(SitePreview, {}) : /* @__PURE__ */ (0, import_jsx_runtime121.jsxs)(import_jsx_runtime121.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(import_editor19.EditorKeyboardShortcutsRegister, {}),
      isEditMode && /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(BlockKeyboardShortcuts, {}),
      !isReady ? /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(CanvasLoader, { id: loadingProgressId }) : null,
      isEditMode && isReady && /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(
        WelcomeGuide,
        {
          postType: postWithTemplate ? context.postType : postType2
        }
      ),
      isReady && /* @__PURE__ */ (0, import_jsx_runtime121.jsxs)(
        Editor,
        {
          postType: postWithTemplate ? context.postType : postType2,
          postId: postWithTemplate ? context.postId : postId,
          templateId: postWithTemplate ? postId : void 0,
          settings: editorSettings,
          className: "edit-site-editor__editor-interface",
          customSaveButton: _isPreviewingTheme && /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(SaveButton, { size: "compact" }),
          customSavePanel: _isPreviewingTheme && /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(SavePanel, {}),
          iframeProps,
          onActionPerformed,
          extraSidebarPanels: !postWithTemplate && /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(plugin_template_setting_panel_default.Slot, {}),
          children: [
            isEditMode && /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(ViewportSync, {}),
            isEditMode && /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(BackButton, { children: ({ length }) => length <= 1 && /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(
              import_components19.Button,
              {
                size: "compact",
                label: (0, import_i18n22.__)("Open Navigation"),
                showTooltip: true,
                tooltipPosition: "middle right",
                onClick: () => {
                  resetZoomLevel();
                  setCurrentRevisionId(null);
                  history.navigate(
                    getNavigationPath(
                      location,
                      postWithTemplate ? context.postType : postType2
                    ),
                    {
                      transition: "canvas-mode-view-transition"
                    }
                  );
                },
                icon: (0, import_i18n22.isRTL)() ? chevron_right_default : chevron_left_default
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(MoreMenu, {})
          ]
        }
      )
    ] });
  }

  // packages/edit-site/build-module/components/site-editor-routes/utils.mjs
  function isThemeDataLoaded(siteData) {
    return siteData.currentTheme !== void 0 && siteData.currentTheme !== null;
  }
  function isClassicThemeWithStyleBookSupport(siteData) {
    const isBlockTheme = siteData.currentTheme?.is_block_theme;
    const supportsEditorStyles = siteData.currentTheme?.theme_supports["editor-styles"];
    const hasThemeJson = siteData.editorSettings?.supportsLayout;
    return !isBlockTheme && (supportsEditorStyles || hasThemeJson);
  }

  // packages/edit-site/build-module/components/site-editor-routes/home.mjs
  var import_jsx_runtime122 = __toESM(require_jsx_runtime(), 1);
  var homeRoute = {
    name: "home",
    path: "/",
    areas: {
      sidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return null;
        }
        return siteData.currentTheme.is_block_theme || isClassicThemeWithStyleBookSupport(siteData) ? /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(SidebarNavigationScreenMain, {}) : /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(SidebarNavigationScreenUnsupported, {});
      },
      preview({ siteData }) {
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        return isBlockTheme || isClassicThemeWithStyleBookSupport(siteData) ? /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(EditSiteEditor, { isHomeRoute: true }) : void 0;
      },
      mobileSidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(import_jsx_runtime122.Fragment, {});
        }
        return siteData.currentTheme.is_block_theme || isClassicThemeWithStyleBookSupport(siteData) ? /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(SidebarNavigationScreenMain, {}) : /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(SidebarNavigationScreenUnsupported, {});
      }
    }
  };

  // packages/edit-site/build-module/components/sidebar-navigation-screen-identity/index.mjs
  var import_i18n23 = __toESM(require_i18n(), 1);
  var import_jsx_runtime123 = __toESM(require_jsx_runtime(), 1);
  function SidebarNavigationScreenIdentity() {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      SidebarNavigationScreen,
      {
        isRoot: true,
        title: (0, import_i18n23.__)("Design"),
        description: (0, import_i18n23.__)(
          "Customize the appearance of your website using the block editor."
        ),
        content: /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(MainSidebarNavigationContent, {})
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-identity/index.mjs
  var import_i18n74 = __toESM(require_i18n(), 1);
  var import_data41 = __toESM(require_data(), 1);
  var import_core_data24 = __toESM(require_core_data(), 1);

  // packages/dataviews/build-module/dataviews/index.mjs
  var import_element116 = __toESM(require_element(), 1);
  var import_compose18 = __toESM(require_compose(), 1);

  // packages/dataviews/build-module/components/dataviews-context/index.mjs
  var import_element57 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/constants.mjs
  var import_i18n24 = __toESM(require_i18n(), 1);
  var OPERATOR_IS_ANY2 = "isAny";
  var OPERATOR_IS_NONE2 = "isNone";
  var OPERATOR_IS_ALL = "isAll";
  var OPERATOR_IS_NOT_ALL = "isNotAll";
  var OPERATOR_BETWEEN = "between";
  var OPERATOR_IN_THE_PAST = "inThePast";
  var OPERATOR_OVER = "over";
  var OPERATOR_IS = "is";
  var OPERATOR_IS_NOT = "isNot";
  var OPERATOR_LESS_THAN = "lessThan";
  var OPERATOR_GREATER_THAN = "greaterThan";
  var OPERATOR_LESS_THAN_OR_EQUAL = "lessThanOrEqual";
  var OPERATOR_GREATER_THAN_OR_EQUAL = "greaterThanOrEqual";
  var OPERATOR_BEFORE2 = "before";
  var OPERATOR_AFTER2 = "after";
  var OPERATOR_BEFORE_INC = "beforeInc";
  var OPERATOR_AFTER_INC = "afterInc";
  var OPERATOR_CONTAINS = "contains";
  var OPERATOR_NOT_CONTAINS = "notContains";
  var OPERATOR_STARTS_WITH = "startsWith";
  var OPERATOR_ON = "on";
  var OPERATOR_NOT_ON = "notOn";
  var SORTING_DIRECTIONS = ["asc", "desc"];
  var sortArrows = { asc: "\u2191", desc: "\u2193" };
  var sortValues = { asc: "ascending", desc: "descending" };
  var sortLabels = {
    asc: (0, import_i18n24.__)("Sort ascending"),
    desc: (0, import_i18n24.__)("Sort descending")
  };
  var sortIcons = {
    asc: arrow_up_default,
    desc: arrow_down_default
  };
  var LAYOUT_TABLE = "table";
  var LAYOUT_GRID = "grid";
  var LAYOUT_LIST2 = "list";
  var LAYOUT_ACTIVITY = "activity";
  var LAYOUT_PICKER_GRID = "pickerGrid";
  var LAYOUT_PICKER_TABLE = "pickerTable";
  var LAYOUT_PICKER_ACTIVITY = "pickerActivity";

  // packages/dataviews/build-module/components/dataviews-context/index.mjs
  var DataViewsContext = (0, import_element57.createContext)({
    view: { type: LAYOUT_TABLE },
    onChangeView: () => {
    },
    fields: [],
    data: [],
    paginationInfo: {
      totalItems: 0,
      totalPages: 0
    },
    selection: [],
    onChangeSelection: () => {
    },
    setOpenedFilter: () => {
    },
    openedFilter: null,
    getItemId: (item) => item.id,
    isItemClickable: () => true,
    renderItemLink: void 0,
    containerWidth: 0,
    containerRef: (0, import_element57.createRef)(),
    resizeObserverRef: () => {
    },
    defaultLayouts: { list: {}, grid: {}, table: {} },
    filters: [],
    isShowingFilter: false,
    setIsShowingFilter: () => {
    },
    hasInitiallyLoaded: false,
    config: {
      perPageSizes: []
    },
    intersectionObserver: null
  });
  DataViewsContext.displayName = "DataViewsContext";
  var dataviews_context_default = DataViewsContext;

  // packages/dataviews/build-module/components/dataviews-layouts/index.mjs
  var import_i18n45 = __toESM(require_i18n(), 1);

  // packages/dataviews/build-module/components/dataviews-layouts/table/index.mjs
  var import_i18n32 = __toESM(require_i18n(), 1);
  var import_components25 = __toESM(require_components(), 1);
  var import_element66 = __toESM(require_element(), 1);
  var import_keycodes4 = __toESM(require_keycodes(), 1);

  // packages/dataviews/build-module/components/dataviews-selection-checkbox/index.mjs
  var import_components20 = __toESM(require_components(), 1);
  var import_i18n25 = __toESM(require_i18n(), 1);
  var import_jsx_runtime124 = __toESM(require_jsx_runtime(), 1);
  var SELECTION_CHECKBOX_CLASS = "dataviews-selection-checkbox";
  function DataViewsSelectionCheckbox({
    selection,
    onChangeSelection,
    item,
    getItemId: getItemId2,
    titleField,
    disabled: disabled2,
    ...extraProps
  }) {
    const id = getItemId2(item);
    const isInSelectionArray = selection.includes(id);
    const checked = !disabled2 && isInSelectionArray;
    const selectionLabel = titleField?.getValue?.({ item }) || (0, import_i18n25.__)("(no title)");
    return /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
      import_components20.CheckboxControl,
      {
        className: SELECTION_CHECKBOX_CLASS,
        "aria-label": selectionLabel,
        "aria-disabled": disabled2,
        checked,
        onChange: () => {
          if (disabled2) {
            return;
          }
          onChangeSelection(
            isInSelectionArray ? selection.filter((itemId) => id !== itemId) : [...selection, id]
          );
        },
        ...extraProps
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-item-actions/index.mjs
  var import_components21 = __toESM(require_components(), 1);
  var import_i18n26 = __toESM(require_i18n(), 1);
  var import_element58 = __toESM(require_element(), 1);
  var import_data35 = __toESM(require_data(), 1);
  var import_compose5 = __toESM(require_compose(), 1);

  // packages/dataviews/build-module/lock-unlock.mjs
  var import_private_apis5 = __toESM(require_private_apis(), 1);
  var { lock: lock4, unlock: unlock4 } = (0, import_private_apis5.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
    "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
    "@wordpress/dataviews"
  );

  // packages/dataviews/build-module/components/dataviews-item-actions/index.mjs
  var import_jsx_runtime125 = __toESM(require_jsx_runtime(), 1);
  var { Menu, kebabCase: kebabCase2 } = unlock4(import_components21.privateApis);
  function ButtonTrigger({
    action,
    onClick,
    items,
    variant
  }) {
    const label = typeof action.label === "string" ? action.label : action.label(items);
    return /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
      import_components21.Button,
      {
        disabled: !!action.disabled,
        accessibleWhenDisabled: true,
        size: "compact",
        variant,
        onClick,
        children: label
      }
    );
  }
  function MenuItemTrigger({
    action,
    onClick,
    items
  }) {
    const label = typeof action.label === "string" ? action.label : action.label(items);
    return /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(Menu.Item, { disabled: action.disabled, onClick, children: /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(Menu.ItemLabel, { children: label }) });
  }
  function ActionModal({
    action,
    items,
    closeModal
  }) {
    const label = typeof action.label === "string" ? action.label : action.label(items);
    const modalHeader = typeof action.modalHeader === "function" ? action.modalHeader(items) : action.modalHeader;
    return /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
      import_components21.Modal,
      {
        title: modalHeader || label,
        __experimentalHideHeader: !!action.hideModalHeader,
        onRequestClose: closeModal,
        focusOnMount: action.modalFocusOnMount ?? true,
        size: action.modalSize || "medium",
        overlayClassName: `dataviews-action-modal dataviews-action-modal__${kebabCase2(
          action.id
        )}`,
        children: /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(action.RenderModal, { items, closeModal })
      }
    );
  }
  function ActionsMenuGroup({
    actions,
    item,
    registry,
    setActiveModalAction
  }) {
    const { primaryActions, regularActions } = (0, import_element58.useMemo)(() => {
      return actions.reduce(
        (acc, action) => {
          (action.isPrimary ? acc.primaryActions : acc.regularActions).push(action);
          return acc;
        },
        {
          primaryActions: [],
          regularActions: []
        }
      );
    }, [actions]);
    const renderActionGroup = (actionList) => actionList.map((action) => /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
      MenuItemTrigger,
      {
        action,
        onClick: () => {
          if ("RenderModal" in action) {
            setActiveModalAction(action);
            return;
          }
          action.callback([item], { registry });
        },
        items: [item]
      },
      action.id
    ));
    return /* @__PURE__ */ (0, import_jsx_runtime125.jsxs)(Menu.Group, { children: [
      renderActionGroup(primaryActions),
      renderActionGroup(regularActions)
    ] });
  }
  function ItemActions({
    item,
    actions,
    isCompact
  }) {
    const registry = (0, import_data35.useRegistry)();
    const { primaryActions, eligibleActions } = (0, import_element58.useMemo)(() => {
      const _eligibleActions = actions.filter(
        (action) => !action.isEligible || action.isEligible(item)
      );
      const _primaryActions = _eligibleActions.filter(
        (action) => action.isPrimary
      );
      return {
        primaryActions: _primaryActions,
        eligibleActions: _eligibleActions
      };
    }, [actions, item]);
    const isMobileViewport = (0, import_compose5.useViewportMatch)("medium", "<");
    if (isCompact) {
      return /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
        CompactItemActions,
        {
          item,
          actions: eligibleActions,
          isSmall: true,
          registry
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime125.jsxs)(
      Stack,
      {
        direction: "row",
        justify: "flex-end",
        className: "dataviews-item-actions",
        style: {
          flexShrink: 0,
          width: "auto"
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
            PrimaryActions,
            {
              item,
              actions: primaryActions,
              registry
            }
          ),
          (primaryActions.length < eligibleActions.length || // Since we hide primary actions on mobile, we need to show the menu
          // there if there are any actions at all.
          isMobileViewport) && /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
            CompactItemActions,
            {
              item,
              actions: eligibleActions,
              registry
            }
          )
        ]
      }
    );
  }
  function CompactItemActions({
    item,
    actions,
    isSmall,
    registry
  }) {
    const [activeModalAction, setActiveModalAction] = (0, import_element58.useState)(
      null
    );
    return /* @__PURE__ */ (0, import_jsx_runtime125.jsxs)(import_jsx_runtime125.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime125.jsxs)(Menu, { placement: "bottom-end", children: [
        /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
          Menu.TriggerButton,
          {
            render: /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
              import_components21.Button,
              {
                size: isSmall ? "small" : "compact",
                icon: more_vertical_default,
                label: (0, import_i18n26.__)("Actions"),
                accessibleWhenDisabled: true,
                disabled: !actions.length,
                className: "dataviews-all-actions-button"
              }
            )
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(Menu.Popover, { children: /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
          ActionsMenuGroup,
          {
            actions,
            item,
            registry,
            setActiveModalAction
          }
        ) })
      ] }),
      !!activeModalAction && /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
        ActionModal,
        {
          action: activeModalAction,
          items: [item],
          closeModal: () => setActiveModalAction(null)
        }
      )
    ] });
  }
  function PrimaryActions({
    item,
    actions,
    registry,
    buttonVariant
  }) {
    const [activeModalAction, setActiveModalAction] = (0, import_element58.useState)(null);
    const isMobileViewport = (0, import_compose5.useViewportMatch)("medium", "<");
    if (isMobileViewport) {
      return null;
    }
    if (!Array.isArray(actions) || actions.length === 0) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime125.jsxs)(import_jsx_runtime125.Fragment, { children: [
      actions.map((action) => /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
        ButtonTrigger,
        {
          action,
          onClick: () => {
            if ("RenderModal" in action) {
              setActiveModalAction(action);
              return;
            }
            action.callback([item], { registry });
          },
          items: [item],
          variant: buttonVariant
        },
        action.id
      )),
      !!activeModalAction && /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
        ActionModal,
        {
          action: activeModalAction,
          items: [item],
          closeModal: () => setActiveModalAction(null)
        }
      )
    ] });
  }

  // packages/dataviews/build-module/components/dataviews-bulk-actions/index.mjs
  var import_components22 = __toESM(require_components(), 1);
  var import_i18n28 = __toESM(require_i18n(), 1);
  var import_element59 = __toESM(require_element(), 1);
  var import_data36 = __toESM(require_data(), 1);
  var import_compose6 = __toESM(require_compose(), 1);

  // packages/dataviews/build-module/utils/get-footer-message.mjs
  var import_i18n27 = __toESM(require_i18n(), 1);
  function getFooterMessage(selectionCount, itemsCount, totalItems, onlyTotalCount = false) {
    if (selectionCount > 0) {
      return (0, import_i18n27.sprintf)(
        /* translators: %d: number of items. */
        (0, import_i18n27._n)("%d Item selected", "%d Items selected", selectionCount),
        selectionCount
      );
    }
    if (onlyTotalCount || totalItems <= itemsCount) {
      return (0, import_i18n27.sprintf)(
        /* translators: %d: number of items. */
        (0, import_i18n27._n)("%d Item", "%d Items", totalItems),
        totalItems
      );
    }
    return (0, import_i18n27.sprintf)(
      /* translators: %1$d: number of items. %2$d: total number of items. */
      (0, import_i18n27._n)("%1$d of %2$d Item", "%1$d of %2$d Items", totalItems),
      itemsCount,
      totalItems
    );
  }

  // packages/dataviews/build-module/components/dataviews-bulk-actions/index.mjs
  var import_jsx_runtime126 = __toESM(require_jsx_runtime(), 1);
  function ActionWithModal({
    action,
    items,
    ActionTriggerComponent
  }) {
    const [isModalOpen, setIsModalOpen] = (0, import_element59.useState)(false);
    const actionTriggerProps = {
      action,
      onClick: () => {
        setIsModalOpen(true);
      },
      items
    };
    return /* @__PURE__ */ (0, import_jsx_runtime126.jsxs)(import_jsx_runtime126.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(ActionTriggerComponent, { ...actionTriggerProps }),
      isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
        ActionModal,
        {
          action,
          items,
          closeModal: () => setIsModalOpen(false)
        }
      )
    ] });
  }
  function hasAPossibleBulkAction(actions, item) {
    return actions.some(
      (action) => action.supportsBulk && (!action.isEligible || action.isEligible(item))
    );
  }
  function useHasAPossibleBulkAction(actions, item) {
    return (0, import_element59.useMemo)(
      () => hasAPossibleBulkAction(actions, item),
      [actions, item]
    );
  }
  function useSomeItemHasAPossibleBulkAction(actions, data) {
    return (0, import_element59.useMemo)(
      () => data.some((item) => hasAPossibleBulkAction(actions, item)),
      [actions, data]
    );
  }
  function BulkSelectionCheckbox({
    selection,
    onChangeSelection,
    data,
    actions,
    getItemId: getItemId2,
    disableSelectAll = false
  }) {
    const selectableItems = (0, import_element59.useMemo)(() => {
      return data.filter((item) => {
        return actions.some(
          (action) => action.supportsBulk && (!action.isEligible || action.isEligible(item))
        );
      });
    }, [data, actions]);
    const selectedItems = data.filter(
      (item) => selection.includes(getItemId2(item)) && selectableItems.includes(item)
    );
    const hasSelection = selection.length > 0;
    const areAllSelected = selectedItems.length === selectableItems.length;
    if (disableSelectAll) {
      return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
        import_components22.CheckboxControl,
        {
          className: "dataviews-view-table-selection-checkbox",
          checked: hasSelection,
          disabled: !hasSelection,
          onChange: () => {
            onChangeSelection([]);
          },
          "aria-label": (0, import_i18n28.__)("Deselect all")
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
      import_components22.CheckboxControl,
      {
        className: "dataviews-view-table-selection-checkbox",
        checked: areAllSelected,
        indeterminate: !areAllSelected && !!selectedItems.length,
        onChange: () => {
          if (areAllSelected) {
            onChangeSelection([]);
          } else {
            onChangeSelection(
              selectableItems.map((item) => getItemId2(item))
            );
          }
        },
        "aria-label": areAllSelected ? (0, import_i18n28.__)("Deselect all") : (0, import_i18n28.__)("Select all")
      }
    );
  }
  function ActionTrigger({
    action,
    onClick,
    isBusy,
    items
  }) {
    const label = typeof action.label === "string" ? action.label : action.label(items);
    const isMobile = (0, import_compose6.useViewportMatch)("medium", "<");
    if (isMobile) {
      return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
        import_components22.Button,
        {
          disabled: isBusy,
          accessibleWhenDisabled: true,
          label,
          icon: action.icon,
          size: "compact",
          onClick,
          isBusy
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
      import_components22.Button,
      {
        disabled: isBusy,
        accessibleWhenDisabled: true,
        size: "compact",
        onClick,
        isBusy,
        children: label
      }
    );
  }
  var EMPTY_ARRAY3 = [];
  function ActionButton({
    action,
    selectedItems,
    actionInProgress,
    setActionInProgress
  }) {
    const registry = (0, import_data36.useRegistry)();
    const selectedEligibleItems = (0, import_element59.useMemo)(() => {
      return selectedItems.filter((item) => {
        return !action.isEligible || action.isEligible(item);
      });
    }, [action, selectedItems]);
    if ("RenderModal" in action) {
      return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
        ActionWithModal,
        {
          action,
          items: selectedEligibleItems,
          ActionTriggerComponent: ActionTrigger
        },
        action.id
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
      ActionTrigger,
      {
        action,
        onClick: async () => {
          setActionInProgress(action.id);
          await action.callback(selectedItems, {
            registry
          });
          setActionInProgress(null);
        },
        items: selectedEligibleItems,
        isBusy: actionInProgress === action.id
      },
      action.id
    );
  }
  function renderFooterContent(data, actions, getItemId2, isInfiniteScroll, selection, actionsToShow, selectedItems, actionInProgress, setActionInProgress, onChangeSelection, paginationInfo) {
    const message2 = getFooterMessage(
      selection.length,
      data.length,
      paginationInfo.totalItems,
      isInfiniteScroll
    );
    return /* @__PURE__ */ (0, import_jsx_runtime126.jsxs)(
      Stack,
      {
        direction: "row",
        className: "dataviews-bulk-actions-footer__container",
        gap: "md",
        align: "center",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
            BulkSelectionCheckbox,
            {
              selection,
              onChangeSelection,
              data,
              actions,
              getItemId: getItemId2,
              disableSelectAll: isInfiniteScroll
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime126.jsx)("span", { className: "dataviews-bulk-actions-footer__item-count", children: message2 }),
          /* @__PURE__ */ (0, import_jsx_runtime126.jsxs)(
            Stack,
            {
              direction: "row",
              className: "dataviews-bulk-actions-footer__action-buttons",
              gap: "xs",
              children: [
                actionsToShow.map((action) => {
                  return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
                    ActionButton,
                    {
                      action,
                      selectedItems,
                      actionInProgress,
                      setActionInProgress
                    },
                    action.id
                  );
                }),
                selectedItems.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
                  import_components22.Button,
                  {
                    icon: close_small_default,
                    showTooltip: true,
                    tooltipPosition: "top",
                    size: "compact",
                    label: (0, import_i18n28.__)("Cancel"),
                    disabled: !!actionInProgress,
                    accessibleWhenDisabled: false,
                    onClick: () => {
                      onChangeSelection(EMPTY_ARRAY3);
                    }
                  }
                )
              ]
            }
          )
        ]
      }
    );
  }
  function FooterContent({
    selection,
    actions,
    onChangeSelection,
    data,
    getItemId: getItemId2,
    isInfiniteScroll,
    paginationInfo
  }) {
    const [actionInProgress, setActionInProgress] = (0, import_element59.useState)(
      null
    );
    const footerContentRef = (0, import_element59.useRef)(void 0);
    const isMobile = (0, import_compose6.useViewportMatch)("medium", "<");
    const bulkActions = (0, import_element59.useMemo)(
      () => actions.filter((action) => action.supportsBulk),
      [actions]
    );
    const selectableItems = (0, import_element59.useMemo)(() => {
      return data.filter((item) => {
        return bulkActions.some(
          (action) => !action.isEligible || action.isEligible(item)
        );
      });
    }, [data, bulkActions]);
    const selectedItems = (0, import_element59.useMemo)(() => {
      return data.filter(
        (item) => selection.includes(getItemId2(item)) && selectableItems.includes(item)
      );
    }, [selection, data, getItemId2, selectableItems]);
    const actionsToShow = (0, import_element59.useMemo)(
      () => actions.filter((action) => {
        return action.supportsBulk && (!isMobile || action.icon) && selectedItems.some(
          (item) => !action.isEligible || action.isEligible(item)
        );
      }),
      [actions, selectedItems, isMobile]
    );
    if (!actionInProgress) {
      if (footerContentRef.current) {
        footerContentRef.current = void 0;
      }
      return renderFooterContent(
        data,
        actions,
        getItemId2,
        isInfiniteScroll,
        selection,
        actionsToShow,
        selectedItems,
        actionInProgress,
        setActionInProgress,
        onChangeSelection,
        paginationInfo
      );
    } else if (!footerContentRef.current) {
      footerContentRef.current = renderFooterContent(
        data,
        actions,
        getItemId2,
        isInfiniteScroll,
        selection,
        actionsToShow,
        selectedItems,
        actionInProgress,
        setActionInProgress,
        onChangeSelection,
        paginationInfo
      );
    }
    return footerContentRef.current;
  }
  function BulkActionsFooter() {
    const {
      data,
      selection,
      actions = EMPTY_ARRAY3,
      onChangeSelection,
      getItemId: getItemId2,
      paginationInfo,
      view
    } = (0, import_element59.useContext)(dataviews_context_default);
    return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
      FooterContent,
      {
        selection,
        onChangeSelection,
        data,
        actions,
        getItemId: getItemId2,
        isInfiniteScroll: !!view.infiniteScrollEnabled,
        paginationInfo
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-layouts/table/column-header-menu.mjs
  var import_i18n29 = __toESM(require_i18n(), 1);
  var import_components23 = __toESM(require_components(), 1);
  var import_element60 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/utils/get-hideable-fields.mjs
  function getHideableFields(view, fields2) {
    const togglableFields = [
      view?.titleField,
      view?.mediaField,
      view?.descriptionField
    ].filter(Boolean);
    return fields2.filter(
      (f2) => !togglableFields.includes(f2.id) && f2.type !== "media" && f2.enableHiding !== false
    );
  }

  // packages/dataviews/build-module/components/dataviews-layouts/table/column-header-menu.mjs
  var import_jsx_runtime127 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu2 } = unlock4(import_components23.privateApis);
  function WithMenuSeparators({ children }) {
    return import_element60.Children.toArray(children).filter(Boolean).map((child, i2) => /* @__PURE__ */ (0, import_jsx_runtime127.jsxs)(import_element60.Fragment, { children: [
      i2 > 0 && /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.Separator, {}),
      child
    ] }, i2));
  }
  var _HeaderMenu = (0, import_element60.forwardRef)(function HeaderMenu({
    fieldId,
    view,
    fields: fields2,
    onChangeView,
    onHide,
    setOpenedFilter,
    canMove = true,
    canInsertLeft = true,
    canInsertRight = true
  }, ref) {
    const visibleFieldIds = view.fields ?? [];
    const index2 = visibleFieldIds?.indexOf(fieldId);
    const isSorted = view.sort?.field === fieldId;
    let isHidable = false;
    let isSortable = false;
    let canAddFilter = false;
    let operators = [];
    const field = fields2.find((f2) => f2.id === fieldId);
    const { setIsShowingFilter } = (0, import_element60.useContext)(dataviews_context_default);
    if (!field) {
      return null;
    }
    isHidable = field.enableHiding !== false;
    isSortable = field.enableSorting !== false;
    const header = field.header;
    operators = !!field.filterBy && field.filterBy?.operators || [];
    canAddFilter = !view.filters?.some((_filter) => fieldId === _filter.field) && !!(field.hasElements || field.Edit) && field.filterBy !== false && !field.filterBy?.isPrimary;
    if (!isSortable && !canMove && !isHidable && !canAddFilter) {
      return header;
    }
    const hiddenFields = getHideableFields(view, fields2).filter(
      (f2) => !visibleFieldIds.includes(f2.id)
    );
    const canInsert = (canInsertLeft || canInsertRight) && !!hiddenFields.length;
    const isRtl = (0, import_i18n29.isRTL)();
    return /* @__PURE__ */ (0, import_jsx_runtime127.jsxs)(Menu2, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime127.jsxs)(
        Menu2.TriggerButton,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
            import_components23.Button,
            {
              size: "compact",
              className: "dataviews-view-table-header-button",
              ref,
              variant: "tertiary"
            }
          ),
          children: [
            header,
            view.sort && isSorted && /* @__PURE__ */ (0, import_jsx_runtime127.jsx)("span", { "aria-hidden": "true", children: sortArrows[view.sort.direction] })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.Popover, { style: { minWidth: "240px" }, children: /* @__PURE__ */ (0, import_jsx_runtime127.jsxs)(WithMenuSeparators, { children: [
        isSortable && /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.Group, { children: SORTING_DIRECTIONS.map(
          (direction) => {
            const isChecked = view.sort && isSorted && view.sort.direction === direction;
            const value = `${fieldId}-${direction}`;
            return /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
              Menu2.RadioItem,
              {
                name: "view-table-sorting",
                value,
                checked: isChecked,
                onChange: () => {
                  onChangeView({
                    ...view,
                    sort: {
                      field: fieldId,
                      direction
                    },
                    showLevels: false
                  });
                },
                children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.ItemLabel, { children: sortLabels[direction] })
              },
              value
            );
          }
        ) }),
        canAddFilter && /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.Group, { children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
          Menu2.Item,
          {
            prefix: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(import_components23.Icon, { icon: funnel_default }),
            onClick: () => {
              setOpenedFilter(fieldId);
              setIsShowingFilter(true);
              onChangeView({
                ...view,
                page: 1,
                filters: [
                  ...view.filters || [],
                  {
                    field: fieldId,
                    value: void 0,
                    operator: operators[0]
                  }
                ]
              });
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.ItemLabel, { children: (0, import_i18n29.__)("Add filter") })
          }
        ) }),
        (canMove || isHidable || canInsert) && field && /* @__PURE__ */ (0, import_jsx_runtime127.jsxs)(Menu2.Group, { children: [
          canMove && /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
            Menu2.Item,
            {
              prefix: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(import_components23.Icon, { icon: arrow_left_default }),
              disabled: isRtl ? index2 >= visibleFieldIds.length - 1 : index2 < 1,
              onClick: () => {
                const targetIndex = isRtl ? index2 + 1 : index2 - 1;
                const newFields = [
                  ...visibleFieldIds
                ];
                newFields.splice(index2, 1);
                newFields.splice(
                  targetIndex,
                  0,
                  fieldId
                );
                onChangeView({
                  ...view,
                  fields: newFields
                });
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.ItemLabel, { children: (0, import_i18n29.__)("Move left") })
            }
          ),
          canMove && /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
            Menu2.Item,
            {
              prefix: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(import_components23.Icon, { icon: arrow_right_default }),
              disabled: isRtl ? index2 < 1 : index2 >= visibleFieldIds.length - 1,
              onClick: () => {
                const targetIndex = isRtl ? index2 - 1 : index2 + 1;
                const newFields = [
                  ...visibleFieldIds
                ];
                newFields.splice(index2, 1);
                newFields.splice(
                  targetIndex,
                  0,
                  fieldId
                );
                onChangeView({
                  ...view,
                  fields: newFields
                });
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.ItemLabel, { children: (0, import_i18n29.__)("Move right") })
            }
          ),
          canInsertLeft && !!hiddenFields.length && /* @__PURE__ */ (0, import_jsx_runtime127.jsxs)(Menu2, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.SubmenuTriggerItem, { children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.ItemLabel, { children: (0, import_i18n29.__)("Insert left") }) }),
            /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.Popover, { children: hiddenFields.map((hiddenField) => {
              const insertIndex = isRtl ? index2 + 1 : index2;
              return /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
                Menu2.Item,
                {
                  onClick: () => {
                    onChangeView({
                      ...view,
                      fields: [
                        ...visibleFieldIds.slice(
                          0,
                          insertIndex
                        ),
                        hiddenField.id,
                        ...visibleFieldIds.slice(
                          insertIndex
                        )
                      ]
                    });
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.ItemLabel, { children: hiddenField.label })
                },
                hiddenField.id
              );
            }) })
          ] }),
          canInsertRight && !!hiddenFields.length && /* @__PURE__ */ (0, import_jsx_runtime127.jsxs)(Menu2, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.SubmenuTriggerItem, { children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.ItemLabel, { children: (0, import_i18n29.__)("Insert right") }) }),
            /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.Popover, { children: hiddenFields.map((hiddenField) => {
              const insertIndex = isRtl ? index2 : index2 + 1;
              return /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
                Menu2.Item,
                {
                  onClick: () => {
                    onChangeView({
                      ...view,
                      fields: [
                        ...visibleFieldIds.slice(
                          0,
                          insertIndex
                        ),
                        hiddenField.id,
                        ...visibleFieldIds.slice(
                          insertIndex
                        )
                      ]
                    });
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.ItemLabel, { children: hiddenField.label })
                },
                hiddenField.id
              );
            }) })
          ] }),
          isHidable && field && /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
            Menu2.Item,
            {
              prefix: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(import_components23.Icon, { icon: unseen_default }),
              onClick: () => {
                onHide(field);
                onChangeView({
                  ...view,
                  fields: visibleFieldIds.filter(
                    (id) => id !== fieldId
                  )
                });
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Menu2.ItemLabel, { children: (0, import_i18n29.__)("Hide column") })
            }
          )
        ] })
      ] }) })
    ] });
  });
  var ColumnHeaderMenu = _HeaderMenu;
  var column_header_menu_default = ColumnHeaderMenu;

  // packages/dataviews/build-module/components/dataviews-layouts/utils/item-click-wrapper.mjs
  var import_element61 = __toESM(require_element(), 1);
  var import_jsx_runtime128 = __toESM(require_jsx_runtime(), 1);
  function getClickableItemProps({
    item,
    isItemClickable,
    onClickItem,
    className
  }) {
    if (!isItemClickable(item) || !onClickItem) {
      return { className };
    }
    return {
      className: className ? `${className} ${className}--clickable` : void 0,
      role: "button",
      tabIndex: 0,
      onClick: (event) => {
        event.stopPropagation();
        onClickItem(item);
      },
      onKeyDown: (event) => {
        if (event.key === "Enter" || event.key === "" || event.key === " ") {
          event.stopPropagation();
          onClickItem(item);
        }
      }
    };
  }
  function ItemClickWrapper({
    item,
    isItemClickable,
    onClickItem,
    renderItemLink,
    className,
    children,
    ...extraProps
  }) {
    if (!isItemClickable(item)) {
      return /* @__PURE__ */ (0, import_jsx_runtime128.jsx)("div", { className, ...extraProps, children });
    }
    if (renderItemLink) {
      const renderedElement = renderItemLink({
        item,
        className: `${className} ${className}--clickable`,
        ...extraProps,
        children
      });
      return (0, import_element61.cloneElement)(renderedElement, {
        onClick: (event) => {
          event.stopPropagation();
          if (renderedElement.props.onClick) {
            renderedElement.props.onClick(event);
          }
        },
        onKeyDown: (event) => {
          if (event.key === "Enter" || event.key === "" || event.key === " ") {
            event.stopPropagation();
            if (renderedElement.props.onKeyDown) {
              renderedElement.props.onKeyDown(event);
            }
          }
        }
      });
    }
    const clickProps = getClickableItemProps({
      item,
      isItemClickable,
      onClickItem,
      className
    });
    return /* @__PURE__ */ (0, import_jsx_runtime128.jsx)("div", { ...clickProps, ...extraProps, children });
  }

  // packages/dataviews/build-module/components/dataviews-layouts/table/column-primary.mjs
  var import_jsx_runtime129 = __toESM(require_jsx_runtime(), 1);
  function ColumnPrimary({
    item,
    level,
    titleField,
    mediaField,
    descriptionField: descriptionField2,
    onClickItem,
    renderItemLink,
    isItemClickable
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime129.jsxs)(Stack, { direction: "row", gap: "md", align: "flex-start", justify: "flex-start", children: [
      mediaField && /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(
        ItemClickWrapper,
        {
          item,
          isItemClickable,
          onClickItem,
          renderItemLink,
          className: "dataviews-view-table__cell-content-wrapper dataviews-column-primary__media",
          "aria-label": isItemClickable(item) && (!!onClickItem || !!renderItemLink) && !!titleField ? titleField.getValue?.({ item }) : void 0,
          children: /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(
            mediaField.render,
            {
              item,
              field: mediaField,
              config: { sizes: "32px" }
            }
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime129.jsxs)(
        Stack,
        {
          direction: "column",
          align: "flex-start",
          className: "dataviews-view-table__primary-column-content",
          children: [
            titleField && /* @__PURE__ */ (0, import_jsx_runtime129.jsxs)(
              ItemClickWrapper,
              {
                item,
                isItemClickable,
                onClickItem,
                renderItemLink,
                className: "dataviews-view-table__cell-content-wrapper dataviews-title-field",
                children: [
                  level !== void 0 && level > 0 && /* @__PURE__ */ (0, import_jsx_runtime129.jsxs)("span", { className: "dataviews-view-table__level", children: [
                    Array(level).fill("\u2014").join(" "),
                    "\xA0"
                  ] }),
                  /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(titleField.render, { item, field: titleField })
                ]
              }
            ),
            descriptionField2 && /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(
              descriptionField2.render,
              {
                item,
                field: descriptionField2
              }
            )
          ]
        }
      )
    ] });
  }
  var column_primary_default = ColumnPrimary;

  // packages/dataviews/build-module/components/dataviews-layouts/table/use-scroll-state.mjs
  var import_element62 = __toESM(require_element(), 1);
  var import_i18n30 = __toESM(require_i18n(), 1);
  var isScrolledToEnd = (element) => {
    if ((0, import_i18n30.isRTL)()) {
      const scrollLeft = Math.abs(element.scrollLeft);
      return scrollLeft <= 1;
    }
    return element.scrollLeft + element.clientWidth >= element.scrollWidth - 1;
  };
  function useScrollState({
    scrollContainerRef,
    enabledHorizontal = false
  }) {
    const [isHorizontalScrollEnd, setIsHorizontalScrollEnd] = (0, import_element62.useState)(false);
    const [isVerticallyScrolled, setIsVerticallyScrolled] = (0, import_element62.useState)(false);
    const handleScroll = (0, import_element62.useCallback)(() => {
      const scrollContainer = scrollContainerRef.current;
      if (!scrollContainer) {
        return;
      }
      if (enabledHorizontal) {
        setIsHorizontalScrollEnd(isScrolledToEnd(scrollContainer));
      }
      setIsVerticallyScrolled(scrollContainer.scrollTop > 0);
    }, [scrollContainerRef, enabledHorizontal]);
    (0, import_element62.useEffect)(() => {
      if (typeof window === "undefined" || !scrollContainerRef.current) {
        return () => {
        };
      }
      const scrollContainer = scrollContainerRef.current;
      handleScroll();
      scrollContainer.addEventListener("scroll", handleScroll);
      window.addEventListener("resize", handleScroll);
      return () => {
        scrollContainer.removeEventListener("scroll", handleScroll);
        window.removeEventListener("resize", handleScroll);
      };
    }, [scrollContainerRef, enabledHorizontal, handleScroll]);
    return { isHorizontalScrollEnd, isVerticallyScrolled };
  }

  // packages/dataviews/build-module/components/dataviews-layouts/utils/get-data-by-group.mjs
  function getDataByGroup(data, groupByField) {
    return data.reduce((groups, item) => {
      const groupName = groupByField.getValue({ item });
      if (!groups.has(groupName)) {
        groups.set(groupName, []);
      }
      groups.get(groupName)?.push(item);
      return groups;
    }, /* @__PURE__ */ new Map());
  }

  // packages/dataviews/build-module/components/dataviews-layouts/utils/use-selection-props.mjs
  var import_element63 = __toESM(require_element(), 1);
  var import_keycodes3 = __toESM(require_keycodes(), 1);
  function getRange(orderedIds, fromIndex, toIndex) {
    return orderedIds.slice(
      Math.min(fromIndex, toIndex),
      Math.max(fromIndex, toIndex) + 1
    );
  }
  function getRangeSelection({
    anchorId,
    targetId,
    lastTargetId,
    orderedIds,
    selection
  }) {
    const targetIndex = orderedIds.indexOf(targetId);
    if (targetIndex === -1) {
      return selection;
    }
    const anchorIndex = anchorId === null ? -1 : orderedIds.indexOf(anchorId);
    const hasAnchor = anchorIndex !== -1;
    const rangeStart = hasAnchor ? anchorIndex : targetIndex;
    const lastTargetIndex = hasAnchor && lastTargetId !== null ? orderedIds.indexOf(lastTargetId) : -1;
    const lastRange = lastTargetIndex === -1 ? [] : getRange(orderedIds, rangeStart, lastTargetIndex);
    const base = selection.filter((id) => !lastRange.includes(id));
    return [
      .../* @__PURE__ */ new Set([
        ...base,
        ...getRange(orderedIds, rangeStart, targetIndex)
      ])
    ];
  }
  function getClosestSelectedId({
    targetId,
    orderedIds,
    selection
  }) {
    const targetIndex = orderedIds.indexOf(targetId);
    if (targetIndex === -1) {
      return null;
    }
    const selectedIds = new Set(selection);
    let closestId = null;
    let closestDistance = Infinity;
    orderedIds.forEach((id, index2) => {
      if (!selectedIds.has(id)) {
        return;
      }
      const distance = Math.abs(index2 - targetIndex);
      if (distance < closestDistance) {
        closestDistance = distance;
        closestId = id;
      }
    });
    return closestId;
  }
  function useSelectionProps({
    data,
    actions,
    getItemId: getItemId2,
    selection,
    onChangeSelection
  }) {
    const gestureRef = (0, import_element63.useRef)(null);
    const isTouchDeviceRef = (0, import_element63.useRef)(false);
    (0, import_element63.useEffect)(() => {
      const markTouchDevice = () => {
        isTouchDeviceRef.current = true;
      };
      document.addEventListener("touchstart", markTouchDevice, {
        once: true
      });
      return () => document.removeEventListener("touchstart", markTouchDevice);
    }, []);
    const selectableIds = data.filter((item) => hasAPossibleBulkAction(actions, item)).map(getItemId2);
    const selectableIdSet = new Set(selectableIds);
    const hasSelectableItems = selectableIds.length > 0;
    const getSelectionProps = (id) => {
      const isSelectable = selectableIdSet.has(id);
      return {
        onMouseDown: (event) => {
          if (event.button === 0 && event.shiftKey && hasSelectableItems) {
            event.preventDefault();
          }
        },
        onClickCapture: (event) => {
          if (!hasSelectableItems) {
            return;
          }
          const isModifierKeyPressed = (0, import_keycodes3.isAppleOS)() ? event.metaKey : event.ctrlKey;
          const isSelectionCheckboxClick = event.target instanceof Element && !!event.target.closest(`.${SELECTION_CHECKBOX_CLASS}`);
          if (!isModifierKeyPressed && !event.shiftKey) {
            if (isSelectable && isSelectionCheckboxClick) {
              gestureRef.current = {
                anchorId: id,
                lastTargetId: null
              };
            }
            return;
          }
          if (isTouchDeviceRef.current || document.getSelection()?.type === "Range") {
            return;
          }
          event.stopPropagation();
          if (!isSelectionCheckboxClick) {
            event.preventDefault();
          }
          if (!isSelectable) {
            return;
          }
          if (event.shiftKey) {
            let gesture = gestureRef.current;
            if (!gesture || !selectableIdSet.has(gesture.anchorId)) {
              gesture = {
                anchorId: getClosestSelectedId({
                  targetId: id,
                  orderedIds: selectableIds,
                  selection
                }) ?? id,
                lastTargetId: null
              };
            }
            onChangeSelection(
              getRangeSelection({
                anchorId: gesture.anchorId,
                targetId: id,
                lastTargetId: gesture.lastTargetId,
                orderedIds: selectableIds,
                selection
              })
            );
            gestureRef.current = {
              anchorId: gesture.anchorId,
              lastTargetId: id
            };
          } else {
            onChangeSelection(
              selection.includes(id) ? selection.filter((itemId) => id !== itemId) : [...selection, id]
            );
            gestureRef.current = { anchorId: id, lastTargetId: null };
          }
        }
      };
    };
    return { getSelectionProps };
  }

  // packages/dataviews/build-module/components/dataviews-view-config/properties-section.mjs
  var import_components24 = __toESM(require_components(), 1);
  var import_i18n31 = __toESM(require_i18n(), 1);
  var import_element64 = __toESM(require_element(), 1);
  var import_jsx_runtime130 = __toESM(require_jsx_runtime(), 1);
  function FieldItem({
    field,
    isVisible: isVisible2,
    onToggleVisibility
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(import_components24.__experimentalItem, { onClick: field.enableHiding ? onToggleVisibility : void 0, children: /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(Stack, { direction: "row", gap: "sm", justify: "flex-start", align: "center", children: [
      /* @__PURE__ */ (0, import_jsx_runtime130.jsx)("div", { style: { height: 24, width: 24 }, children: isVisible2 && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(import_components24.Icon, { icon: check_default }) }),
      /* @__PURE__ */ (0, import_jsx_runtime130.jsx)("span", { className: "dataviews-view-config__label", children: field.label })
    ] }) });
  }
  function isDefined(item) {
    return !!item;
  }
  function PropertiesSection({
    showLabel = true
  }) {
    const { view, fields: fields2, onChangeView } = (0, import_element64.useContext)(dataviews_context_default);
    const regularFields = getHideableFields(view, fields2);
    if (!regularFields?.length) {
      return null;
    }
    const titleField = fields2.find((f2) => f2.id === view.titleField);
    const previewField3 = fields2.find((f2) => f2.id === view.mediaField);
    const descriptionField2 = fields2.find(
      (f2) => f2.id === view.descriptionField
    );
    const lockedFields = [
      {
        field: titleField,
        isVisibleFlag: "showTitle"
      },
      {
        field: previewField3,
        isVisibleFlag: "showMedia"
      },
      {
        field: descriptionField2,
        isVisibleFlag: "showDescription"
      }
    ].filter(({ field }) => isDefined(field));
    const visibleFieldIds = view.fields ?? [];
    const visibleRegularFieldsCount = regularFields.filter(
      (f2) => visibleFieldIds.includes(f2.id)
    ).length;
    const visibleLockedFields = lockedFields.filter(
      ({ isVisibleFlag }) => (
        // @ts-expect-error
        view[isVisibleFlag] ?? true
      )
    );
    const totalVisibleFields = visibleLockedFields.length + visibleRegularFieldsCount;
    const isSingleVisibleLockedField = totalVisibleFields === 1 && visibleLockedFields.length === 1;
    return /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(Stack, { direction: "column", className: "dataviews-field-control", children: [
      showLabel && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(import_components24.BaseControl.VisualLabel, { children: (0, import_i18n31.__)("Properties") }),
      /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
        Stack,
        {
          direction: "column",
          className: "dataviews-view-config__properties",
          children: /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(import_components24.__experimentalItemGroup, { isBordered: true, isSeparated: true, size: "medium", children: [
            lockedFields.map(({ field, isVisibleFlag }) => {
              const isVisible2 = view[isVisibleFlag] ?? true;
              const fieldToRender = isSingleVisibleLockedField && isVisible2 ? { ...field, enableHiding: false } : field;
              return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
                FieldItem,
                {
                  field: fieldToRender,
                  isVisible: isVisible2,
                  onToggleVisibility: () => {
                    onChangeView({
                      ...view,
                      [isVisibleFlag]: !isVisible2
                    });
                  }
                },
                field.id
              );
            }),
            regularFields.map((field) => {
              const isVisible2 = visibleFieldIds.includes(field.id);
              const fieldToRender = totalVisibleFields === 1 && isVisible2 ? { ...field, enableHiding: false } : field;
              return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
                FieldItem,
                {
                  field: fieldToRender,
                  isVisible: isVisible2,
                  onToggleVisibility: () => {
                    onChangeView({
                      ...view,
                      fields: isVisible2 ? visibleFieldIds.filter(
                        (fieldId) => fieldId !== field.id
                      ) : [...visibleFieldIds, field.id]
                    });
                  }
                },
                field.id
              );
            })
          ] })
        }
      )
    ] });
  }

  // packages/dataviews/build-module/hooks/use-delayed-loading.mjs
  var import_element65 = __toESM(require_element(), 1);
  function useDelayedLoading(isLoading, options = { delay: 400 }) {
    const [showLoader, setShowLoader] = (0, import_element65.useState)(false);
    (0, import_element65.useEffect)(() => {
      if (!isLoading) {
        return;
      }
      const timeout = setTimeout(() => {
        setShowLoader(true);
      }, options.delay);
      return () => {
        clearTimeout(timeout);
        setShowLoader(false);
      };
    }, [isLoading, options.delay]);
    return showLoader;
  }

  // packages/dataviews/build-module/components/dataviews-layouts/table/index.mjs
  var import_jsx_runtime131 = __toESM(require_jsx_runtime(), 1);
  function getEffectiveAlign(explicitAlign, fieldType) {
    if (explicitAlign) {
      return explicitAlign;
    }
    if (fieldType === "integer" || fieldType === "number") {
      return "end";
    }
    return void 0;
  }
  function TableColumnField({
    item,
    fields: fields2,
    column,
    align
  }) {
    const field = fields2.find((f2) => f2.id === column);
    if (!field) {
      return null;
    }
    const className = clsx_default("dataviews-view-table__cell-content-wrapper", {
      "dataviews-view-table__cell-align-end": align === "end",
      "dataviews-view-table__cell-align-center": align === "center"
    });
    return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(field.render, { item, field }) });
  }
  function TableRow({
    hasBulkActions,
    item,
    level,
    actions,
    fields: fields2,
    id,
    view,
    titleField,
    mediaField,
    descriptionField: descriptionField2,
    selection,
    getItemId: getItemId2,
    isItemClickable,
    onClickItem,
    renderItemLink,
    onChangeSelection,
    onMouseDown,
    onClickCapture,
    isActionsColumnSticky,
    posinset
  }) {
    const { paginationInfo } = (0, import_element66.useContext)(dataviews_context_default);
    const hasPossibleBulkAction = useHasAPossibleBulkAction(actions, item);
    const isSelected2 = hasPossibleBulkAction && selection.includes(id);
    const {
      showTitle = true,
      showMedia = true,
      showDescription = true,
      infiniteScrollEnabled
    } = view;
    const columns = view.fields ?? [];
    const hasPrimaryColumn = titleField && showTitle || mediaField && showMedia || descriptionField2 && showDescription;
    return /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(
      "tr",
      {
        className: clsx_default("dataviews-view-table__row", {
          "is-selected": hasPossibleBulkAction && isSelected2,
          "has-bulk-actions": hasPossibleBulkAction
        }),
        "aria-setsize": infiniteScrollEnabled ? paginationInfo.totalItems : void 0,
        "aria-posinset": posinset,
        role: infiniteScrollEnabled ? "article" : void 0,
        onClickCapture,
        onMouseDown: (event) => {
          const isMetaClick = (0, import_keycodes4.isAppleOS)() ? event.metaKey : event.ctrlKey;
          if (event.button === 0 && isMetaClick && window.navigator.userAgent.toLowerCase().includes("firefox")) {
            event.preventDefault();
          }
          onMouseDown(event);
        },
        children: [
          hasBulkActions && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("td", { className: "dataviews-view-table__checkbox-column", children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("div", { className: "dataviews-view-table__cell-content-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
            DataViewsSelectionCheckbox,
            {
              item,
              selection,
              onChangeSelection,
              getItemId: getItemId2,
              titleField,
              disabled: !hasPossibleBulkAction
            }
          ) }) }),
          hasPrimaryColumn && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("td", { children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
            column_primary_default,
            {
              item,
              level,
              titleField: showTitle ? titleField : void 0,
              mediaField: showMedia ? mediaField : void 0,
              descriptionField: showDescription ? descriptionField2 : void 0,
              isItemClickable,
              onClickItem,
              renderItemLink
            }
          ) }),
          columns.map((column) => {
            const { width, maxWidth, minWidth, align } = view.layout?.styles?.[column] ?? {};
            const field = fields2.find((f2) => f2.id === column);
            const effectiveAlign = getEffectiveAlign(align, field?.type);
            return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
              "td",
              {
                style: {
                  width,
                  maxWidth,
                  minWidth
                },
                children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                  TableColumnField,
                  {
                    fields: fields2,
                    item,
                    column,
                    align: effectiveAlign
                  }
                )
              },
              column
            );
          }),
          !!actions?.length && // Disable reason: we are not making the element interactive,
          // but preventing any click events from bubbling up to the
          // table row. This allows us to add a click handler to the row
          // itself (to toggle row selection) without erroneously
          // intercepting click events from ItemActions.
          /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
            "td",
            {
              className: clsx_default("dataviews-view-table__actions-column", {
                "dataviews-view-table__actions-column--sticky": true,
                "dataviews-view-table__actions-column--stuck": isActionsColumnSticky
              }),
              onClick: (e2) => e2.stopPropagation(),
              children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(ItemActions, { item, actions })
            }
          )
        ]
      }
    );
  }
  function ViewTable({
    actions,
    data,
    fields: fields2,
    getItemId: getItemId2,
    getItemLevel: getItemLevel2,
    isLoading = false,
    onChangeView,
    onChangeSelection,
    selection,
    setOpenedFilter,
    onClickItem,
    isItemClickable,
    renderItemLink,
    view,
    className,
    empty
  }) {
    const { containerRef } = (0, import_element66.useContext)(dataviews_context_default);
    const isDelayedLoading = useDelayedLoading(isLoading);
    const groupField = view.groupBy?.field ? fields2.find((f2) => f2.id === view.groupBy?.field) : null;
    const dataByGroup = groupField ? getDataByGroup(data, groupField) : null;
    const orderedData = dataByGroup ? Array.from(dataByGroup.values()).flat() : data;
    const { getSelectionProps } = useSelectionProps({
      data: orderedData,
      actions,
      getItemId: getItemId2,
      selection,
      onChangeSelection
    });
    const headerMenuRefs = (0, import_element66.useRef)(/* @__PURE__ */ new Map());
    const headerMenuToFocusRef = (0, import_element66.useRef)(void 0);
    const [nextHeaderMenuToFocus, setNextHeaderMenuToFocus] = (0, import_element66.useState)();
    const [contextMenuAnchor, setContextMenuAnchor] = (0, import_element66.useState)(null);
    (0, import_element66.useEffect)(() => {
      if (headerMenuToFocusRef.current) {
        headerMenuToFocusRef.current.focus();
        headerMenuToFocusRef.current = void 0;
      }
    });
    const tableNoticeId = (0, import_element66.useId)();
    const { isHorizontalScrollEnd, isVerticallyScrolled } = useScrollState({
      scrollContainerRef: containerRef,
      enabledHorizontal: !!actions?.length
    });
    const hasBulkActions = useSomeItemHasAPossibleBulkAction(actions, data);
    if (nextHeaderMenuToFocus) {
      headerMenuToFocusRef.current = nextHeaderMenuToFocus;
      setNextHeaderMenuToFocus(void 0);
      return;
    }
    const onHide = (field) => {
      const hidden = headerMenuRefs.current.get(field.id);
      const fallback = hidden ? headerMenuRefs.current.get(hidden.fallback) : void 0;
      setNextHeaderMenuToFocus(fallback?.node);
    };
    const handleHeaderContextMenu = (event) => {
      event.preventDefault();
      event.stopPropagation();
      const virtualAnchor = {
        getBoundingClientRect: () => ({
          x: event.clientX,
          y: event.clientY,
          top: event.clientY,
          left: event.clientX,
          right: event.clientX,
          bottom: event.clientY,
          width: 0,
          height: 0,
          toJSON: () => ({})
        })
      };
      window.requestAnimationFrame(() => {
        setContextMenuAnchor(virtualAnchor);
      });
    };
    const hasData = !!data?.length;
    const titleField = fields2.find((field) => field.id === view.titleField);
    const mediaField = fields2.find((field) => field.id === view.mediaField);
    const descriptionField2 = fields2.find(
      (field) => field.id === view.descriptionField
    );
    const { showTitle = true, showMedia = true, showDescription = true } = view;
    const hasPrimaryColumn = titleField && showTitle || mediaField && showMedia || descriptionField2 && showDescription;
    const columns = view.fields ?? [];
    const headerMenuRef = (column, index2) => (node) => {
      if (node) {
        headerMenuRefs.current.set(column, {
          node,
          fallback: columns[index2 > 0 ? index2 - 1 : 1]
        });
      } else {
        headerMenuRefs.current.delete(column);
      }
    };
    const isInfiniteScroll = view.infiniteScrollEnabled && !dataByGroup;
    const isRtl = (0, import_i18n32.isRTL)();
    if (!hasData) {
      return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
        "div",
        {
          className: clsx_default("dataviews-no-results", {
            "is-refreshing": isDelayedLoading
          }),
          id: tableNoticeId,
          children: empty
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(import_jsx_runtime131.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(
        "table",
        {
          className: clsx_default("dataviews-view-table", className, {
            [`has-${view.layout?.density}-density`]: view.layout?.density && ["compact", "comfortable"].includes(
              view.layout.density
            ),
            "has-bulk-actions": hasBulkActions,
            "is-refreshing": !isInfiniteScroll && isDelayedLoading
          }),
          "aria-busy": isLoading,
          "aria-describedby": tableNoticeId,
          role: isInfiniteScroll ? "feed" : void 0,
          inert: !isInfiniteScroll && isLoading ? "true" : void 0,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)("colgroup", { children: [
              hasBulkActions && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("col", { className: "dataviews-view-table__col-checkbox" }),
              hasPrimaryColumn && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("col", { className: "dataviews-view-table__col-first-data" }),
              columns.map((column, index2) => /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                "col",
                {
                  className: clsx_default(
                    `dataviews-view-table__col-${column}`,
                    {
                      "dataviews-view-table__col-expand": !hasPrimaryColumn && index2 === columns.length - 1
                    }
                  )
                },
                `col-${column}`
              )),
              !!actions?.length && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("col", { className: "dataviews-view-table__col-actions" })
            ] }),
            contextMenuAnchor && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
              import_components25.Popover,
              {
                anchor: contextMenuAnchor,
                onClose: () => setContextMenuAnchor(null),
                placement: "bottom-start",
                children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(PropertiesSection, { showLabel: false })
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
              "thead",
              {
                className: clsx_default({
                  "dataviews-view-table__thead--stuck": isVerticallyScrolled
                }),
                onContextMenu: handleHeaderContextMenu,
                children: /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)("tr", { className: "dataviews-view-table__row", children: [
                  hasBulkActions && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                    "th",
                    {
                      className: "dataviews-view-table__checkbox-column",
                      scope: "col",
                      onContextMenu: handleHeaderContextMenu,
                      children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                        BulkSelectionCheckbox,
                        {
                          selection,
                          onChangeSelection,
                          data,
                          actions,
                          getItemId: getItemId2
                        }
                      )
                    }
                  ),
                  hasPrimaryColumn && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("th", { scope: "col", children: titleField && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                    column_header_menu_default,
                    {
                      ref: headerMenuRef(
                        titleField.id,
                        0
                      ),
                      fieldId: titleField.id,
                      view,
                      fields: fields2,
                      onChangeView,
                      onHide,
                      setOpenedFilter,
                      canMove: false,
                      canInsertLeft: isRtl ? view.layout?.enableMoving ?? true : false,
                      canInsertRight: isRtl ? false : view.layout?.enableMoving ?? true
                    }
                  ) }),
                  columns.map((column, index2) => {
                    const { width, maxWidth, minWidth, align } = view.layout?.styles?.[column] ?? {};
                    const field = fields2.find(
                      (f2) => f2.id === column
                    );
                    const effectiveAlign = getEffectiveAlign(
                      align,
                      field?.type
                    );
                    const canInsertOrMove = view.layout?.enableMoving ?? true;
                    return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                      "th",
                      {
                        style: {
                          width,
                          maxWidth,
                          minWidth,
                          textAlign: effectiveAlign
                        },
                        "aria-sort": view.sort?.direction && view.sort?.field === column ? sortValues[view.sort.direction] : void 0,
                        scope: "col",
                        children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                          column_header_menu_default,
                          {
                            ref: headerMenuRef(column, index2),
                            fieldId: column,
                            view,
                            fields: fields2,
                            onChangeView,
                            onHide,
                            setOpenedFilter,
                            canMove: canInsertOrMove,
                            canInsertLeft: canInsertOrMove,
                            canInsertRight: canInsertOrMove
                          }
                        )
                      },
                      column
                    );
                  }),
                  !!actions?.length && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                    "th",
                    {
                      className: clsx_default(
                        "dataviews-view-table__actions-column",
                        {
                          "dataviews-view-table__actions-column--sticky": true,
                          "dataviews-view-table__actions-column--stuck": !isHorizontalScrollEnd
                        }
                      ),
                      children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("span", { className: "dataviews-view-table-header", children: (0, import_i18n32.__)("Actions") })
                    }
                  )
                ] })
              }
            ),
            hasData && groupField && dataByGroup ? Array.from(dataByGroup.entries()).map(
              ([groupName, groupItems]) => /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)("tbody", { children: [
                /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("tr", { className: "dataviews-view-table__group-header-row", children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                  "td",
                  {
                    colSpan: columns.length + (hasPrimaryColumn ? 1 : 0) + (hasBulkActions ? 1 : 0) + (actions?.length ? 1 : 0),
                    className: "dataviews-view-table__group-header-cell",
                    children: view.groupBy?.showLabel === false ? groupName : (0, import_i18n32.sprintf)(
                      // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                      (0, import_i18n32.__)("%1$s: %2$s"),
                      groupField.label,
                      groupName
                    )
                  }
                ) }),
                groupItems.map((item, index2) => {
                  const id = getItemId2(item) || index2.toString();
                  return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                    TableRow,
                    {
                      item,
                      level: view.showLevels && typeof getItemLevel2 === "function" ? getItemLevel2(item) : void 0,
                      hasBulkActions,
                      actions,
                      fields: fields2,
                      id,
                      view,
                      titleField,
                      mediaField,
                      descriptionField: descriptionField2,
                      selection,
                      getItemId: getItemId2,
                      onChangeSelection,
                      ...getSelectionProps(id),
                      onClickItem,
                      renderItemLink,
                      isItemClickable,
                      isActionsColumnSticky: !isHorizontalScrollEnd
                    },
                    getItemId2(item)
                  );
                })
              ] }, `group-${groupName}`)
            ) : /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("tbody", { children: hasData && data.map((item, index2) => {
              const id = getItemId2(item) || index2.toString();
              return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
                TableRow,
                {
                  item,
                  level: view.showLevels && typeof getItemLevel2 === "function" ? getItemLevel2(item) : void 0,
                  hasBulkActions,
                  actions,
                  fields: fields2,
                  id,
                  view,
                  titleField,
                  mediaField,
                  descriptionField: descriptionField2,
                  selection,
                  getItemId: getItemId2,
                  onChangeSelection,
                  ...getSelectionProps(id),
                  onClickItem,
                  renderItemLink,
                  isItemClickable,
                  isActionsColumnSticky: !isHorizontalScrollEnd,
                  posinset: isInfiniteScroll ? index2 + 1 : void 0
                },
                getItemId2(item)
              );
            }) })
          ]
        }
      ),
      isInfiniteScroll && isLoading && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("div", { className: "dataviews-loading", id: tableNoticeId, children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(import_components25.Spinner, {}) }) })
    ] });
  }
  var table_default = ViewTable;

  // packages/dataviews/build-module/components/dataviews-layouts/grid/index.mjs
  var import_components28 = __toESM(require_components(), 1);
  var import_i18n35 = __toESM(require_i18n(), 1);

  // packages/dataviews/build-module/components/dataviews-layouts/grid/composite-grid.mjs
  var import_components27 = __toESM(require_components(), 1);
  var import_i18n34 = __toESM(require_i18n(), 1);
  var import_compose7 = __toESM(require_compose(), 1);
  var import_element70 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataviews-layouts/grid/preview-size-picker.mjs
  var import_components26 = __toESM(require_components(), 1);
  var import_i18n33 = __toESM(require_i18n(), 1);
  var import_element67 = __toESM(require_element(), 1);
  var import_jsx_runtime132 = __toESM(require_jsx_runtime(), 1);
  var imageSizes = [
    {
      value: 120,
      breakpoint: 1
    },
    {
      value: 170,
      breakpoint: 1
    },
    {
      value: 230,
      breakpoint: 1
    },
    {
      value: 290,
      breakpoint: 1112
      // at minimum image width, 4 images display at this container size
    },
    {
      value: 350,
      breakpoint: 1636
      // at minimum image width, 6 images display at this container size
    },
    {
      value: 430,
      breakpoint: 588
      // at minimum image width, 2 images display at this container size
    }
  ];
  var DEFAULT_PREVIEW_SIZE = imageSizes[2].value;
  function useGridColumns() {
    const context = (0, import_element67.useContext)(dataviews_context_default);
    const view = context.view;
    return (0, import_element67.useMemo)(() => {
      const containerWidth = context.containerWidth;
      const gap = 32;
      const previewSize = view.layout?.previewSize ?? DEFAULT_PREVIEW_SIZE;
      const columns = Math.floor(
        (containerWidth + gap) / (previewSize + gap)
      );
      return Math.max(1, columns);
    }, [context.containerWidth, view.layout?.previewSize]);
  }

  // packages/dataviews/build-module/components/dataviews-layouts/utils/grid-items.mjs
  var import_element68 = __toESM(require_element(), 1);
  var import_jsx_runtime133 = __toESM(require_jsx_runtime(), 1);
  var GridItems = (0, import_element68.forwardRef)(({ className, previewSize, ...props }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime133.jsx)(
      "div",
      {
        ref,
        className: clsx_default("dataviews-view-grid-items", className),
        style: {
          gridTemplateColumns: previewSize && `repeat(auto-fill, minmax(${previewSize}px, 1fr))`
        },
        ...props
      }
    );
  });

  // packages/dataviews/build-module/components/dataviews-layouts/utils/use-infinite-scroll.mjs
  var import_element69 = __toESM(require_element(), 1);
  function useIntersectionObserver(elementRef, posinset) {
    const { intersectionObserver } = (0, import_element69.useContext)(dataviews_context_default);
    (0, import_element69.useEffect)(() => {
      const element = elementRef.current;
      if (!element || posinset === void 0 || !intersectionObserver) {
        return;
      }
      intersectionObserver.observe(element);
      return () => {
        intersectionObserver.unobserve(element);
      };
    }, [elementRef, intersectionObserver, posinset]);
  }
  function usePlaceholdersNeeded(data, isInfiniteScroll, gridColumns) {
    const hasData = !!data?.length;
    const firstItemPosition = hasData && isInfiniteScroll ? data[0].position : void 0;
    return firstItemPosition && gridColumns ? (firstItemPosition - 1) % gridColumns : 0;
  }

  // packages/dataviews/build-module/components/dataviews-layouts/grid/composite-grid.mjs
  var import_jsx_runtime134 = __toESM(require_jsx_runtime(), 1);
  var { Badge: WCBadge } = unlock4(import_components27.privateApis);
  function chunk(array, size4) {
    const chunks = [];
    for (let i2 = 0, j2 = array.length; i2 < j2; i2 += size4) {
      chunks.push(array.slice(i2, i2 + size4));
    }
    return chunks;
  }
  var GridItem = (0, import_element70.forwardRef)(
    function GridItem2({
      view,
      selection,
      onChangeSelection,
      onClickItem,
      isItemClickable,
      renderItemLink,
      getItemId: getItemId2,
      item,
      actions,
      mediaField,
      titleField,
      descriptionField: descriptionField2,
      regularFields,
      badgeFields,
      hasBulkActions,
      config: config2,
      posinset,
      setsize,
      ...props
    }, forwardedRef) {
      const {
        showTitle = true,
        showMedia = true,
        showDescription = true
      } = view;
      const hasBulkAction = useHasAPossibleBulkAction(actions, item);
      const id = getItemId2(item);
      const elementRef = (0, import_element70.useRef)(null);
      const setRefs = (0, import_element70.useCallback)(
        (node) => {
          elementRef.current = node;
          if (typeof forwardedRef === "function") {
            forwardedRef(node);
          } else if (forwardedRef) {
            forwardedRef.current = node;
          }
        },
        [forwardedRef]
      );
      useIntersectionObserver(elementRef, posinset);
      const instanceId = (0, import_compose7.useInstanceId)(GridItem2);
      const isSelected2 = selection.includes(id);
      const mediaPlaceholder = /* @__PURE__ */ (0, import_jsx_runtime134.jsx)("span", { className: "dataviews-view-grid__media-placeholder" });
      const rendersMediaField = showMedia && mediaField?.render;
      const renderedMediaField = rendersMediaField ? /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
        mediaField.render,
        {
          item,
          field: mediaField,
          config: config2
        }
      ) : mediaPlaceholder;
      const renderedTitleField = showTitle && titleField?.render ? /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(titleField.render, { item, field: titleField }) : null;
      let mediaA11yProps;
      let titleA11yProps;
      if (isItemClickable(item) && onClickItem) {
        if (renderedTitleField) {
          mediaA11yProps = {
            "aria-labelledby": `dataviews-view-grid__title-field-${instanceId}`
          };
          titleA11yProps = {
            id: `dataviews-view-grid__title-field-${instanceId}`
          };
        } else {
          mediaA11yProps = {
            "aria-label": (0, import_i18n34.__)("Navigate to item")
          };
        }
      }
      return /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(
        Stack,
        {
          direction: "column",
          ...props,
          ref: setRefs,
          "aria-setsize": setsize,
          "aria-posinset": posinset,
          className: clsx_default(
            props.className,
            "dataviews-view-grid__row__gridcell",
            "dataviews-view-grid__card",
            {
              "is-selected": hasBulkAction && isSelected2
            }
          ),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
              ItemClickWrapper,
              {
                item,
                isItemClickable,
                onClickItem,
                renderItemLink,
                className: clsx_default("dataviews-view-grid__media", {
                  "dataviews-view-grid__media--placeholder": !rendersMediaField
                }),
                ...mediaA11yProps,
                children: renderedMediaField
              }
            ),
            hasBulkActions && /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
              DataViewsSelectionCheckbox,
              {
                item,
                selection,
                onChangeSelection,
                getItemId: getItemId2,
                titleField,
                disabled: !hasBulkAction
              }
            ),
            !!actions?.length && /* @__PURE__ */ (0, import_jsx_runtime134.jsx)("div", { className: "dataviews-view-grid__media-actions", children: /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
              ItemActions,
              {
                item,
                actions,
                isCompact: true
              }
            ) }),
            showTitle && /* @__PURE__ */ (0, import_jsx_runtime134.jsx)("div", { className: "dataviews-view-grid__title-actions", children: /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
              ItemClickWrapper,
              {
                item,
                isItemClickable,
                onClickItem,
                renderItemLink,
                className: "dataviews-view-grid__title-field dataviews-title-field",
                ...titleA11yProps,
                title: titleField?.getValueFormatted({
                  item,
                  field: titleField
                }) || void 0,
                children: renderedTitleField
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(Stack, { direction: "column", gap: "xs", children: [
              showDescription && descriptionField2?.render && /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                descriptionField2.render,
                {
                  item,
                  field: descriptionField2
                }
              ),
              !!badgeFields?.length && /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                Stack,
                {
                  direction: "row",
                  className: "dataviews-view-grid__badge-fields",
                  gap: "sm",
                  wrap: "wrap",
                  align: "top",
                  justify: "flex-start",
                  children: badgeFields.map((field) => {
                    return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                      WCBadge,
                      {
                        className: "dataviews-view-grid__field-value",
                        children: /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                          field.render,
                          {
                            item,
                            field
                          }
                        )
                      },
                      field.id
                    );
                  })
                }
              ),
              !!regularFields?.length && /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                Stack,
                {
                  direction: "column",
                  className: "dataviews-view-grid__fields",
                  gap: "xs",
                  children: regularFields.map((field) => {
                    return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                      import_components27.Flex,
                      {
                        className: "dataviews-view-grid__field",
                        gap: 1,
                        justify: "flex-start",
                        expanded: true,
                        style: { height: "auto" },
                        direction: "row",
                        children: /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(import_jsx_runtime134.Fragment, { children: [
                          /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(tooltip_exports.Root, { children: [
                            /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                              tooltip_exports.Trigger,
                              {
                                render: /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(import_components27.FlexItem, { className: "dataviews-view-grid__field-name", children: field.header })
                              }
                            ),
                            /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(tooltip_exports.Popup, { children: field.label })
                          ] }),
                          /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                            import_components27.FlexItem,
                            {
                              className: "dataviews-view-grid__field-value",
                              style: { maxHeight: "none" },
                              children: /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                                field.render,
                                {
                                  item,
                                  field
                                }
                              )
                            }
                          )
                        ] })
                      },
                      field.id
                    );
                  })
                }
              )
            ] })
          ]
        }
      );
    }
  );
  function CompositeGrid({
    data,
    isInfiniteScroll,
    className,
    inert,
    isLoading,
    view,
    fields: fields2,
    selection,
    onChangeSelection,
    onClickItem,
    isItemClickable,
    renderItemLink,
    getItemId: getItemId2,
    actions,
    getSelectionProps
  }) {
    const { paginationInfo, resizeObserverRef } = (0, import_element70.useContext)(dataviews_context_default);
    const gridColumns = useGridColumns();
    const hasBulkActions = useSomeItemHasAPossibleBulkAction(actions, data);
    const titleField = fields2.find(
      (field) => field.id === view?.titleField
    );
    const mediaField = fields2.find(
      (field) => field.id === view?.mediaField
    );
    const descriptionField2 = fields2.find(
      (field) => field.id === view?.descriptionField
    );
    const otherFields = view.fields ?? [];
    const { regularFields, badgeFields } = otherFields.reduce(
      (accumulator, fieldId) => {
        const field = fields2.find((f2) => f2.id === fieldId);
        if (!field) {
          return accumulator;
        }
        const key = view.layout?.badgeFields?.includes(fieldId) ? "badgeFields" : "regularFields";
        accumulator[key].push(field);
        return accumulator;
      },
      { regularFields: [], badgeFields: [] }
    );
    const size4 = "900px";
    const totalRows = Math.ceil(data.length / gridColumns);
    const placeholdersNeeded = usePlaceholdersNeeded(
      data,
      isInfiniteScroll,
      gridColumns
    );
    return /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(import_jsx_runtime134.Fragment, {
      // Render infinite scroll layout (no rows, feed semantics)
      children: [
        isInfiniteScroll && /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(
          import_components27.Composite,
          {
            render: /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
              GridItems,
              {
                className: clsx_default(
                  "dataviews-view-grid-infinite-scroll",
                  className,
                  {
                    [`has-${view.layout?.density}-density`]: view.layout?.density && [
                      "compact",
                      "comfortable"
                    ].includes(view.layout.density)
                  }
                ),
                previewSize: view.layout?.previewSize,
                "aria-busy": isLoading,
                ref: resizeObserverRef
              }
            ),
            role: "feed",
            focusWrap: true,
            inert,
            children: [
              Array.from({ length: placeholdersNeeded }).map(
                (_, index2) => /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                  import_components27.Composite.Item,
                  {
                    render: (props) => /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                      Stack,
                      {
                        ...props,
                        direction: "column",
                        role: "article",
                        className: "dataviews-view-grid__row__gridcell dataviews-view-grid__card dataviews-view-grid__placeholder"
                      }
                    ),
                    "aria-hidden": true,
                    tabIndex: -1
                  },
                  `placeholder-${index2}`
                )
              ),
              data.map((item) => {
                const itemId = getItemId2(item);
                const selectionProps = getSelectionProps(itemId);
                const stablePosition = item.position;
                return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                  import_components27.Composite.Item,
                  {
                    render: (props) => /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                      GridItem,
                      {
                        ...props,
                        id: itemId,
                        role: "article",
                        view,
                        selection,
                        onChangeSelection,
                        onClickItem,
                        isItemClickable,
                        renderItemLink,
                        getItemId: getItemId2,
                        item,
                        actions,
                        onMouseDown: (event) => {
                          props.onMouseDown?.(event);
                          selectionProps.onMouseDown(
                            event
                          );
                        },
                        onClickCapture: (event) => {
                          props.onClickCapture?.(event);
                          selectionProps.onClickCapture(
                            event
                          );
                        },
                        mediaField,
                        titleField,
                        descriptionField: descriptionField2,
                        regularFields,
                        badgeFields,
                        hasBulkActions,
                        posinset: stablePosition,
                        setsize: paginationInfo.totalItems,
                        config: {
                          sizes: size4
                        }
                      }
                    )
                  },
                  itemId
                );
              })
            ]
          }
        ),
        // Render standard grid layout (with rows, grid semantics)
        !isInfiniteScroll && /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
          import_components27.Composite,
          {
            role: "grid",
            className: clsx_default("dataviews-view-grid", className, {
              [`has-${view.layout?.density}-density`]: view.layout?.density && ["compact", "comfortable"].includes(
                view.layout.density
              )
            }),
            focusWrap: true,
            "aria-busy": isLoading,
            "aria-rowcount": totalRows,
            ref: resizeObserverRef,
            inert,
            children: chunk(data, gridColumns).map((row, i2) => /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
              import_components27.Composite.Row,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                  "div",
                  {
                    role: "row",
                    "aria-rowindex": i2 + 1,
                    "aria-label": (0, import_i18n34.sprintf)(
                      /* translators: %d: The row number in the grid */
                      (0, import_i18n34.__)("Row %d"),
                      i2 + 1
                    ),
                    className: "dataviews-view-grid__row",
                    style: {
                      gridTemplateColumns: `repeat( ${gridColumns}, minmax(0, 1fr) )`
                    }
                  }
                ),
                children: row.map((item) => {
                  const itemId = getItemId2(item);
                  const selectionProps = getSelectionProps(itemId);
                  return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                    import_components27.Composite.Item,
                    {
                      render: (props) => /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
                        GridItem,
                        {
                          ...props,
                          id: itemId,
                          role: "gridcell",
                          view,
                          selection,
                          onChangeSelection,
                          onClickItem,
                          isItemClickable,
                          renderItemLink,
                          getItemId: getItemId2,
                          item,
                          actions,
                          onMouseDown: (event) => {
                            props.onMouseDown?.(
                              event
                            );
                            selectionProps.onMouseDown(
                              event
                            );
                          },
                          onClickCapture: (event) => {
                            props.onClickCapture?.(
                              event
                            );
                            selectionProps.onClickCapture(
                              event
                            );
                          },
                          mediaField,
                          titleField,
                          descriptionField: descriptionField2,
                          regularFields,
                          badgeFields,
                          hasBulkActions,
                          config: {
                            sizes: size4
                          }
                        }
                      )
                    },
                    itemId
                  );
                })
              },
              i2
            ))
          }
        )
      ]
    });
  }

  // packages/dataviews/build-module/components/dataviews-layouts/grid/index.mjs
  var import_jsx_runtime135 = __toESM(require_jsx_runtime(), 1);
  function ViewGrid({
    actions,
    data,
    fields: fields2,
    getItemId: getItemId2,
    isLoading,
    onChangeSelection,
    onClickItem,
    isItemClickable,
    renderItemLink,
    selection,
    view,
    className,
    empty
  }) {
    const isDelayedLoading = useDelayedLoading(!!isLoading);
    const hasData = !!data?.length;
    const groupField = view.groupBy?.field ? fields2.find((f2) => f2.id === view.groupBy?.field) : null;
    const dataByGroup = groupField ? getDataByGroup(data, groupField) : null;
    const isInfiniteScroll = view.infiniteScrollEnabled && !dataByGroup;
    const orderedData = dataByGroup ? Array.from(dataByGroup.values()).flat() : data;
    const { getSelectionProps } = useSelectionProps({
      data: orderedData,
      actions,
      getItemId: getItemId2,
      selection,
      onChangeSelection
    });
    if (!hasData) {
      return /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(
        "div",
        {
          className: clsx_default("dataviews-no-results", {
            "is-refreshing": isDelayedLoading
          }),
          children: empty
        }
      );
    }
    const gridProps = {
      className: clsx_default(className, {
        "is-refreshing": !isInfiniteScroll && isDelayedLoading
      }),
      inert: !isInfiniteScroll && !!isLoading ? "true" : void 0,
      isLoading,
      view,
      fields: fields2,
      selection,
      onChangeSelection,
      onClickItem,
      isItemClickable,
      renderItemLink,
      getItemId: getItemId2,
      actions,
      getSelectionProps
    };
    return /* @__PURE__ */ (0, import_jsx_runtime135.jsxs)(import_jsx_runtime135.Fragment, {
      // Render multiple groups.
      children: [
        hasData && groupField && dataByGroup && /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Stack, { direction: "column", gap: "lg", children: Array.from(dataByGroup.entries()).map(
          ([groupName, groupItems]) => /* @__PURE__ */ (0, import_jsx_runtime135.jsxs)(
            Stack,
            {
              direction: "column",
              gap: "sm",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime135.jsx)("h3", { className: "dataviews-view-grid__group-header", children: view.groupBy?.showLabel === false ? groupName : (0, import_i18n35.sprintf)(
                  // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                  (0, import_i18n35.__)("%1$s: %2$s"),
                  groupField.label,
                  groupName
                ) }),
                /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(
                  CompositeGrid,
                  {
                    ...gridProps,
                    data: groupItems,
                    isInfiniteScroll: false
                  }
                )
              ]
            },
            groupName
          )
        ) }),
        // Render a single grid with all data.
        !dataByGroup && /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(
          CompositeGrid,
          {
            ...gridProps,
            data,
            isInfiniteScroll: !!isInfiniteScroll
          }
        ),
        isInfiniteScroll && isLoading && /* @__PURE__ */ (0, import_jsx_runtime135.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(import_components28.Spinner, {}) })
      ]
    });
  }
  var grid_default = ViewGrid;

  // packages/dataviews/build-module/components/dataviews-layouts/list/index.mjs
  var import_compose8 = __toESM(require_compose(), 1);
  var import_components29 = __toESM(require_components(), 1);
  var import_element71 = __toESM(require_element(), 1);
  var import_i18n36 = __toESM(require_i18n(), 1);
  var import_data37 = __toESM(require_data(), 1);
  var import_jsx_runtime136 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu3 } = unlock4(import_components29.privateApis);
  function generateItemWrapperCompositeId(idPrefix) {
    return `${idPrefix}-item-wrapper`;
  }
  function generatePrimaryActionCompositeId(idPrefix, primaryActionId) {
    return `${idPrefix}-primary-action-${primaryActionId}`;
  }
  function generateDropdownTriggerCompositeId(idPrefix) {
    return `${idPrefix}-dropdown`;
  }
  function PrimaryActionGridCell({
    idPrefix,
    primaryAction,
    item
  }) {
    const registry = (0, import_data37.useRegistry)();
    const [isModalOpen, setIsModalOpen] = (0, import_element71.useState)(false);
    const compositeItemId = generatePrimaryActionCompositeId(
      idPrefix,
      primaryAction.id
    );
    const label = typeof primaryAction.label === "string" ? primaryAction.label : primaryAction.label([item]);
    return "RenderModal" in primaryAction ? /* @__PURE__ */ (0, import_jsx_runtime136.jsx)("div", { role: "gridcell", children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
      import_components29.Composite.Item,
      {
        id: compositeItemId,
        render: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
          import_components29.Button,
          {
            disabled: !!primaryAction.disabled,
            accessibleWhenDisabled: true,
            text: label,
            size: "small",
            onClick: () => setIsModalOpen(true)
          }
        ),
        children: isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
          ActionModal,
          {
            action: primaryAction,
            items: [item],
            closeModal: () => setIsModalOpen(false)
          }
        )
      }
    ) }, primaryAction.id) : /* @__PURE__ */ (0, import_jsx_runtime136.jsx)("div", { role: "gridcell", children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
      import_components29.Composite.Item,
      {
        id: compositeItemId,
        render: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
          import_components29.Button,
          {
            disabled: !!primaryAction.disabled,
            accessibleWhenDisabled: true,
            size: "small",
            onClick: () => {
              primaryAction.callback([item], { registry });
            },
            children: label
          }
        )
      }
    ) }, primaryAction.id);
  }
  function ListItem({
    view,
    actions,
    idPrefix,
    isSelected: isSelected2,
    item,
    titleField,
    mediaField,
    descriptionField: descriptionField2,
    onSelect,
    otherFields,
    onDropdownTriggerKeyDown,
    posinset
  }) {
    const {
      showTitle = true,
      showMedia = true,
      showDescription = true,
      infiniteScrollEnabled
    } = view;
    const itemRef = (0, import_element71.useRef)(null);
    const labelId = `${idPrefix}-label`;
    const descriptionId = `${idPrefix}-description`;
    const registry = (0, import_data37.useRegistry)();
    const [isHovered, setIsHovered] = (0, import_element71.useState)(false);
    const [activeModalAction, setActiveModalAction] = (0, import_element71.useState)(
      null
    );
    const handleHover = ({ type }) => {
      const isHover = type === "mouseenter";
      setIsHovered(isHover);
    };
    const { paginationInfo } = (0, import_element71.useContext)(dataviews_context_default);
    (0, import_element71.useEffect)(() => {
      if (isSelected2) {
        itemRef.current?.scrollIntoView({
          behavior: "auto",
          block: "nearest",
          inline: "nearest"
        });
      }
    }, [isSelected2]);
    const { primaryAction, eligibleActions } = (0, import_element71.useMemo)(() => {
      const _eligibleActions = actions.filter(
        (action) => !action.isEligible || action.isEligible(item)
      );
      const _primaryActions = _eligibleActions.filter(
        (action) => action.isPrimary
      );
      return {
        primaryAction: _primaryActions[0],
        eligibleActions: _eligibleActions
      };
    }, [actions, item]);
    const hasOnlyOnePrimaryAction = primaryAction && actions.length === 1;
    const renderedMediaField = showMedia && mediaField?.render ? /* @__PURE__ */ (0, import_jsx_runtime136.jsx)("div", { className: "dataviews-view-list__media-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
      mediaField.render,
      {
        item,
        field: mediaField,
        config: { sizes: "52px" }
      }
    ) }) : null;
    const renderedTitleField = showTitle && titleField?.render ? /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(titleField.render, { item, field: titleField }) : null;
    const renderDescription = showDescription && descriptionField2?.render;
    const hasOnlyMediaAndTitle = !!renderedMediaField && !renderDescription && !otherFields.length;
    const usedActions = eligibleActions?.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(
      Stack,
      {
        direction: "row",
        gap: "md",
        className: "dataviews-view-list__item-actions",
        children: [
          primaryAction && /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
            PrimaryActionGridCell,
            {
              idPrefix,
              primaryAction,
              item
            }
          ),
          !hasOnlyOnePrimaryAction && /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)("div", { role: "gridcell", children: [
            /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(Menu3, { placement: "bottom-end", children: [
              /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                Menu3.TriggerButton,
                {
                  render: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                    import_components29.Composite.Item,
                    {
                      id: generateDropdownTriggerCompositeId(
                        idPrefix
                      ),
                      render: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                        import_components29.Button,
                        {
                          size: "small",
                          icon: more_vertical_default,
                          label: (0, import_i18n36.__)("Actions"),
                          accessibleWhenDisabled: true,
                          disabled: !actions.length,
                          onKeyDown: onDropdownTriggerKeyDown
                        }
                      )
                    }
                  )
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Menu3.Popover, { children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                ActionsMenuGroup,
                {
                  actions: eligibleActions,
                  item,
                  registry,
                  setActiveModalAction
                }
              ) })
            ] }),
            !!activeModalAction && /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
              ActionModal,
              {
                action: activeModalAction,
                items: [item],
                closeModal: () => setActiveModalAction(null)
              }
            )
          ] })
        ]
      }
    );
    return /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
      import_components29.Composite.Row,
      {
        ref: itemRef,
        render: (
          /* aria-posinset breaks Composite.Row if passed to it directly. */
          /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
            "div",
            {
              "aria-posinset": posinset,
              "aria-setsize": infiniteScrollEnabled ? paginationInfo.totalItems : void 0
            }
          )
        ),
        role: infiniteScrollEnabled ? "article" : "row",
        className: clsx_default({
          "is-selected": isSelected2,
          "is-hovered": isHovered
        }),
        onMouseEnter: handleHover,
        onMouseLeave: handleHover,
        children: /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(
          Stack,
          {
            direction: "row",
            className: "dataviews-view-list__item-wrapper",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime136.jsx)("div", { role: "gridcell", children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                import_components29.Composite.Item,
                {
                  id: generateItemWrapperCompositeId(idPrefix),
                  "aria-pressed": isSelected2,
                  "aria-labelledby": labelId,
                  "aria-describedby": descriptionId,
                  className: "dataviews-view-list__item",
                  onClick: () => onSelect(item)
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(
                Stack,
                {
                  direction: "row",
                  gap: "md",
                  justify: "start",
                  align: hasOnlyMediaAndTitle ? "center" : "flex-start",
                  style: { flex: 1, minWidth: 0 },
                  children: [
                    renderedMediaField,
                    /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(
                      Stack,
                      {
                        direction: "column",
                        gap: "xs",
                        className: "dataviews-view-list__field-wrapper",
                        children: [
                          /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(Stack, { direction: "row", align: "center", children: [
                            /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                              "div",
                              {
                                className: "dataviews-title-field dataviews-view-list__title-field",
                                id: labelId,
                                children: renderedTitleField
                              }
                            ),
                            usedActions
                          ] }),
                          renderDescription && /* @__PURE__ */ (0, import_jsx_runtime136.jsx)("div", { className: "dataviews-view-list__field", children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                            descriptionField2.render,
                            {
                              item,
                              field: descriptionField2
                            }
                          ) }),
                          /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                            "div",
                            {
                              className: "dataviews-view-list__fields",
                              id: descriptionId,
                              children: otherFields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(
                                "div",
                                {
                                  className: "dataviews-view-list__field",
                                  children: [
                                    /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                                      VisuallyHidden,
                                      {
                                        className: "dataviews-view-list__field-label",
                                        render: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)("span", {}),
                                        children: field.label
                                      }
                                    ),
                                    /* @__PURE__ */ (0, import_jsx_runtime136.jsx)("span", { className: "dataviews-view-list__field-value", children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                                      field.render,
                                      {
                                        item,
                                        field
                                      }
                                    ) })
                                  ]
                                },
                                field.id
                              ))
                            }
                          )
                        ]
                      }
                    )
                  ]
                }
              )
            ]
          }
        )
      }
    );
  }
  function isDefined2(item) {
    return !!item;
  }
  function ViewList(props) {
    const {
      actions,
      data,
      fields: fields2,
      getItemId: getItemId2,
      isLoading,
      onChangeSelection,
      selection,
      view,
      className,
      empty
    } = props;
    const baseId = (0, import_compose8.useInstanceId)(ViewList, "view-list");
    const isDelayedLoading = useDelayedLoading(!!isLoading);
    const { paginationInfo } = (0, import_element71.useContext)(dataviews_context_default);
    const selectedItem = data?.findLast(
      (item) => selection.includes(getItemId2(item))
    );
    const titleField = fields2.find((field) => field.id === view.titleField);
    const mediaField = fields2.find((field) => field.id === view.mediaField);
    const descriptionField2 = fields2.find(
      (field) => field.id === view.descriptionField
    );
    const otherFields = (view?.fields ?? []).map((fieldId) => fields2.find((f2) => fieldId === f2.id)).filter(isDefined2);
    const onSelect = (item) => onChangeSelection([getItemId2(item)]);
    const generateCompositeItemIdPrefix = (0, import_element71.useCallback)(
      (item) => `${baseId}-${getItemId2(item)}`,
      [baseId, getItemId2]
    );
    const isActiveCompositeItem = (0, import_element71.useCallback)(
      (item, idToCheck) => {
        return idToCheck.startsWith(
          generateCompositeItemIdPrefix(item)
        );
      },
      [generateCompositeItemIdPrefix]
    );
    const [activeCompositeId, setActiveCompositeId] = (0, import_element71.useState)(void 0);
    const compositeRef = (0, import_element71.useRef)(null);
    (0, import_element71.useEffect)(() => {
      if (selectedItem) {
        setActiveCompositeId(
          generateItemWrapperCompositeId(
            generateCompositeItemIdPrefix(selectedItem)
          )
        );
      }
    }, [selectedItem, generateCompositeItemIdPrefix]);
    const activeItemIndex = data.findIndex(
      (item) => isActiveCompositeItem(item, activeCompositeId ?? "")
    );
    const previousActiveItemIndex = (0, import_compose8.usePrevious)(activeItemIndex);
    const isActiveIdInList = activeItemIndex !== -1;
    const selectCompositeItem = (0, import_element71.useCallback)(
      (targetIndex, generateCompositeId) => {
        const clampedIndex = Math.min(
          data.length - 1,
          Math.max(0, targetIndex)
        );
        if (!data[clampedIndex]) {
          return;
        }
        const itemIdPrefix = generateCompositeItemIdPrefix(
          data[clampedIndex]
        );
        const targetCompositeItemId = generateCompositeId(itemIdPrefix);
        setActiveCompositeId(targetCompositeItemId);
        if (compositeRef.current?.contains(
          compositeRef.current.ownerDocument.activeElement
        )) {
          document.getElementById(targetCompositeItemId)?.focus();
        }
      },
      [data, generateCompositeItemIdPrefix]
    );
    (0, import_element71.useEffect)(() => {
      const wasActiveIdInList = previousActiveItemIndex !== void 0 && previousActiveItemIndex !== -1;
      if (!isActiveIdInList && wasActiveIdInList) {
        selectCompositeItem(
          previousActiveItemIndex,
          generateItemWrapperCompositeId
        );
      }
    }, [isActiveIdInList, selectCompositeItem, previousActiveItemIndex]);
    const onDropdownTriggerKeyDown = (0, import_element71.useCallback)(
      (event) => {
        if (event.key === "ArrowDown") {
          event.preventDefault();
          selectCompositeItem(
            activeItemIndex + 1,
            generateDropdownTriggerCompositeId
          );
        }
        if (event.key === "ArrowUp") {
          event.preventDefault();
          selectCompositeItem(
            activeItemIndex - 1,
            generateDropdownTriggerCompositeId
          );
        }
      },
      [selectCompositeItem, activeItemIndex]
    );
    const hasData = !!data?.length;
    const groupField = view.groupBy?.field ? fields2.find((field) => field.id === view.groupBy?.field) : null;
    const dataByGroup = hasData && groupField ? getDataByGroup(data, groupField) : null;
    const isInfiniteScroll = view.infiniteScrollEnabled && !dataByGroup;
    const hasMoreItems = isInfiniteScroll && (view.startPosition ?? 1) + (view.perPage ?? 0) < paginationInfo.totalItems;
    const listClassName = clsx_default("dataviews-view-list", className, {
      [`has-${view.layout?.density}-density`]: view.layout?.density && ["compact", "comfortable"].includes(view.layout.density),
      "is-refreshing": !isInfiniteScroll && isDelayedLoading
    });
    const compositeProps = {
      ref: compositeRef,
      id: baseId,
      render: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)("div", {}),
      activeId: activeCompositeId,
      setActiveId: setActiveCompositeId,
      inert: !isInfiniteScroll && !!isLoading ? "true" : void 0
    };
    if (!hasData) {
      return /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
        "div",
        {
          className: clsx_default("dataviews-no-results", {
            "is-refreshing": isDelayedLoading
          }),
          children: empty
        }
      );
    }
    if (hasData && groupField && dataByGroup) {
      return /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
        import_components29.Composite,
        {
          ...compositeProps,
          className: "dataviews-view-list__group",
          role: "grid",
          children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Stack, { direction: "column", gap: "lg", className: listClassName, children: Array.from(dataByGroup.entries()).map(
            ([groupName, groupItems]) => /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(Stack, { direction: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime136.jsx)("h3", { className: "dataviews-view-list__group-header", children: view.groupBy?.showLabel === false ? groupName : (0, import_i18n36.sprintf)(
                // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                (0, import_i18n36.__)("%1$s: %2$s"),
                groupField.label,
                groupName
              ) }),
              groupItems.map((item) => {
                const id = generateCompositeItemIdPrefix(item);
                return /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
                  ListItem,
                  {
                    view,
                    idPrefix: id,
                    actions,
                    item,
                    isSelected: item === selectedItem,
                    onSelect,
                    mediaField,
                    titleField,
                    descriptionField: descriptionField2,
                    otherFields,
                    onDropdownTriggerKeyDown
                  },
                  id
                );
              })
            ] }, groupName)
          ) })
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(import_jsx_runtime136.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
        import_components29.Composite,
        {
          ...compositeProps,
          className: listClassName,
          role: view.infiniteScrollEnabled ? "feed" : "grid",
          children: data.map((item, index2) => {
            const id = generateCompositeItemIdPrefix(item);
            return /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
              ListItem,
              {
                view,
                idPrefix: id,
                actions,
                item,
                isSelected: item === selectedItem,
                onSelect,
                mediaField,
                titleField,
                descriptionField: descriptionField2,
                otherFields,
                onDropdownTriggerKeyDown,
                posinset: view.infiniteScrollEnabled ? index2 + 1 : void 0
              },
              id
            );
          })
        }
      ),
      (hasMoreItems || isInfiniteScroll && isLoading) && // Keep the spinner's height reserved while loading more so the
      // scroll position doesn't bounce. Hidden, and silent to a11y,
      // while idle.
      /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
        "p",
        {
          className: "dataviews-loading-more",
          "aria-hidden": !isLoading,
          children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(import_components29.Spinner, {})
        }
      )
    ] });
  }

  // packages/dataviews/build-module/components/dataviews-layouts/activity/index.mjs
  var import_components30 = __toESM(require_components(), 1);

  // packages/dataviews/build-module/components/dataviews-layouts/activity/activity-group.mjs
  var import_i18n37 = __toESM(require_i18n(), 1);
  var import_element72 = __toESM(require_element(), 1);
  var import_jsx_runtime137 = __toESM(require_jsx_runtime(), 1);
  function ActivityGroup({
    groupName,
    groupData,
    groupField,
    showLabel = true,
    children
  }) {
    const groupHeader = showLabel ? (0, import_element72.createInterpolateElement)(
      // translators: %s: The label of the field e.g. "Status".
      (0, import_i18n37.sprintf)((0, import_i18n37.__)("%s: <groupName />"), groupField.label).trim(),
      {
        groupName: /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(
          groupField.render,
          {
            item: groupData[0],
            field: groupField
          }
        )
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(groupField.render, { item: groupData[0], field: groupField });
    return /* @__PURE__ */ (0, import_jsx_runtime137.jsxs)(
      Stack,
      {
        direction: "column",
        className: "dataviews-view-activity__group",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime137.jsx)("h3", { className: "dataviews-view-activity__group-header", children: groupHeader }),
          children
        ]
      },
      groupName
    );
  }

  // packages/dataviews/build-module/components/dataviews-layouts/activity/activity-item.mjs
  var import_element73 = __toESM(require_element(), 1);
  var import_data38 = __toESM(require_data(), 1);
  var import_compose9 = __toESM(require_compose(), 1);
  var import_jsx_runtime138 = __toESM(require_jsx_runtime(), 1);
  function ActivityItem(props) {
    const {
      view,
      actions,
      item,
      titleField,
      mediaField,
      descriptionField: descriptionField2,
      otherFields,
      posinset,
      onClickItem,
      renderItemLink,
      isItemClickable
    } = props;
    const {
      showTitle = true,
      showMedia = true,
      showDescription = true,
      infiniteScrollEnabled
    } = view;
    const itemRef = (0, import_element73.useRef)(null);
    const registry = (0, import_data38.useRegistry)();
    const { paginationInfo } = (0, import_element73.useContext)(dataviews_context_default);
    const { primaryActions, eligibleActions } = (0, import_element73.useMemo)(() => {
      const _eligibleActions = actions.filter(
        (action) => !action.isEligible || action.isEligible(item)
      );
      const _primaryActions = _eligibleActions.filter(
        (action) => action.isPrimary
      );
      return {
        primaryActions: _primaryActions,
        eligibleActions: _eligibleActions
      };
    }, [actions, item]);
    const isMobileViewport = (0, import_compose9.useViewportMatch)("medium", "<");
    const density = view.layout?.density ?? "balanced";
    const mediaContent = showMedia && density !== "compact" && mediaField?.render ? /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
      mediaField.render,
      {
        item,
        field: mediaField,
        config: {
          sizes: density === "comfortable" ? "32px" : "24px"
        }
      }
    ) : null;
    const renderedMediaField = /* @__PURE__ */ (0, import_jsx_runtime138.jsx)("div", { className: "dataviews-view-activity__item-type-icon", children: mediaContent || /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
      "span",
      {
        className: "dataviews-view-activity__item-bullet",
        "aria-hidden": "true"
      }
    ) });
    const renderedTitleField = showTitle && titleField?.render ? /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(titleField.render, { item, field: titleField }) : null;
    const verticalGap = (0, import_element73.useMemo)(() => {
      switch (density) {
        case "comfortable":
          return "md";
        default:
          return "sm";
      }
    }, [density]);
    return /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
      "div",
      {
        ref: itemRef,
        role: infiniteScrollEnabled ? "article" : void 0,
        "aria-posinset": posinset,
        "aria-setsize": infiniteScrollEnabled ? paginationInfo.totalItems : void 0,
        className: clsx_default(
          "dataviews-view-activity__item",
          density === "compact" && "is-compact",
          density === "balanced" && "is-balanced",
          density === "comfortable" && "is-comfortable"
        ),
        children: /* @__PURE__ */ (0, import_jsx_runtime138.jsxs)(Stack, { direction: "row", gap: "lg", justify: "start", align: "flex-start", children: [
          /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
            Stack,
            {
              direction: "column",
              gap: "xs",
              align: "center",
              className: "dataviews-view-activity__item-type",
              children: renderedMediaField
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime138.jsxs)(
            Stack,
            {
              direction: "column",
              gap: verticalGap,
              align: "flex-start",
              className: "dataviews-view-activity__item-content",
              children: [
                renderedTitleField && /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
                  ItemClickWrapper,
                  {
                    item,
                    isItemClickable,
                    onClickItem,
                    renderItemLink,
                    className: "dataviews-view-activity__item-title",
                    children: renderedTitleField
                  }
                ),
                showDescription && descriptionField2 && /* @__PURE__ */ (0, import_jsx_runtime138.jsx)("div", { className: "dataviews-view-activity__item-description", children: /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
                  descriptionField2.render,
                  {
                    item,
                    field: descriptionField2
                  }
                ) }),
                /* @__PURE__ */ (0, import_jsx_runtime138.jsx)("div", { className: "dataviews-view-activity__item-fields", children: otherFields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime138.jsxs)(
                  "div",
                  {
                    className: "dataviews-view-activity__item-field",
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
                        VisuallyHidden,
                        {
                          className: "dataviews-view-activity__item-field-label",
                          render: /* @__PURE__ */ (0, import_jsx_runtime138.jsx)("span", {}),
                          children: field.label
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime138.jsx)("span", { className: "dataviews-view-activity__item-field-value", children: /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
                        field.render,
                        {
                          item,
                          field
                        }
                      ) })
                    ]
                  },
                  field.id
                )) }),
                !!primaryActions?.length && /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
                  PrimaryActions,
                  {
                    item,
                    actions: primaryActions,
                    registry,
                    buttonVariant: "secondary"
                  }
                )
              ]
            }
          ),
          (primaryActions.length < eligibleActions.length || // Since we hide primary actions on mobile, we need to show the menu
          // there if there are any actions at all.
          isMobileViewport && // At the same time, only show the menu if there are actions to show.
          eligibleActions.length > 0) && /* @__PURE__ */ (0, import_jsx_runtime138.jsx)("div", { className: "dataviews-view-activity__item-actions", children: /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
            ItemActions,
            {
              item,
              actions: eligibleActions,
              isCompact: true
            }
          ) })
        ] })
      }
    );
  }
  var activity_item_default = ActivityItem;

  // packages/dataviews/build-module/components/dataviews-layouts/activity/activity-items.mjs
  var import_react15 = __toESM(require_react(), 1);
  function isDefined3(item) {
    return !!item;
  }
  function ActivityItems(props) {
    const { data, fields: fields2, getItemId: getItemId2, view } = props;
    const titleField = fields2.find((field) => field.id === view.titleField);
    const mediaField = fields2.find((field) => field.id === view.mediaField);
    const descriptionField2 = fields2.find(
      (field) => field.id === view.descriptionField
    );
    const otherFields = (view?.fields ?? []).map((fieldId) => fields2.find((f2) => fieldId === f2.id)).filter(isDefined3);
    return data.map((item, index2) => {
      return /* @__PURE__ */ (0, import_react15.createElement)(
        activity_item_default,
        {
          ...props,
          key: getItemId2(item),
          item,
          mediaField,
          titleField,
          descriptionField: descriptionField2,
          otherFields,
          posinset: view.infiniteScrollEnabled ? index2 + 1 : void 0
        }
      );
    });
  }

  // packages/dataviews/build-module/components/dataviews-layouts/activity/index.mjs
  var import_jsx_runtime139 = __toESM(require_jsx_runtime(), 1);
  function ViewActivity(props) {
    const { empty, data, fields: fields2, isLoading, view, className } = props;
    const isDelayedLoading = useDelayedLoading(!!isLoading);
    const hasData = !!data?.length;
    const groupField = view.groupBy?.field ? fields2.find((field) => field.id === view.groupBy?.field) : null;
    const dataByGroup = hasData && groupField ? getDataByGroup(data, groupField) : null;
    const isInfiniteScroll = view.infiniteScrollEnabled && !dataByGroup;
    if (!hasData) {
      return /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(
        "div",
        {
          className: clsx_default("dataviews-no-results", {
            "is-refreshing": isDelayedLoading
          }),
          children: empty
        }
      );
    }
    const isInert = !isInfiniteScroll && !!isLoading;
    const wrapperClassName = clsx_default("dataviews-view-activity", className, {
      "is-refreshing": !isInfiniteScroll && isDelayedLoading
    });
    const groupedEntries = dataByGroup ? Array.from(dataByGroup.entries()) : [];
    if (hasData && groupField && dataByGroup) {
      return /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(
        Stack,
        {
          direction: "column",
          gap: "sm",
          className: wrapperClassName,
          inert: isInert ? "true" : void 0,
          children: groupedEntries.map(
            ([groupName, groupData]) => /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(
              ActivityGroup,
              {
                groupName,
                groupData,
                groupField,
                showLabel: view.groupBy?.showLabel !== false,
                children: /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(
                  ActivityItems,
                  {
                    ...props,
                    data: groupData
                  }
                )
              },
              groupName
            )
          )
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime139.jsxs)(import_jsx_runtime139.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(
        "div",
        {
          className: wrapperClassName,
          role: view.infiniteScrollEnabled ? "feed" : void 0,
          inert: isInert ? "true" : void 0,
          children: /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(ActivityItems, { ...props })
        }
      ),
      isInfiniteScroll && isLoading && /* @__PURE__ */ (0, import_jsx_runtime139.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(import_components30.Spinner, {}) })
    ] });
  }

  // packages/dataviews/build-module/components/dataviews-layouts/picker-grid/index.mjs
  var import_components33 = __toESM(require_components(), 1);
  var import_i18n40 = __toESM(require_i18n(), 1);
  var import_compose10 = __toESM(require_compose(), 1);
  var import_element76 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataviews-picker-footer/index.mjs
  var import_components32 = __toESM(require_components(), 1);
  var import_data39 = __toESM(require_data(), 1);
  var import_element75 = __toESM(require_element(), 1);
  var import_i18n39 = __toESM(require_i18n(), 1);

  // packages/dataviews/build-module/components/dataviews-pagination/index.mjs
  var import_components31 = __toESM(require_components(), 1);
  var import_element74 = __toESM(require_element(), 1);
  var import_i18n38 = __toESM(require_i18n(), 1);
  var import_jsx_runtime140 = __toESM(require_jsx_runtime(), 1);
  function hasPaginationControls(view, paginationInfo) {
    return !view.infiniteScrollEnabled && paginationInfo.totalItems > 0 && paginationInfo.totalPages > 1;
  }
  function DataViewsPagination() {
    const { view, onChangeView, paginationInfo } = (0, import_element74.useContext)(dataviews_context_default);
    if (!hasPaginationControls(view, paginationInfo)) {
      return null;
    }
    const { totalPages } = paginationInfo;
    const currentPage = view.page ?? 1;
    const pageSelectOptions = Array.from(Array(totalPages)).map(
      (_, i2) => {
        const page = i2 + 1;
        return {
          value: page.toString(),
          label: page.toString(),
          "aria-label": currentPage === page ? (0, import_i18n38.sprintf)(
            // translators: 1: current page number. 2: total number of pages.
            (0, import_i18n38.__)("Page %1$d of %2$d"),
            currentPage,
            totalPages
          ) : page.toString()
        };
      }
    );
    return /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(
      Stack,
      {
        direction: "row",
        className: "dataviews-pagination",
        justify: "end",
        align: "center",
        gap: "xl",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
            Stack,
            {
              direction: "row",
              justify: "flex-start",
              align: "center",
              gap: "xs",
              className: "dataviews-pagination__page-select",
              children: (0, import_element74.createInterpolateElement)(
                (0, import_i18n38.sprintf)(
                  // translators: 1: Current page number, 2: Total number of pages.
                  (0, import_i18n38._x)("<div>Page</div>%1$s<div>of %2$d</div>", "paging"),
                  "<CurrentPage />",
                  totalPages
                ),
                {
                  div: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)("div", { "aria-hidden": true }),
                  // @ts-expect-error — Tag injected via sprintf argument, not visible in format string.
                  CurrentPage: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                    import_components31.SelectControl,
                    {
                      "aria-label": (0, import_i18n38.__)("Current page"),
                      value: currentPage.toString(),
                      options: pageSelectOptions,
                      onChange: (newValue) => {
                        onChangeView({
                          ...view,
                          page: +newValue
                        });
                      },
                      size: "small",
                      variant: "minimal"
                    }
                  )
                }
              )
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(Stack, { direction: "row", gap: "xs", align: "center", children: [
            /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
              import_components31.Button,
              {
                onClick: () => onChangeView({
                  ...view,
                  page: currentPage - 1
                }),
                disabled: currentPage === 1,
                accessibleWhenDisabled: true,
                label: (0, import_i18n38.__)("Previous page"),
                icon: (0, import_i18n38.isRTL)() ? next_default : previous_default,
                showTooltip: true,
                size: "compact",
                tooltipPosition: "top"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
              import_components31.Button,
              {
                onClick: () => onChangeView({ ...view, page: currentPage + 1 }),
                disabled: currentPage >= totalPages,
                accessibleWhenDisabled: true,
                label: (0, import_i18n38.__)("Next page"),
                icon: (0, import_i18n38.isRTL)() ? previous_default : next_default,
                showTooltip: true,
                size: "compact",
                tooltipPosition: "top"
              }
            )
          ] })
        ]
      }
    );
  }
  var dataviews_pagination_default = (0, import_element74.memo)(DataViewsPagination);

  // packages/dataviews/build-module/components/dataviews-picker-footer/index.mjs
  var import_jsx_runtime141 = __toESM(require_jsx_runtime(), 1);
  function useIsMultiselectPicker(actions) {
    return (0, import_element75.useMemo)(() => {
      return !!actions?.length && actions?.every((action) => action.supportsBulk);
    }, [actions]);
  }

  // packages/dataviews/build-module/components/dataviews-layouts/picker-grid/index.mjs
  var import_jsx_runtime142 = __toESM(require_jsx_runtime(), 1);
  var { Badge: WCBadge2 } = unlock4(import_components33.privateApis);
  function GridItem3({
    view,
    multiselect,
    selection,
    onChangeSelection,
    getItemId: getItemId2,
    item,
    mediaField,
    titleField,
    descriptionField: descriptionField2,
    regularFields,
    badgeFields,
    config: config2,
    posinset,
    setsize
  }) {
    const { showTitle = true, showMedia = true, showDescription = true } = view;
    const id = getItemId2(item);
    const elementRef = (0, import_element76.useRef)(null);
    const isSelected2 = selection.includes(id);
    useIntersectionObserver(elementRef, posinset);
    const renderedMediaField = mediaField?.render ? /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
      mediaField.render,
      {
        item,
        field: mediaField,
        config: config2
      }
    ) : null;
    const renderedTitleField = showTitle && titleField?.render ? /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(titleField.render, { item, field: titleField }) : null;
    return /* @__PURE__ */ (0, import_jsx_runtime142.jsxs)(
      import_components33.Composite.Item,
      {
        ref: elementRef,
        "aria-label": titleField ? titleField.getValue({ item }) || (0, import_i18n40.__)("(no title)") : void 0,
        render: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(Stack, { direction: "column", children, ...props }),
        role: "option",
        "aria-posinset": posinset,
        "aria-setsize": setsize,
        className: clsx_default("dataviews-view-picker-grid__card", {
          "is-selected": isSelected2
        }),
        "aria-selected": isSelected2,
        onClick: () => {
          if (isSelected2) {
            onChangeSelection(
              selection.filter((itemId) => id !== itemId)
            );
          } else {
            const newSelection = multiselect ? [...selection, id] : [id];
            onChangeSelection(newSelection);
          }
        },
        children: [
          showMedia && renderedMediaField && /* @__PURE__ */ (0, import_jsx_runtime142.jsx)("div", { className: "dataviews-view-picker-grid__media", children: renderedMediaField }),
          showMedia && renderedMediaField && /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
            DataViewsSelectionCheckbox,
            {
              item,
              selection,
              onChangeSelection,
              getItemId: getItemId2,
              titleField,
              disabled: false,
              "aria-hidden": true,
              tabIndex: -1
            }
          ),
          showTitle && /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
            Stack,
            {
              direction: "row",
              justify: "space-between",
              className: "dataviews-view-picker-grid__title-actions",
              children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)("div", { className: "dataviews-view-picker-grid__title-field dataviews-title-field", children: renderedTitleField })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime142.jsxs)(Stack, { direction: "column", gap: "xs", children: [
            showDescription && descriptionField2?.render && /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
              descriptionField2.render,
              {
                item,
                field: descriptionField2
              }
            ),
            !!badgeFields?.length && /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
              Stack,
              {
                direction: "row",
                className: "dataviews-view-picker-grid__badge-fields",
                gap: "sm",
                wrap: "wrap",
                align: "top",
                justify: "flex-start",
                children: badgeFields.map((field) => {
                  return /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                    WCBadge2,
                    {
                      className: "dataviews-view-picker-grid__field-value",
                      children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                        field.render,
                        {
                          item,
                          field
                        }
                      )
                    },
                    field.id
                  );
                })
              }
            ),
            !!regularFields?.length && /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
              Stack,
              {
                direction: "column",
                className: "dataviews-view-picker-grid__fields",
                gap: "xs",
                children: regularFields.map((field) => {
                  return /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                    import_components33.Flex,
                    {
                      className: "dataviews-view-picker-grid__field",
                      gap: 1,
                      justify: "flex-start",
                      expanded: true,
                      style: { height: "auto" },
                      direction: "row",
                      children: /* @__PURE__ */ (0, import_jsx_runtime142.jsxs)(import_jsx_runtime142.Fragment, { children: [
                        /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(import_components33.FlexItem, { className: "dataviews-view-picker-grid__field-name", children: field.header }),
                        /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                          import_components33.FlexItem,
                          {
                            className: "dataviews-view-picker-grid__field-value",
                            style: { maxHeight: "none" },
                            children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                              field.render,
                              {
                                item,
                                field
                              }
                            )
                          }
                        )
                      ] })
                    },
                    field.id
                  );
                })
              }
            )
          ] })
        ]
      },
      id
    );
  }
  function GridGroup({
    groupName,
    groupField,
    showLabel = true,
    children
  }) {
    const headerId = (0, import_compose10.useInstanceId)(
      GridGroup,
      "dataviews-view-picker-grid-group__header"
    );
    return /* @__PURE__ */ (0, import_jsx_runtime142.jsxs)(
      Stack,
      {
        direction: "column",
        gap: "sm",
        role: "group",
        "aria-labelledby": headerId,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
            "h3",
            {
              className: "dataviews-view-picker-grid-group__header",
              id: headerId,
              children: showLabel ? (0, import_i18n40.sprintf)(
                // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                (0, import_i18n40.__)("%1$s: %2$s"),
                groupField.label,
                groupName
              ) : groupName
            }
          ),
          children
        ]
      },
      groupName
    );
  }
  function ViewPickerGrid({
    actions,
    data,
    fields: fields2,
    getItemId: getItemId2,
    isLoading,
    onChangeSelection,
    selection,
    view,
    className,
    empty
  }) {
    const { resizeObserverRef, paginationInfo, itemListLabel } = (0, import_element76.useContext)(dataviews_context_default);
    const titleField = fields2.find(
      (field) => field.id === view?.titleField
    );
    const mediaField = fields2.find(
      (field) => field.id === view?.mediaField
    );
    const descriptionField2 = fields2.find(
      (field) => field.id === view?.descriptionField
    );
    const otherFields = view.fields ?? [];
    const { regularFields, badgeFields } = otherFields.reduce(
      (accumulator, fieldId) => {
        const field = fields2.find((f2) => f2.id === fieldId);
        if (!field) {
          return accumulator;
        }
        const key = view.layout?.badgeFields?.includes(fieldId) ? "badgeFields" : "regularFields";
        accumulator[key].push(field);
        return accumulator;
      },
      { regularFields: [], badgeFields: [] }
    );
    const hasData = !!data?.length;
    const usedPreviewSize = view.layout?.previewSize;
    const isMultiselect = useIsMultiselectPicker(actions);
    const size4 = "900px";
    const groupField = view.groupBy?.field ? fields2.find((f2) => f2.id === view.groupBy?.field) : null;
    const dataByGroup = groupField ? getDataByGroup(data, groupField) : null;
    const isInfiniteScroll = (view.infiniteScrollEnabled && !dataByGroup) ?? false;
    const currentPage = view?.page ?? 1;
    const perPage = view?.perPage ?? 0;
    const setSize = isInfiniteScroll ? paginationInfo?.totalItems : void 0;
    const gridColumns = useGridColumns();
    const placeholdersNeeded = usePlaceholdersNeeded(
      data,
      isInfiniteScroll,
      gridColumns
    );
    return /* @__PURE__ */ (0, import_jsx_runtime142.jsxs)(import_jsx_runtime142.Fragment, {
      // Render multiple groups.
      children: [
        hasData && groupField && dataByGroup && /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
          import_components33.Composite,
          {
            virtualFocus: true,
            orientation: "horizontal",
            role: "listbox",
            "aria-multiselectable": isMultiselect,
            className: clsx_default(
              "dataviews-view-picker-grid",
              className,
              {
                [`has-${view.layout?.density}-density`]: view.layout?.density && ["compact", "comfortable"].includes(
                  view.layout.density
                )
              }
            ),
            "aria-label": itemListLabel,
            render: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
              Stack,
              {
                direction: "column",
                gap: "lg",
                children,
                ...props
              }
            ),
            children: Array.from(dataByGroup.entries()).map(
              ([groupName, groupItems]) => /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                GridGroup,
                {
                  groupName,
                  groupField,
                  showLabel: view.groupBy?.showLabel !== false,
                  children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                    GridItems,
                    {
                      previewSize: usedPreviewSize,
                      style: {
                        gridTemplateColumns: usedPreviewSize && `repeat(auto-fill, minmax(${usedPreviewSize}px, 1fr))`
                      },
                      "aria-busy": isLoading,
                      ref: resizeObserverRef,
                      children: groupItems.map((item) => {
                        const posInSet = item.position ?? (currentPage - 1) * perPage + data.indexOf(item) + 1;
                        return /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                          GridItem3,
                          {
                            view,
                            multiselect: isMultiselect,
                            selection,
                            onChangeSelection,
                            getItemId: getItemId2,
                            item,
                            mediaField,
                            titleField,
                            descriptionField: descriptionField2,
                            regularFields,
                            badgeFields,
                            config: {
                              sizes: size4
                            },
                            posinset: posInSet,
                            setsize: setSize
                          },
                          getItemId2(item)
                        );
                      })
                    }
                  )
                },
                groupName
              )
            )
          }
        ),
        // Render a single grid with all data.
        hasData && !dataByGroup && /* @__PURE__ */ (0, import_jsx_runtime142.jsxs)(
          import_components33.Composite,
          {
            render: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
              GridItems,
              {
                className: clsx_default(
                  "dataviews-view-picker-grid",
                  className,
                  {
                    [`has-${view.layout?.density}-density`]: view.layout?.density && [
                      "compact",
                      "comfortable"
                    ].includes(view.layout.density)
                  }
                ),
                previewSize: usedPreviewSize,
                "aria-busy": isLoading,
                ref: resizeObserverRef
              }
            ),
            virtualFocus: true,
            orientation: "horizontal",
            role: "listbox",
            "aria-multiselectable": isMultiselect,
            "aria-label": itemListLabel,
            children: [
              Array.from({ length: placeholdersNeeded }).map(
                (_, index2) => /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                  import_components33.Composite.Item,
                  {
                    render: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                      Stack,
                      {
                        direction: "column",
                        children,
                        ...props
                      }
                    ),
                    role: "option",
                    "aria-hidden": true,
                    tabIndex: -1,
                    className: "dataviews-view-picker-grid__card dataviews-view-picker-grid__placeholder"
                  },
                  `placeholder-${index2}`
                )
              ),
              data.map((item) => {
                const posinset = item.position;
                return /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
                  GridItem3,
                  {
                    view,
                    multiselect: isMultiselect,
                    selection,
                    onChangeSelection,
                    getItemId: getItemId2,
                    item,
                    mediaField,
                    titleField,
                    descriptionField: descriptionField2,
                    regularFields,
                    badgeFields,
                    config: {
                      sizes: size4
                    },
                    posinset,
                    setsize: setSize
                  },
                  getItemId2(item)
                );
              })
            ]
          }
        ),
        // Render empty state.
        !hasData && /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
          "div",
          {
            className: clsx_default({
              "dataviews-loading": isLoading,
              "dataviews-no-results": !isLoading
            }),
            children: isLoading ? /* @__PURE__ */ (0, import_jsx_runtime142.jsx)("p", { children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(import_components33.Spinner, {}) }) : empty
          }
        ),
        hasData && isLoading && /* @__PURE__ */ (0, import_jsx_runtime142.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(import_components33.Spinner, {}) })
      ]
    });
  }
  var picker_grid_default = ViewPickerGrid;

  // packages/dataviews/build-module/components/dataviews-layouts/picker-table/index.mjs
  var import_i18n41 = __toESM(require_i18n(), 1);
  var import_components34 = __toESM(require_components(), 1);
  var import_element77 = __toESM(require_element(), 1);
  var import_jsx_runtime143 = __toESM(require_jsx_runtime(), 1);
  function TableColumnField2({
    item,
    fields: fields2,
    column,
    align
  }) {
    const field = fields2.find((f2) => f2.id === column);
    if (!field) {
      return null;
    }
    const className = clsx_default("dataviews-view-table__cell-content-wrapper", {
      "dataviews-view-table__cell-align-end": align === "end",
      "dataviews-view-table__cell-align-center": align === "center"
    });
    return /* @__PURE__ */ (0, import_jsx_runtime143.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(field.render, { item, field }) });
  }
  function TableRow2({
    item,
    fields: fields2,
    id,
    view,
    titleField,
    mediaField,
    descriptionField: descriptionField2,
    selection,
    getItemId: getItemId2,
    onChangeSelection,
    multiselect,
    posinset
  }) {
    const { paginationInfo } = (0, import_element77.useContext)(dataviews_context_default);
    const isSelected2 = selection.includes(id);
    const [isHovered, setIsHovered] = (0, import_element77.useState)(false);
    const elementRef = (0, import_element77.useRef)(null);
    useIntersectionObserver(elementRef, posinset);
    const {
      showTitle = true,
      showMedia = true,
      showDescription = true,
      infiniteScrollEnabled
    } = view;
    const handleMouseEnter = () => {
      setIsHovered(true);
    };
    const handleMouseLeave = () => {
      setIsHovered(false);
    };
    const columns = view.fields ?? [];
    const hasPrimaryColumn = titleField && showTitle || mediaField && showMedia || descriptionField2 && showDescription;
    return /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)(
      import_components34.Composite.Item,
      {
        ref: elementRef,
        render: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
          "tr",
          {
            className: clsx_default("dataviews-view-table__row", {
              "is-selected": isSelected2,
              "is-hovered": isHovered
            }),
            onMouseEnter: handleMouseEnter,
            onMouseLeave: handleMouseLeave,
            children,
            ...props
          }
        ),
        "aria-selected": isSelected2,
        "aria-setsize": paginationInfo.totalItems || void 0,
        "aria-posinset": posinset,
        role: infiniteScrollEnabled ? "article" : "option",
        onMouseDown: (event) => {
          if (event.button !== 0) {
            return;
          }
          event.currentTarget.parentElement?.focus({
            preventScroll: true
          });
        },
        onClick: () => {
          if (isSelected2) {
            onChangeSelection(
              selection.filter((itemId) => id !== itemId)
            );
          } else {
            const newSelection = multiselect ? [...selection, id] : [id];
            onChangeSelection(newSelection);
          }
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
            "td",
            {
              className: "dataviews-view-table__checkbox-column",
              role: "presentation",
              children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)("div", { className: "dataviews-view-table__cell-content-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                DataViewsSelectionCheckbox,
                {
                  item,
                  selection,
                  onChangeSelection,
                  getItemId: getItemId2,
                  titleField,
                  disabled: false,
                  "aria-hidden": true,
                  tabIndex: -1
                }
              ) })
            }
          ),
          hasPrimaryColumn && /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
            "td",
            {
              role: "presentation",
              children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                column_primary_default,
                {
                  item,
                  titleField: showTitle ? titleField : void 0,
                  mediaField: showMedia ? mediaField : void 0,
                  descriptionField: showDescription ? descriptionField2 : void 0,
                  isItemClickable: () => false
                }
              )
            }
          ),
          columns.map((column) => {
            const { width, maxWidth, minWidth, align } = view.layout?.styles?.[column] ?? {};
            return /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
              "td",
              {
                style: {
                  width,
                  maxWidth,
                  minWidth
                },
                role: "presentation",
                children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                  TableColumnField2,
                  {
                    fields: fields2,
                    item,
                    column,
                    align
                  }
                )
              },
              column
            );
          })
        ]
      },
      id
    );
  }
  function ViewPickerTable({
    actions,
    data,
    fields: fields2,
    getItemId: getItemId2,
    isLoading = false,
    onChangeView,
    onChangeSelection,
    selection,
    setOpenedFilter,
    view,
    className,
    empty
  }) {
    const headerMenuRefs = (0, import_element77.useRef)(/* @__PURE__ */ new Map());
    const headerMenuToFocusRef = (0, import_element77.useRef)(void 0);
    const [nextHeaderMenuToFocus, setNextHeaderMenuToFocus] = (0, import_element77.useState)();
    const isMultiselect = useIsMultiselectPicker(actions) ?? false;
    (0, import_element77.useEffect)(() => {
      if (headerMenuToFocusRef.current) {
        headerMenuToFocusRef.current.focus();
        headerMenuToFocusRef.current = void 0;
      }
    });
    const groupField = view.groupBy?.field ? fields2.find((f2) => f2.id === view.groupBy?.field) : null;
    const dataByGroup = groupField ? getDataByGroup(data, groupField) : null;
    const isInfiniteScroll = view.infiniteScrollEnabled && !dataByGroup;
    const tableNoticeId = (0, import_element77.useId)();
    if (nextHeaderMenuToFocus) {
      headerMenuToFocusRef.current = nextHeaderMenuToFocus;
      setNextHeaderMenuToFocus(void 0);
      return;
    }
    const onHide = (field) => {
      const hidden = headerMenuRefs.current.get(field.id);
      const fallback = hidden ? headerMenuRefs.current.get(hidden.fallback) : void 0;
      setNextHeaderMenuToFocus(fallback?.node);
    };
    const hasData = !!data?.length;
    const titleField = fields2.find((field) => field.id === view.titleField);
    const mediaField = fields2.find((field) => field.id === view.mediaField);
    const descriptionField2 = fields2.find(
      (field) => field.id === view.descriptionField
    );
    const { showTitle = true, showMedia = true, showDescription = true } = view;
    const hasPrimaryColumn = titleField && showTitle || mediaField && showMedia || descriptionField2 && showDescription;
    const columns = view.fields ?? [];
    const headerMenuRef = (column, index2) => (node) => {
      if (node) {
        headerMenuRefs.current.set(column, {
          node,
          fallback: columns[index2 > 0 ? index2 - 1 : 1]
        });
      } else {
        headerMenuRefs.current.delete(column);
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)(import_jsx_runtime143.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)(
        "table",
        {
          className: clsx_default(
            "dataviews-view-table",
            "dataviews-view-picker-table",
            className,
            {
              [`has-${view.layout?.density}-density`]: view.layout?.density && ["compact", "comfortable"].includes(
                view.layout.density
              )
            }
          ),
          "aria-busy": isLoading,
          "aria-describedby": tableNoticeId,
          role: isInfiniteScroll ? "feed" : "listbox",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime143.jsx)("thead", { role: "presentation", children: /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)(
              "tr",
              {
                className: "dataviews-view-table__row",
                role: "presentation",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime143.jsx)("th", { className: "dataviews-view-table__checkbox-column", children: isMultiselect && /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                    BulkSelectionCheckbox,
                    {
                      selection,
                      onChangeSelection,
                      data,
                      actions,
                      getItemId: getItemId2,
                      disableSelectAll: isInfiniteScroll
                    }
                  ) }),
                  hasPrimaryColumn && /* @__PURE__ */ (0, import_jsx_runtime143.jsx)("th", { children: titleField && /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                    column_header_menu_default,
                    {
                      ref: headerMenuRef(
                        titleField.id,
                        0
                      ),
                      fieldId: titleField.id,
                      view,
                      fields: fields2,
                      onChangeView,
                      onHide,
                      setOpenedFilter,
                      canMove: false
                    }
                  ) }),
                  columns.map((column, index2) => {
                    const { width, maxWidth, minWidth, align } = view.layout?.styles?.[column] ?? {};
                    return /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                      "th",
                      {
                        style: {
                          width,
                          maxWidth,
                          minWidth,
                          textAlign: align
                        },
                        "aria-sort": view.sort?.direction && view.sort?.field === column ? sortValues[view.sort.direction] : void 0,
                        scope: "col",
                        children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                          column_header_menu_default,
                          {
                            ref: headerMenuRef(column, index2),
                            fieldId: column,
                            view,
                            fields: fields2,
                            onChangeView,
                            onHide,
                            setOpenedFilter,
                            canMove: view.layout?.enableMoving ?? true
                          }
                        )
                      },
                      column
                    );
                  })
                ]
              }
            ) }),
            hasData && groupField && dataByGroup ? Array.from(dataByGroup.entries()).map(
              ([groupName, groupItems]) => /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)(
                import_components34.Composite,
                {
                  virtualFocus: true,
                  orientation: "vertical",
                  render: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)("tbody", { role: "group" }),
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                      "tr",
                      {
                        className: "dataviews-view-table__group-header-row",
                        role: "presentation",
                        children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                          "td",
                          {
                            colSpan: columns.length + (hasPrimaryColumn ? 1 : 0) + 1,
                            className: "dataviews-view-table__group-header-cell",
                            role: "presentation",
                            children: view.groupBy?.showLabel === false ? groupName : (0, import_i18n41.sprintf)(
                              // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                              (0, import_i18n41.__)("%1$s: %2$s"),
                              groupField.label,
                              groupName
                            )
                          }
                        )
                      }
                    ),
                    groupItems.map((item, index2) => /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                      TableRow2,
                      {
                        item,
                        fields: fields2,
                        id: getItemId2(item) || index2.toString(),
                        view,
                        titleField,
                        mediaField,
                        descriptionField: descriptionField2,
                        selection,
                        getItemId: getItemId2,
                        onChangeSelection,
                        multiselect: isMultiselect
                      },
                      getItemId2(item)
                    ))
                  ]
                },
                `group-${groupName}`
              )
            ) : /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
              import_components34.Composite,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)("tbody", { role: "presentation" }),
                virtualFocus: true,
                orientation: "vertical",
                children: hasData && data.map((item, index2) => {
                  const itemId = getItemId2(item);
                  const posinset = item.position;
                  return /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
                    TableRow2,
                    {
                      item,
                      fields: fields2,
                      id: itemId || index2.toString(),
                      view,
                      titleField,
                      mediaField,
                      descriptionField: descriptionField2,
                      selection,
                      getItemId: getItemId2,
                      onChangeSelection,
                      multiselect: isMultiselect,
                      posinset
                    },
                    itemId
                  );
                })
              }
            )
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)(
        "div",
        {
          className: clsx_default({
            "dataviews-loading": isLoading,
            "dataviews-no-results": !hasData && !isLoading
          }),
          id: tableNoticeId,
          children: [
            !hasData && (isLoading ? /* @__PURE__ */ (0, import_jsx_runtime143.jsx)("p", { children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(import_components34.Spinner, {}) }) : empty),
            hasData && isLoading && /* @__PURE__ */ (0, import_jsx_runtime143.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(import_components34.Spinner, {}) })
          ]
        }
      )
    ] });
  }
  var picker_table_default = ViewPickerTable;

  // packages/dataviews/build-module/components/dataviews-layouts/picker-activity/index.mjs
  var import_components35 = __toESM(require_components(), 1);
  var import_element78 = __toESM(require_element(), 1);
  var import_compose11 = __toESM(require_compose(), 1);
  var import_i18n42 = __toESM(require_i18n(), 1);
  var import_jsx_runtime144 = __toESM(require_jsx_runtime(), 1);
  function isDefined4(item) {
    return !!item;
  }
  function PickerActivityItem({
    view,
    multiselect,
    selection,
    onChangeSelection,
    getItemId: getItemId2,
    item,
    titleField,
    mediaField,
    descriptionField: descriptionField2,
    otherFields,
    posinset,
    setsize
  }) {
    const elementRef = (0, import_element78.useRef)(null);
    useIntersectionObserver(elementRef, posinset);
    const { showTitle = true, showMedia = true, showDescription = true } = view;
    const id = getItemId2(item);
    const isSelected2 = selection.includes(id);
    const density = view.layout?.density ?? "balanced";
    const mediaContent = showMedia && density !== "compact" && mediaField?.render ? /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
      mediaField.render,
      {
        item,
        field: mediaField,
        config: {
          sizes: density === "comfortable" ? "32px" : "24px"
        }
      }
    ) : null;
    const renderedMediaField = /* @__PURE__ */ (0, import_jsx_runtime144.jsx)("div", { className: "dataviews-view-picker-activity__item-type-icon", children: mediaContent || /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
      "span",
      {
        className: "dataviews-view-picker-activity__item-bullet",
        "aria-hidden": "true"
      }
    ) });
    const renderedTitleField = showTitle && titleField?.render ? /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(titleField.render, { item, field: titleField }) : null;
    const renderedDescriptionField = showDescription && descriptionField2?.render ? /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(descriptionField2.render, { item, field: descriptionField2 }) : null;
    const verticalGap = (0, import_element78.useMemo)(() => {
      switch (density) {
        case "comfortable":
          return "md";
        default:
          return "sm";
      }
    }, [density]);
    return /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
      import_components35.Composite.Item,
      {
        ref: elementRef,
        role: "option",
        "aria-label": titleField ? titleField.getValue({ item }) || void 0 : void 0,
        "aria-posinset": posinset,
        "aria-setsize": setsize,
        "aria-selected": isSelected2,
        className: clsx_default(
          "dataviews-view-picker-activity__item",
          density === "compact" && "is-compact",
          density === "balanced" && "is-balanced",
          density === "comfortable" && "is-comfortable",
          isSelected2 && "is-selected"
        ),
        onClick: () => {
          if (isSelected2) {
            onChangeSelection(
              selection.filter((itemId) => id !== itemId)
            );
          } else {
            const newSelection = multiselect ? [...selection, id] : [id];
            onChangeSelection(newSelection);
          }
        },
        render: /* @__PURE__ */ (0, import_jsx_runtime144.jsx)("div", {}),
        children: /* @__PURE__ */ (0, import_jsx_runtime144.jsxs)(Stack, { direction: "row", gap: "lg", justify: "start", align: "flex-start", children: [
          /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
            Stack,
            {
              direction: "column",
              gap: "xs",
              align: "center",
              className: "dataviews-view-picker-activity__item-type",
              children: renderedMediaField
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime144.jsxs)(
            Stack,
            {
              direction: "column",
              gap: verticalGap,
              align: "flex-start",
              className: "dataviews-view-picker-activity__item-content",
              children: [
                renderedTitleField && /* @__PURE__ */ (0, import_jsx_runtime144.jsx)("div", { className: "dataviews-view-picker-activity__item-title", children: renderedTitleField }),
                renderedDescriptionField && /* @__PURE__ */ (0, import_jsx_runtime144.jsx)("div", { className: "dataviews-view-picker-activity__item-description", children: renderedDescriptionField }),
                /* @__PURE__ */ (0, import_jsx_runtime144.jsx)("div", { className: "dataviews-view-picker-activity__item-fields", children: otherFields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime144.jsxs)(
                  "div",
                  {
                    className: "dataviews-view-picker-activity__item-field",
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
                        VisuallyHidden,
                        {
                          render: /* @__PURE__ */ (0, import_jsx_runtime144.jsx)("span", {}),
                          className: "dataviews-view-picker-activity__item-field-label",
                          children: field.label
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime144.jsx)("span", { className: "dataviews-view-picker-activity__item-field-value", children: /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
                        field.render,
                        {
                          item,
                          field
                        }
                      ) })
                    ]
                  },
                  field.id
                )) })
              ]
            }
          )
        ] })
      }
    );
  }
  function PickerActivityGroup({
    groupName,
    groupField,
    showLabel = true,
    children
  }) {
    const headerId = (0, import_compose11.useInstanceId)(
      PickerActivityGroup,
      "dataviews-view-picker-activity-group__header"
    );
    return /* @__PURE__ */ (0, import_jsx_runtime144.jsxs)(
      Stack,
      {
        direction: "column",
        role: "group",
        "aria-labelledby": headerId,
        className: "dataviews-view-picker-activity-group",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
            "h3",
            {
              className: "dataviews-view-picker-activity-group__header",
              id: headerId,
              children: showLabel ? (0, import_i18n42.sprintf)(
                // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                (0, import_i18n42.__)("%1$s: %2$s"),
                groupField.label,
                groupName
              ) : groupName
            }
          ),
          children
        ]
      }
    );
  }
  function ViewPickerActivity({
    data,
    fields: fields2,
    getItemId: getItemId2,
    isLoading,
    onChangeSelection,
    selection,
    view,
    actions,
    className,
    empty
  }) {
    const { itemListLabel, paginationInfo } = (0, import_element78.useContext)(dataviews_context_default);
    const isMultiselect = useIsMultiselectPicker(actions);
    const titleField = fields2.find(
      (field) => field.id === view?.titleField
    );
    const mediaField = fields2.find(
      (field) => field.id === view?.mediaField
    );
    const descriptionField2 = fields2.find(
      (field) => field.id === view?.descriptionField
    );
    const otherFields = (view?.fields ?? []).map((fieldId) => fields2.find((f2) => fieldId === f2.id)).filter(isDefined4);
    const groupField = view.groupBy?.field ? fields2.find((f2) => f2.id === view.groupBy?.field) : null;
    const dataByGroup = groupField ? getDataByGroup(data, groupField) : null;
    const isInfiniteScroll = (view.infiniteScrollEnabled && !dataByGroup) ?? false;
    const setsize = isInfiniteScroll ? paginationInfo?.totalItems : void 0;
    const hasData = !!data?.length;
    const isGrouped = !!(groupField && dataByGroup);
    const renderItem = (item) => /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
      PickerActivityItem,
      {
        view,
        multiselect: isMultiselect,
        selection,
        onChangeSelection,
        getItemId: getItemId2,
        item,
        titleField,
        mediaField,
        descriptionField: descriptionField2,
        otherFields,
        posinset: item.position,
        setsize
      },
      getItemId2(item)
    );
    if (!hasData) {
      return /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
        "div",
        {
          className: clsx_default({
            "dataviews-loading": isLoading,
            "dataviews-no-results": !isLoading
          }),
          children: isLoading ? /* @__PURE__ */ (0, import_jsx_runtime144.jsx)("p", { children: /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(import_components35.Spinner, {}) }) : empty
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime144.jsxs)(import_jsx_runtime144.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
        import_components35.Composite,
        {
          virtualFocus: true,
          orientation: "vertical",
          role: "listbox",
          "aria-multiselectable": isMultiselect,
          "aria-label": itemListLabel,
          "aria-busy": isLoading,
          render: isGrouped ? /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(Stack, { direction: "column", gap: "sm" }) : void 0,
          className: clsx_default(
            "dataviews-view-picker-activity",
            className
          ),
          children: isGrouped && dataByGroup ? Array.from(dataByGroup.entries()).map(
            ([groupName, groupItems]) => /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
              PickerActivityGroup,
              {
                groupName,
                groupField,
                showLabel: view.groupBy?.showLabel !== false,
                children: groupItems.map(renderItem)
              },
              groupName
            )
          ) : data.map(renderItem)
        }
      ),
      isLoading && /* @__PURE__ */ (0, import_jsx_runtime144.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(import_components35.Spinner, {}) })
    ] });
  }

  // packages/dataviews/build-module/components/dataviews-layouts/utils/density-picker.mjs
  var import_components36 = __toESM(require_components(), 1);
  var import_i18n43 = __toESM(require_i18n(), 1);
  var import_element79 = __toESM(require_element(), 1);
  var import_jsx_runtime145 = __toESM(require_jsx_runtime(), 1);
  function DensityPicker() {
    const context = (0, import_element79.useContext)(dataviews_context_default);
    const view = context.view;
    return /* @__PURE__ */ (0, import_jsx_runtime145.jsxs)(
      import_components36.__experimentalToggleGroupControl,
      {
        label: (0, import_i18n43.__)("Density"),
        value: view.layout?.density || "balanced",
        onChange: (value) => {
          context.onChangeView({
            ...view,
            layout: {
              ...view.layout,
              density: value
            }
          });
        },
        isBlock: true,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime145.jsx)(
            import_components36.__experimentalToggleGroupControlOption,
            {
              value: "comfortable",
              label: (0, import_i18n43._x)(
                "Comfortable",
                "Density option for DataView layout"
              )
            },
            "comfortable"
          ),
          /* @__PURE__ */ (0, import_jsx_runtime145.jsx)(
            import_components36.__experimentalToggleGroupControlOption,
            {
              value: "balanced",
              label: (0, import_i18n43._x)("Balanced", "Density option for DataView layout")
            },
            "balanced"
          ),
          /* @__PURE__ */ (0, import_jsx_runtime145.jsx)(
            import_components36.__experimentalToggleGroupControlOption,
            {
              value: "compact",
              label: (0, import_i18n43._x)("Compact", "Density option for DataView layout")
            },
            "compact"
          )
        ]
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-layouts/utils/preview-size-picker.mjs
  var import_components37 = __toESM(require_components(), 1);
  var import_i18n44 = __toESM(require_i18n(), 1);
  var import_element80 = __toESM(require_element(), 1);
  var import_jsx_runtime146 = __toESM(require_jsx_runtime(), 1);
  var imageSizes2 = [
    {
      value: 120,
      breakpoint: 1
    },
    {
      value: 170,
      breakpoint: 1
    },
    {
      value: 230,
      breakpoint: 1
    },
    {
      value: 290,
      breakpoint: 1112
      // at minimum image width, 4 images display at this container size
    },
    {
      value: 350,
      breakpoint: 1636
      // at minimum image width, 6 images display at this container size
    },
    {
      value: 430,
      breakpoint: 588
      // at minimum image width, 2 images display at this container size
    }
  ];
  function PreviewSizePicker() {
    const context = (0, import_element80.useContext)(dataviews_context_default);
    const view = context.view;
    const breakValues = imageSizes2.filter((size4) => {
      return context.containerWidth >= size4.breakpoint;
    });
    const layoutPreviewSize = view.layout?.previewSize ?? 230;
    const previewSizeToUse = breakValues.map((size4, index2) => ({ ...size4, index: index2 })).filter((size4) => size4.value <= layoutPreviewSize).sort((a2, b2) => b2.value - a2.value)[0]?.index ?? 0;
    const marks = breakValues.map((size4, index2) => {
      return {
        value: index2
      };
    });
    return /* @__PURE__ */ (0, import_jsx_runtime146.jsx)(
      import_components37.RangeControl,
      {
        showTooltip: false,
        label: (0, import_i18n44.__)("Preview size"),
        value: previewSizeToUse,
        min: 0,
        max: breakValues.length - 1,
        withInputField: false,
        onChange: (value = 0) => {
          context.onChangeView({
            ...view,
            layout: {
              ...view.layout,
              previewSize: breakValues[value].value
            }
          });
        },
        step: 1,
        marks
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-layouts/utils/grid-config-options.mjs
  var import_jsx_runtime147 = __toESM(require_jsx_runtime(), 1);
  function GridConfigOptions() {
    return /* @__PURE__ */ (0, import_jsx_runtime147.jsxs)(import_jsx_runtime147.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(DensityPicker, {}),
      /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(PreviewSizePicker, {})
    ] });
  }

  // packages/dataviews/build-module/components/dataviews-layouts/index.mjs
  var VIEW_LAYOUTS = [
    {
      type: LAYOUT_TABLE,
      label: (0, import_i18n45.__)("Table"),
      component: table_default,
      icon: block_table_default,
      viewConfigOptions: DensityPicker
    },
    {
      type: LAYOUT_GRID,
      label: (0, import_i18n45.__)("Grid"),
      component: grid_default,
      icon: category_default,
      viewConfigOptions: GridConfigOptions
    },
    {
      type: LAYOUT_LIST2,
      label: (0, import_i18n45.__)("List"),
      component: ViewList,
      icon: (0, import_i18n45.isRTL)() ? format_list_bullets_rtl_default : format_list_bullets_default,
      viewConfigOptions: DensityPicker
    },
    {
      type: LAYOUT_ACTIVITY,
      label: (0, import_i18n45.__)("Activity"),
      component: ViewActivity,
      icon: scheduled_default,
      viewConfigOptions: DensityPicker
    },
    {
      type: LAYOUT_PICKER_GRID,
      label: (0, import_i18n45.__)("Grid"),
      component: picker_grid_default,
      icon: category_default,
      viewConfigOptions: GridConfigOptions,
      isPicker: true
    },
    {
      type: LAYOUT_PICKER_TABLE,
      label: (0, import_i18n45.__)("Table"),
      component: picker_table_default,
      icon: block_table_default,
      viewConfigOptions: DensityPicker,
      isPicker: true
    },
    {
      type: LAYOUT_PICKER_ACTIVITY,
      label: (0, import_i18n45.__)("Activity"),
      component: ViewPickerActivity,
      icon: scheduled_default,
      viewConfigOptions: DensityPicker,
      isPicker: true
    }
  ];

  // packages/dataviews/build-module/components/dataviews-filters/filters.mjs
  var import_element88 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataviews-filters/filter.mjs
  var import_components40 = __toESM(require_components(), 1);
  var import_i18n48 = __toESM(require_i18n(), 1);
  var import_element85 = __toESM(require_element(), 1);

  // node_modules/@ariakit/react-components/dist/focusable/focusable-context.js
  var import_react16 = __toESM(require_react(), 1);
  var FocusableContext = (0, import_react16.createContext)(true);

  // node_modules/@ariakit/utils/dist/index.js
  function toArray2(arg) {
    if (Array.isArray(arg)) return arg;
    return typeof arg !== "undefined" ? [arg] : [];
  }
  function flatten2DArray(array) {
    const flattened = [];
    for (const row of array) flattened.push(...row);
    return flattened;
  }
  function reverseArray(array) {
    return array.slice().reverse();
  }
  function noop5(..._) {
  }
  function hasOwnProperty(object, prop) {
    if (typeof Object.hasOwn === "function") return Object.hasOwn(object, prop);
    return Object.prototype.hasOwnProperty.call(object, prop);
  }
  function chain(...fns) {
    return (...args) => {
      for (const fn of fns) if (typeof fn === "function") fn(...args);
    };
  }
  function normalizeString(str) {
    return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
  }
  function omit(object, keys) {
    const result = { ...object };
    for (const key of keys) if (hasOwnProperty(result, key)) delete result[key];
    return result;
  }
  function pick(object, paths) {
    const result = {};
    for (const key of paths) if (hasOwnProperty(object, key)) result[key] = object[key];
    return result;
  }
  function identity(value) {
    return value;
  }
  function afterPaint(cb = noop5) {
    let raf2 = requestAnimationFrame(() => {
      raf2 = requestAnimationFrame(cb);
    });
    return () => cancelAnimationFrame(raf2);
  }
  function invariant(condition, message2) {
    if (condition) return;
    if (typeof message2 !== "string") throw new Error("Invariant failed");
    throw new Error(message2);
  }
  function getKeys(obj) {
    return Object.keys(obj);
  }
  function isFalsyBooleanCallback(booleanOrCallback, ...args) {
    const result = typeof booleanOrCallback === "function" ? booleanOrCallback(...args) : booleanOrCallback;
    if (result == null) return false;
    return !result;
  }
  function disabledFromProps(props) {
    return props.disabled || props["aria-disabled"] === true || props["aria-disabled"] === "true";
  }
  function removeUndefinedValues(obj) {
    const result = {};
    for (const key in obj) if (obj[key] !== void 0) result[key] = obj[key];
    return result;
  }
  function defaultValue(...values) {
    for (const value of values) if (value !== void 0) return value;
  }
  var canUseDOM = checkIsBrowser();
  function checkIsBrowser() {
    return typeof window !== "undefined" && !!window.document?.createElement;
  }
  function getDocument(node) {
    if (!node) return document;
    if ("self" in node) return node.document;
    return node.ownerDocument || document;
  }
  function getActiveElement(node, activeDescendant = false) {
    const { activeElement: activeElement2 } = getDocument(node);
    if (!activeElement2?.nodeName) return null;
    if (isFrame(activeElement2) && activeElement2.contentDocument?.body) return getActiveElement(activeElement2.contentDocument.body, activeDescendant);
    if (activeDescendant) {
      const id = activeElement2.getAttribute("aria-activedescendant");
      if (id) {
        const element = getDocument(activeElement2).getElementById(id);
        if (element) return element;
      }
    }
    return activeElement2;
  }
  function contains2(parent, child) {
    return parent === child || parent.contains(child);
  }
  function isElement2(target) {
    return target?.nodeType === 1;
  }
  function isNode2(target) {
    return typeof target?.nodeType === "number";
  }
  function isFrame(element) {
    return element.tagName === "IFRAME";
  }
  function isButton(element) {
    const tagName = element.tagName.toLowerCase();
    if (tagName === "button") return true;
    if (tagName === "input" && element.type) return buttonInputTypes.indexOf(element.type) !== -1;
    return false;
  }
  var buttonInputTypes = [
    "button",
    "color",
    "file",
    "image",
    "reset",
    "submit"
  ];
  function isVisible(element) {
    if (typeof element.checkVisibility === "function") return element.checkVisibility();
    const htmlElement = element;
    return htmlElement.offsetWidth > 0 || htmlElement.offsetHeight > 0 || element.getClientRects().length > 0;
  }
  function isTextField(element) {
    try {
      if (element.tagName === "TEXTAREA") return true;
      if (element.tagName !== "INPUT") return false;
      return element.selectionStart !== null;
    } catch (_error) {
      return false;
    }
  }
  function isTextbox(element) {
    return element.isContentEditable || isTextField(element);
  }
  function getTextboxValue(element) {
    if (isTextField(element)) return element.value;
    if (element.isContentEditable) {
      const range = getDocument(element).createRange();
      range.selectNodeContents(element);
      return range.toString();
    }
    return "";
  }
  function getTextboxSelection(element) {
    let start2 = 0;
    let end = 0;
    if (isTextField(element)) {
      start2 = element.selectionStart || 0;
      end = element.selectionEnd || 0;
    } else if (element.isContentEditable) {
      const selection = getDocument(element).getSelection();
      if (selection?.rangeCount && selection.anchorNode && contains2(element, selection.anchorNode) && selection.focusNode && contains2(element, selection.focusNode)) {
        const range = selection.getRangeAt(0);
        const nextRange = range.cloneRange();
        nextRange.selectNodeContents(element);
        nextRange.setEnd(range.startContainer, range.startOffset);
        start2 = nextRange.toString().length;
        nextRange.setEnd(range.endContainer, range.endOffset);
        end = nextRange.toString().length;
      }
    }
    return {
      start: start2,
      end
    };
  }
  var allowedPopupRoles = [
    "dialog",
    "menu",
    "listbox",
    "tree",
    "grid"
  ];
  var itemRoleByPopupRole = {
    menu: "menuitem",
    listbox: "option",
    tree: "treeitem"
  };
  function getPopupRole(element, fallback) {
    const role = element?.getAttribute("role");
    if (role && allowedPopupRoles.indexOf(role) !== -1) return role;
    return fallback;
  }
  function getItemRoleByPopupRole(popupRole) {
    if (popupRole == null) return;
    if (!hasOwnProperty(itemRoleByPopupRole, popupRole)) return;
    return itemRoleByPopupRole[popupRole];
  }
  function getScrollingElement(element) {
    if (!element) return null;
    const isScrollableOverflow = (overflow) => {
      if (overflow === "auto") return true;
      if (overflow === "scroll") return true;
      return false;
    };
    if (element.clientHeight && element.scrollHeight > element.clientHeight) {
      const { overflowY } = getComputedStyle(element);
      if (isScrollableOverflow(overflowY)) return element;
    } else if (element.clientWidth && element.scrollWidth > element.clientWidth) {
      const { overflowX } = getComputedStyle(element);
      if (isScrollableOverflow(overflowX)) return element;
    }
    const doc = getDocument(element);
    return getScrollingElement(element.parentElement) || doc.scrollingElement || doc.body;
  }
  function setSelectionRange(element, ...args) {
    if (/text|search|password|tel|url/i.test(element.type)) element.setSelectionRange(...args);
  }
  function sortBasedOnDOMPosition(items, getElement) {
    const pairs = items.map((item, index2) => [index2, item]);
    let isOrderDifferent = false;
    pairs.sort(([indexA, a2], [indexB, b2]) => {
      const elementA = getElement(a2);
      const elementB = getElement(b2);
      if (elementA === elementB) return 0;
      if (!elementA || !elementB) return 0;
      if (isElementPreceding(elementA, elementB)) {
        if (indexA > indexB) isOrderDifferent = true;
        return -1;
      }
      if (indexA < indexB) isOrderDifferent = true;
      return 1;
    });
    if (isOrderDifferent) return pairs.map(([_, item]) => item);
    return items;
  }
  function isElementPreceding(a2, b2) {
    return Boolean(b2.compareDocumentPosition(a2) & Node.DOCUMENT_POSITION_PRECEDING);
  }
  function isTouchDevice() {
    return canUseDOM && !!navigator.maxTouchPoints;
  }
  function isApple() {
    if (!canUseDOM) return false;
    return /mac|iphone|ipad|ipod/i.test(navigator.platform);
  }
  function isSafari() {
    return canUseDOM && isApple() && /apple/i.test(navigator.vendor);
  }
  function isFirefox() {
    return canUseDOM && /firefox\//i.test(navigator.userAgent);
  }
  function isPortalEvent(event) {
    const { currentTarget, target } = event;
    if (!currentTarget) return false;
    if (!isNode2(target)) return true;
    return !contains2(currentTarget, target);
  }
  function isSelfTarget(event) {
    return event.target === event.currentTarget;
  }
  function isActivatableNavigationTarget(element) {
    if (!isElement2(element)) return false;
    const target = element;
    const tagName = target.tagName.toLowerCase();
    if (tagName === "a") return true;
    if (tagName === "button" && target.type === "submit") return true;
    if (tagName === "input" && target.type === "submit") return true;
    return false;
  }
  function isOpeningInNewTab(event) {
    const isAppleDevice = isApple();
    if (isAppleDevice && !event.metaKey) return false;
    if (!isAppleDevice && !event.ctrlKey) return false;
    return isActivatableNavigationTarget(event.currentTarget);
  }
  function isDownloading(event) {
    if (!event.altKey) return false;
    return isActivatableNavigationTarget(event.currentTarget);
  }
  function fireBlurEvent(element, eventInit) {
    const event = new FocusEvent("blur", eventInit);
    const defaultAllowed = element.dispatchEvent(event);
    const bubbleInit = {
      ...eventInit,
      bubbles: true
    };
    element.dispatchEvent(new FocusEvent("focusout", bubbleInit));
    return defaultAllowed;
  }
  function fireKeyboardEvent(element, type, eventInit) {
    const event = new KeyboardEvent(type, eventInit);
    return element.dispatchEvent(event);
  }
  function fireClickEvent(element, eventInit) {
    const event = new MouseEvent("click", eventInit);
    return element.dispatchEvent(event);
  }
  function isFocusEventOutside(event, container) {
    const containerElement = container || event.currentTarget;
    const relatedTarget = event.relatedTarget;
    return !isNode2(relatedTarget) || !contains2(containerElement, relatedTarget);
  }
  function isInputEvent(event) {
    return event.type === "input";
  }
  function queueBeforeEvent(element, type, callback, timeout) {
    const createTimer = (callback2) => {
      if (timeout) {
        const timerId2 = setTimeout(callback2, timeout);
        return () => clearTimeout(timerId2);
      }
      const timerId = requestAnimationFrame(callback2);
      return () => cancelAnimationFrame(timerId);
    };
    const cancelTimer = createTimer(() => {
      element.removeEventListener(type, callSync, true);
      callback();
    });
    const callSync = () => {
      cancelTimer();
      callback();
    };
    element.addEventListener(type, callSync, {
      once: true,
      capture: true
    });
    return () => {
      cancelTimer();
      element.removeEventListener(type, callSync, true);
    };
  }
  function addGlobalEventListener(type, listener, options, scope = window) {
    const children = [];
    try {
      scope.document.addEventListener(type, listener, options);
      for (const frame of Array.from(scope.frames)) children.push(addGlobalEventListener(type, listener, options, frame));
    } catch {
    }
    const removeEventListener = () => {
      try {
        scope.document.removeEventListener(type, listener, options);
      } catch {
      }
      for (const remove of children) remove();
    };
    return removeEventListener;
  }
  var selector = "input:not([type='hidden']):not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], button:not([disabled]), [tabindex], summary, iframe, object, embed, area[href], audio[controls], video[controls], [contenteditable]:not([contenteditable='false'])";
  function isFocusable(element) {
    if (!element.matches(selector)) return false;
    if (!isVisible(element)) return false;
    if (element.closest("[inert]")) return false;
    return true;
  }
  function hasFocus(element) {
    const activeElement2 = getActiveElement(element);
    if (!activeElement2) return false;
    if (activeElement2 === element) return true;
    const activeDescendant = activeElement2.getAttribute("aria-activedescendant");
    if (!activeDescendant) return false;
    return activeDescendant === element.id;
  }
  function hasFocusWithin(element) {
    const activeElement2 = getActiveElement(element);
    if (!activeElement2) return false;
    if (contains2(element, activeElement2)) return true;
    const activeDescendant = activeElement2.getAttribute("aria-activedescendant");
    if (!activeDescendant) return false;
    if (!("id" in element)) return false;
    if (activeDescendant === element.id) return true;
    return !!element.querySelector(`#${CSS.escape(activeDescendant)}`);
  }
  function focusIntoView(element, options) {
    if (!("scrollIntoView" in element)) element.focus();
    else {
      element.focus({ preventScroll: true });
      element.scrollIntoView({
        block: "nearest",
        inline: "nearest",
        ...options
      });
    }
  }
  function createUndoCallback(callback) {
    return async () => {
      const redo = await callback?.();
      return createUndoCallback(async () => {
        await redo?.();
        return callback;
      });
    };
  }
  var UndoManager = createUndoManager();
  function createUndoManager({ limit = 100 } = {}) {
    const undoStack = [];
    let redoStack = [];
    let currentGroup = null;
    const canUndo = () => undoStack.length > 0;
    const canRedo = () => redoStack.length > 0;
    const undo = async () => {
      if (!canUndo()) return;
      currentGroup = null;
      redoStack.push(await undoStack.pop()?.());
    };
    const redo = async () => {
      if (!canRedo()) return;
      currentGroup = null;
      undoStack.push(await redoStack.pop()?.());
    };
    const execute = async (callback, group) => {
      if (!callback) return;
      const sameGroup = group === currentGroup;
      currentGroup = group ?? null;
      const nextIndex = sameGroup ? Math.max(0, undoStack.length - 1) : undoStack.length;
      const undoCallback = await callback();
      if (!undoCallback) return;
      redoStack = [];
      const currentUndo = undoStack[nextIndex];
      undoStack[nextIndex] = createUndoCallback(async () => {
        await undoCallback?.();
        const currentRedo = await currentUndo?.();
        return async () => {
          await currentRedo?.();
          await callback?.();
        };
      });
      while (undoStack.length > limit) undoStack.shift();
    };
    return {
      canUndo,
      canRedo,
      undo,
      redo,
      execute
    };
  }

  // node_modules/@ariakit/react-utils/dist/index.js
  var React59 = __toESM(require_react(), 1);
  var import_react17 = __toESM(require_react(), 1);
  var import_jsx_runtime148 = __toESM(require_jsx_runtime(), 1);
  function setRef(ref, value) {
    if (typeof ref === "function") {
      const cleanup = ref(value);
      if (typeof cleanup === "function") return cleanup;
    } else if (ref) ref.current = value;
  }
  function isValidElementWithRef(element) {
    if (!element) return false;
    if (!(0, import_react17.isValidElement)(element)) return false;
    if ("ref" in element.props) return true;
    if ("ref" in element) return true;
    return false;
  }
  function getRefProperty(element) {
    if (!isValidElementWithRef(element)) return null;
    return { ...element.props }.ref || element.ref;
  }
  function mergeProps2(base, overrides) {
    const props = { ...base };
    for (const key in overrides) {
      if (!hasOwnProperty(overrides, key)) continue;
      if (key === "className") {
        const prop = "className";
        const baseClass = base[prop];
        const overrideClass = overrides[prop];
        if (baseClass && overrideClass) props[prop] = `${baseClass} ${overrideClass}`;
        else props[prop] = overrideClass || baseClass;
        continue;
      }
      if (key === "style") {
        const prop = "style";
        props[prop] = base[prop] ? {
          ...base[prop],
          ...overrides[prop]
        } : overrides[prop];
        continue;
      }
      const overrideValue = overrides[key];
      if (key.startsWith("on")) {
        if (typeof overrideValue !== "function") continue;
        const baseValue = base[key];
        if (typeof baseValue === "function") {
          props[key] = (...args) => {
            overrideValue(...args);
            baseValue(...args);
          };
          continue;
        }
      }
      props[key] = overrideValue;
    }
    return props;
  }
  var _React = { ...React59 };
  var useReactId = _React.useId;
  var useReactDeferredValue = _React.useDeferredValue;
  var useReactInsertionEffect = _React.useInsertionEffect;
  var useSafeLayoutEffect = canUseDOM ? import_react17.useLayoutEffect : import_react17.useEffect;
  function useInitialValue(value) {
    const [initialValue] = (0, import_react17.useState)(value);
    return initialValue;
  }
  function useLiveRef(value) {
    const ref = (0, import_react17.useRef)(value);
    useSafeLayoutEffect(() => {
      ref.current = value;
    });
    return ref;
  }
  function useEvent(callback) {
    const ref = (0, import_react17.useRef)(() => {
      throw new Error("Cannot call an event handler while rendering.");
    });
    if (useReactInsertionEffect) useReactInsertionEffect(() => {
      ref.current = callback;
    });
    else ref.current = callback;
    return (0, import_react17.useCallback)((...args) => ref.current?.(...args), []);
  }
  function useTransactionState(callback) {
    const [state, setState] = (0, import_react17.useState)(null);
    useSafeLayoutEffect(() => {
      if (state == null) return;
      if (!callback) return;
      let prevState = null;
      callback((prev) => {
        prevState = prev;
        return state;
      });
      return () => {
        callback(prevState);
      };
    }, [state, callback]);
    return [state, setState];
  }
  function useMergeRefs(...refs) {
    return (0, import_react17.useMemo)(() => {
      if (!refs.some(Boolean)) return;
      return (value) => {
        const refEffects = [];
        for (const ref of refs) {
          if (!ref) continue;
          const cleanup = setRef(ref, value);
          refEffects.push({
            ref,
            cleanup: typeof cleanup === "function" ? cleanup : void 0
          });
        }
        if (!refEffects.some((effect) => effect.cleanup)) return;
        return () => {
          for (const { ref, cleanup } of refEffects) if (cleanup) cleanup();
          else setRef(ref, null);
        };
      };
    }, refs);
  }
  function useId5(defaultId) {
    if (useReactId) {
      const reactId = useReactId();
      if (defaultId) return defaultId;
      return reactId;
    }
    const [id, setId] = (0, import_react17.useState)(defaultId);
    useSafeLayoutEffect(() => {
      if (defaultId || id) return;
      setId(`id-${Math.random().toString(36).slice(2, 8)}`);
    }, [defaultId, id]);
    return defaultId || id;
  }
  function useTagName(refOrElement, type) {
    const stringOrUndefined = (type2) => {
      if (typeof type2 !== "string") return;
      return type2;
    };
    const [tagName, setTagName] = (0, import_react17.useState)(() => stringOrUndefined(type));
    useSafeLayoutEffect(() => {
      setTagName((refOrElement && "current" in refOrElement ? refOrElement.current : refOrElement)?.tagName.toLowerCase() || stringOrUndefined(type));
    }, [refOrElement, type]);
    return tagName;
  }
  function useAttribute(refOrElement, attributeName, defaultValue2) {
    const initialValue = useInitialValue(defaultValue2);
    const [attribute, setAttribute] = (0, import_react17.useState)(initialValue);
    (0, import_react17.useEffect)(() => {
      const element = refOrElement && "current" in refOrElement ? refOrElement.current : refOrElement;
      if (!element) return;
      const callback = () => {
        const value = element.getAttribute(attributeName);
        setAttribute(value == null ? initialValue : value);
      };
      const observer = new MutationObserver(callback);
      observer.observe(element, { attributeFilter: [attributeName] });
      callback();
      return () => observer.disconnect();
    }, [
      refOrElement,
      attributeName,
      initialValue
    ]);
    return attribute;
  }
  function useUpdateEffect(effect, deps) {
    const mounted = (0, import_react17.useRef)(false);
    (0, import_react17.useEffect)(() => {
      if (mounted.current) return effect();
      mounted.current = true;
    }, deps);
    (0, import_react17.useEffect)(() => () => {
      mounted.current = false;
    }, []);
  }
  function useUpdateLayoutEffect(effect, deps) {
    const mounted = (0, import_react17.useRef)(false);
    useSafeLayoutEffect(() => {
      if (mounted.current) return effect();
      mounted.current = true;
    }, deps);
    useSafeLayoutEffect(() => () => {
      mounted.current = false;
    }, []);
  }
  function useForceUpdate2() {
    return (0, import_react17.useReducer)(() => [], []);
  }
  function useBooleanEvent(booleanOrCallback) {
    return useEvent(typeof booleanOrCallback === "function" ? booleanOrCallback : () => booleanOrCallback);
  }
  function useWrapElement(props, callback, deps = []) {
    const wrapElement = (0, import_react17.useCallback)((element) => {
      if (props.wrapElement) element = props.wrapElement(element);
      return callback(element);
    }, [...deps, props.wrapElement]);
    return {
      ...props,
      wrapElement
    };
  }
  function useMetadataProps(props, key, value) {
    const parent = props.onLoadedMetadataCapture;
    const onLoadedMetadataCapture = (0, import_react17.useMemo)(() => {
      return Object.assign(() => {
      }, parent, ...value !== void 0 ? [{ [key]: value }] : []);
    }, [
      parent,
      key,
      value
    ]);
    return [parent?.[key], { onLoadedMetadataCapture }];
  }
  var hasInstalledGlobalEventListeners = false;
  function useIsMouseMoving() {
    (0, import_react17.useEffect)(() => {
      if (hasInstalledGlobalEventListeners) return;
      addGlobalEventListener("mousemove", setMouseMoving, true);
      addGlobalEventListener("mousedown", resetMouseMoving, true);
      addGlobalEventListener("mouseup", resetMouseMoving, true);
      addGlobalEventListener("keydown", resetMouseMoving, true);
      addGlobalEventListener("scroll", resetMouseMoving, true);
      hasInstalledGlobalEventListeners = true;
    }, []);
    return useEvent(() => mouseMoving);
  }
  var mouseMoving = false;
  var previousScreenX = 0;
  var previousScreenY = 0;
  function hasMouseMovement(event) {
    const movementX = event.movementX || event.screenX - previousScreenX;
    const movementY = event.movementY || event.screenY - previousScreenY;
    previousScreenX = event.screenX;
    previousScreenY = event.screenY;
    return movementX || movementY || false;
  }
  function setMouseMoving(event) {
    if (!hasMouseMovement(event)) return;
    mouseMoving = true;
  }
  function resetMouseMoving() {
    mouseMoving = false;
  }
  function forwardRef43(render4) {
    const Role = React59.forwardRef((props, ref) => render4({
      ...props,
      ref
    }));
    Role.displayName = render4.displayName || render4.name;
    return Role;
  }
  function memo5(Component, propsAreEqual) {
    return React59.memo(Component, propsAreEqual);
  }
  function createElement5(Type, props) {
    const { wrapElement, render: render4, ...rest } = props;
    const mergedRef = useMergeRefs(props.ref, getRefProperty(render4));
    let element;
    if (React59.isValidElement(render4)) {
      const renderProps = {
        ...render4.props,
        ref: mergedRef
      };
      element = React59.cloneElement(render4, mergeProps2(rest, renderProps));
    } else if (render4) element = render4(rest);
    else element = /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(Type, { ...rest });
    if (wrapElement) return wrapElement(element);
    return element;
  }
  function createHook(useProps) {
    const useRole = (props = {}) => {
      return useProps(props);
    };
    useRole.displayName = useProps.name;
    return useRole;
  }
  function createStoreContext(providers = [], scopedProviders = []) {
    const context = React59.createContext(void 0);
    const scopedContext = React59.createContext(void 0);
    const useContext67 = () => React59.useContext(context);
    const useScopedContext = (onlyScoped = false) => {
      const scoped = React59.useContext(scopedContext);
      const store2 = useContext67();
      if (onlyScoped) return scoped;
      return scoped || store2;
    };
    const useProviderContext = () => {
      const scoped = React59.useContext(scopedContext);
      const store2 = useContext67();
      if (scoped && scoped === store2) return;
      return store2;
    };
    const ContextProvider = (props) => {
      return providers.reduceRight((children, Provider2) => /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(Provider2, {
        ...props,
        children
      }), /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(context.Provider, { ...props }));
    };
    const ScopedContextProvider = (props) => {
      return /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(ContextProvider, {
        ...props,
        children: scopedProviders.reduceRight((children, Provider2) => /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(Provider2, {
          ...props,
          children
        }), /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(scopedContext.Provider, { ...props }))
      });
    };
    return {
      context,
      scopedContext,
      useContext: useContext67,
      useScopedContext,
      useProviderContext,
      ContextProvider,
      ScopedContextProvider
    };
  }

  // node_modules/@ariakit/react-components/dist/focusable/focusable.js
  var import_react18 = __toESM(require_react(), 1);
  var TagName = "div";
  var accessibleWhenDisabledSymbol = /* @__PURE__ */ Symbol("accessibleWhenDisabled");
  var isSafariBrowser = isSafari();
  var alwaysFocusVisibleInputTypes = [
    "text",
    "search",
    "url",
    "tel",
    "email",
    "password",
    "number",
    "date",
    "month",
    "week",
    "time",
    "datetime",
    "datetime-local"
  ];
  function isAlwaysFocusVisible(element) {
    const { tagName, readOnly, type } = element;
    if (tagName === "TEXTAREA" && !readOnly) return true;
    if (tagName === "SELECT" && !readOnly) return true;
    if (tagName === "INPUT" && !readOnly) return alwaysFocusVisibleInputTypes.includes(type);
    if (element.isContentEditable) return true;
    if (element.getAttribute("role") === "combobox" && element.dataset.name) return true;
    return false;
  }
  function isNativeTabbable(tagName) {
    if (!tagName) return true;
    return tagName === "button" || tagName === "summary" || tagName === "input" || tagName === "select" || tagName === "textarea" || tagName === "a";
  }
  function supportsDisabledAttribute(tagName) {
    if (!tagName) return true;
    return tagName === "button" || tagName === "input" || tagName === "select" || tagName === "textarea";
  }
  function isNativeSubmitControl(element) {
    if (element.tagName === "BUTTON") {
      const { type } = element;
      return type === "submit";
    }
    if (element.tagName === "INPUT") {
      const { type } = element;
      return type === "submit" || type === "image";
    }
    return false;
  }
  function getTabIndex2({ focusable: focusable2, trulyDisabled, nativeTabbable, supportsDisabled, safariTabIndex, tabIndexProp }) {
    if (!focusable2) return tabIndexProp;
    if (trulyDisabled) {
      if (nativeTabbable && !supportsDisabled) return -1;
      return;
    }
    if (nativeTabbable) {
      if (safariTabIndex && tabIndexProp == null) return 0;
      return tabIndexProp;
    }
    return tabIndexProp ?? 0;
  }
  function useDisableEvent(onEvent, disabled2) {
    return useEvent((event) => {
      onEvent?.(event);
      if (event.defaultPrevented) return;
      if (disabled2) {
        event.stopPropagation();
        event.preventDefault();
      }
    });
  }
  var hasInstalledGlobalEventListeners2 = false;
  var isKeyboardModality = true;
  function onGlobalMouseDown(event) {
    const target = event.target;
    if (isElement2(target) && !target.hasAttribute("data-focus-visible")) isKeyboardModality = false;
  }
  function onGlobalKeyDown(event) {
    if (event.metaKey) return;
    if (event.ctrlKey) return;
    if (event.altKey) return;
    isKeyboardModality = true;
  }
  var useFocusable = createHook(function useFocusable2({ focusable: focusable2 = true, accessibleWhenDisabled, autoFocus, onFocusVisible, ...props }) {
    const ref = (0, import_react18.useRef)(null);
    const [parentAccessibleWhenDisabled, metadataProps] = useMetadataProps(props, accessibleWhenDisabledSymbol, accessibleWhenDisabled);
    accessibleWhenDisabled ??= parentAccessibleWhenDisabled;
    (0, import_react18.useEffect)(() => {
      if (!focusable2) return;
      if (hasInstalledGlobalEventListeners2) return;
      addGlobalEventListener("mousedown", onGlobalMouseDown, true);
      addGlobalEventListener("keydown", onGlobalKeyDown, true);
      hasInstalledGlobalEventListeners2 = true;
    }, [focusable2]);
    const disabled2 = focusable2 && disabledFromProps(props);
    const trulyDisabled = disabled2 && !accessibleWhenDisabled;
    const [focusVisible, setFocusVisible] = (0, import_react18.useState)(false);
    const focusVisibleRef = (0, import_react18.useRef)(false);
    const nativeSubmitObserverCleanupRef = (0, import_react18.useRef)(null);
    const cleanupFocusVisible = useEvent((element) => {
      nativeSubmitObserverCleanupRef.current?.();
      nativeSubmitObserverCleanupRef.current = null;
      focusVisibleRef.current = false;
      element?.removeAttribute("data-focus-visible");
    });
    (0, import_react18.useEffect)(() => {
      if (!focusable2) return;
      if (!trulyDisabled) return;
      cleanupFocusVisible(ref.current);
      if (focusVisible) setFocusVisible(false);
    }, [
      focusable2,
      trulyDisabled,
      focusVisible,
      cleanupFocusVisible
    ]);
    (0, import_react18.useEffect)(() => {
      if (!focusable2) return;
      if (!focusVisible) return;
      const element = ref.current;
      if (!element) return;
      if (typeof IntersectionObserver === "undefined") return;
      const observer = new IntersectionObserver(() => {
        if (!isFocusable(element)) {
          focusVisibleRef.current = false;
          setFocusVisible(false);
        }
      });
      observer.observe(element);
      return () => observer.disconnect();
    }, [focusable2, focusVisible]);
    (0, import_react18.useEffect)(() => {
      return () => nativeSubmitObserverCleanupRef.current?.();
    }, []);
    const onKeyPressCapture = useDisableEvent(props.onKeyPressCapture, disabled2);
    const onMouseDownCapture = useDisableEvent(props.onMouseDownCapture, disabled2);
    const onClickCapture = useDisableEvent(props.onClickCapture, disabled2);
    const handleFocusVisible = (event, currentTarget) => {
      if (currentTarget) event.currentTarget = currentTarget;
      if (!focusable2) return;
      const element = event.currentTarget;
      if (!element) return;
      if (!hasFocus(element)) return;
      onFocusVisible?.(event);
      if (event.defaultPrevented) return;
      element.dataset.focusVisible = "true";
      focusVisibleRef.current = true;
      if (isNativeSubmitControl(element)) {
        nativeSubmitObserverCleanupRef.current?.();
        nativeSubmitObserverCleanupRef.current = null;
        if (typeof IntersectionObserver !== "undefined") {
          const observer = new IntersectionObserver(() => {
            if (isFocusable(element)) return;
            cleanupFocusVisible(element);
          });
          observer.observe(element);
          nativeSubmitObserverCleanupRef.current = () => observer.disconnect();
        }
        return;
      }
      setFocusVisible(true);
    };
    const onKeyDownCaptureProp = props.onKeyDownCapture;
    const onKeyDownCapture = useEvent((event) => {
      onKeyDownCaptureProp?.(event);
      if (event.defaultPrevented) return;
      if (!focusable2) return;
      if (focusVisible) return;
      if (focusVisibleRef.current) return;
      if (event.metaKey) return;
      if (event.altKey) return;
      if (event.ctrlKey) return;
      if (!isSelfTarget(event)) return;
      const element = event.currentTarget;
      const applyFocusVisible = () => handleFocusVisible(event, element);
      queueBeforeEvent(element, "focusout", applyFocusVisible);
    });
    const onFocusCaptureProp = props.onFocusCapture;
    const onFocusCapture = useEvent((event) => {
      onFocusCaptureProp?.(event);
      if (event.defaultPrevented) return;
      if (!focusable2) return;
      if (!isSelfTarget(event)) {
        setFocusVisible(false);
        return;
      }
      const element = event.currentTarget;
      const applyFocusVisible = () => handleFocusVisible(event, element);
      if (isKeyboardModality || isAlwaysFocusVisible(event.target)) queueBeforeEvent(event.target, "focusout", applyFocusVisible);
      else setFocusVisible(false);
    });
    const onBlurProp = props.onBlur;
    const onBlur = useEvent((event) => {
      onBlurProp?.(event);
      if (!focusable2) return;
      if (!isFocusEventOutside(event)) return;
      cleanupFocusVisible(event.currentTarget);
      setFocusVisible(false);
    });
    const autoFocusOnShow = (0, import_react18.useContext)(FocusableContext);
    const autoFocusRef = useEvent((element) => {
      if (!focusable2) return;
      if (!autoFocus) return;
      if (!element) return;
      if (!autoFocusOnShow) return;
      queueMicrotask(() => {
        if (hasFocus(element)) return;
        if (!isFocusable(element)) return;
        element.focus();
      });
    });
    const tagName = useTagName(ref);
    const nativeTabbable = focusable2 && isNativeTabbable(tagName);
    const supportsDisabled = focusable2 && supportsDisabledAttribute(tagName);
    const [safariTabIndex, setSafariTabIndex] = (0, import_react18.useState)(false);
    if (isSafariBrowser) (0, import_react18.useEffect)(() => {
      if (!focusable2) return;
      const element = ref.current;
      if (!element) return;
      const { type } = element;
      const isNativeCheckboxOrRadio = element.tagName === "INPUT" && (type === "checkbox" || type === "radio");
      setSafariTabIndex(isButton(element) || isNativeCheckboxOrRadio);
    }, [focusable2]);
    const styleProp = props.style;
    const style = (0, import_react18.useMemo)(() => {
      if (trulyDisabled) return {
        pointerEvents: "none",
        ...styleProp
      };
      return styleProp;
    }, [trulyDisabled, styleProp]);
    props = {
      "data-focus-visible": focusable2 && focusVisible || void 0,
      "data-autofocus": autoFocus || void 0,
      "aria-disabled": disabled2 || void 0,
      ...props,
      ...metadataProps,
      ref: useMergeRefs(ref, autoFocusRef, props.ref),
      style,
      tabIndex: getTabIndex2({
        focusable: focusable2,
        trulyDisabled,
        nativeTabbable,
        supportsDisabled,
        safariTabIndex,
        tabIndexProp: props.tabIndex
      }),
      disabled: supportsDisabled && trulyDisabled ? true : void 0,
      contentEditable: disabled2 ? void 0 : props.contentEditable,
      onKeyPressCapture,
      onClickCapture,
      onMouseDownCapture,
      onKeyDownCapture,
      onFocusCapture,
      onBlur
    };
    return removeUndefinedValues(props);
  });
  var Focusable = forwardRef43(function Focusable2(props) {
    return createElement5(TagName, useFocusable(props));
  });

  // node_modules/@ariakit/react-components/dist/command/command.js
  var import_react19 = __toESM(require_react(), 1);
  var TagName2 = "button";
  function isNativeClick(event) {
    if (!event.isTrusted) return false;
    const element = event.currentTarget;
    if (event.key === "Enter") return isButton(element) || element.tagName === "SUMMARY" || element.tagName === "A";
    if (event.key === " ") return isButton(element) || element.tagName === "SUMMARY" || element.tagName === "INPUT" || element.tagName === "SELECT";
    return false;
  }
  var symbol = /* @__PURE__ */ Symbol("command");
  var useCommand = createHook(function useCommand2({ clickOnEnter = true, clickOnSpace = true, ...props }) {
    const ref = (0, import_react19.useRef)(null);
    const [isNativeButton, setIsNativeButton] = (0, import_react19.useState)(false);
    (0, import_react19.useEffect)(() => {
      if (!ref.current) return;
      setIsNativeButton(isButton(ref.current));
    }, []);
    const [active, setActive] = (0, import_react19.useState)(false);
    const activeRef = (0, import_react19.useRef)(false);
    const disabled2 = disabledFromProps(props);
    const [isDuplicate, metadataProps] = useMetadataProps(props, symbol, true);
    useSafeLayoutEffect(() => {
      if (!disabled2) return;
      activeRef.current = false;
      setActive(false);
    }, [disabled2]);
    const onKeyDownProp = props.onKeyDown;
    const onKeyDown = useEvent((event) => {
      onKeyDownProp?.(event);
      const element = event.currentTarget;
      if (event.defaultPrevented) return;
      if (isDuplicate) return;
      if (disabled2) return;
      if (!isSelfTarget(event)) return;
      if (isTextField(element)) return;
      if (element.isContentEditable) return;
      const isEnter = clickOnEnter && event.key === "Enter";
      const isSpace = clickOnSpace && event.key === " ";
      const shouldPreventEnter = event.key === "Enter" && !clickOnEnter;
      const shouldPreventSpace = event.key === " " && !clickOnSpace;
      if (shouldPreventEnter || shouldPreventSpace) {
        event.preventDefault();
        return;
      }
      if (isEnter || isSpace) {
        const nativeClick = isNativeClick(event);
        if (isEnter) {
          if (!nativeClick) {
            event.preventDefault();
            const { view, ...eventInit } = event;
            const click = () => fireClickEvent(element, eventInit);
            if (isFirefox()) queueBeforeEvent(element, "keyup", click);
            else queueMicrotask(click);
          }
        } else if (isSpace) {
          activeRef.current = true;
          if (!nativeClick) {
            event.preventDefault();
            setActive(true);
          }
        }
      }
    });
    const onKeyUpProp = props.onKeyUp;
    const onKeyUp = useEvent((event) => {
      onKeyUpProp?.(event);
      if (isDuplicate) return;
      const isSpace = clickOnSpace && event.key === " ";
      if (!activeRef.current || !isSpace) return;
      const nativeClick = isNativeClick(event);
      activeRef.current = false;
      if (!nativeClick) setActive(false);
      if (event.defaultPrevented) return;
      if (!isSelfTarget(event)) return;
      if (disabled2) return;
      if (event.metaKey) return;
      if (nativeClick) return;
      event.preventDefault();
      const element = event.currentTarget;
      const { view, ...eventInit } = event;
      queueMicrotask(() => fireClickEvent(element, eventInit));
    });
    const onBlurProp = props.onBlur;
    const onBlur = useEvent((event) => {
      onBlurProp?.(event);
      if (!activeRef.current) return;
      activeRef.current = false;
      setActive(false);
    });
    props = {
      "data-active": active || void 0,
      type: isNativeButton ? "button" : void 0,
      ...metadataProps,
      ...props,
      ref: useMergeRefs(ref, props.ref),
      onKeyDown,
      onKeyUp,
      onBlur
    };
    props = useFocusable(props);
    return props;
  });
  var Command = forwardRef43(function Command2(props) {
    return createElement5(TagName2, useCommand(props));
  });

  // node_modules/@ariakit/react-components/dist/collection/collection-context.js
  var ctx2 = createStoreContext();
  var useCollectionContext = ctx2.useContext;
  var useCollectionScopedContext = ctx2.useScopedContext;
  var useCollectionProviderContext = ctx2.useProviderContext;
  var CollectionContextProvider = ctx2.ContextProvider;
  var CollectionScopedContextProvider = ctx2.ScopedContextProvider;

  // node_modules/@ariakit/react-components/dist/collection/collection-item.js
  var import_react20 = __toESM(require_react(), 1);
  var TagName3 = "div";
  var useCollectionItem = createHook(function useCollectionItem2({ store: store2, shouldRegisterItem = true, getItem = identity, element, ...props }) {
    const context = useCollectionContext();
    store2 = store2 || context;
    const id = useId5(props.id);
    const ref = (0, import_react20.useRef)(element);
    (0, import_react20.useEffect)(() => {
      const element2 = ref.current;
      if (!id) return;
      if (!element2) return;
      if (!shouldRegisterItem) return;
      const item = getItem({
        id,
        element: element2
      });
      return store2?.renderItem(item);
    }, [
      id,
      shouldRegisterItem,
      getItem,
      store2
    ]);
    props = {
      ...props,
      ref: useMergeRefs(ref, props.ref)
    };
    return removeUndefinedValues(props);
  });
  var CollectionItem = forwardRef43(function CollectionItem2(props) {
    return createElement5(TagName3, useCollectionItem(props));
  });

  // node_modules/@ariakit/react-components/dist/composite/composite-context.js
  var import_react21 = __toESM(require_react(), 1);
  var ctx3 = createStoreContext([CollectionContextProvider], [CollectionScopedContextProvider]);
  var useCompositeContext = ctx3.useContext;
  var useCompositeScopedContext = ctx3.useScopedContext;
  var useCompositeProviderContext = ctx3.useProviderContext;
  var CompositeContextProvider = ctx3.ContextProvider;
  var CompositeScopedContextProvider = ctx3.ScopedContextProvider;
  var CompositeItemContext = (0, import_react21.createContext)(void 0);
  var CompositeRowContext = (0, import_react21.createContext)(void 0);

  // node_modules/@ariakit/store/dist/index.js
  function getInternal(store2, key) {
    const internals = store2.__unstableInternals;
    invariant(internals, "Invalid store");
    return internals[key];
  }
  function hasUpdatedKey(keys, updatedKey) {
    if (!keys) return true;
    for (const currentKey of keys) if (updatedKey instanceof Set) {
      if (updatedKey.has(currentKey)) return true;
    } else if (currentKey === updatedKey) return true;
    return false;
  }
  function isSameValue(value, other) {
    return value === other || value !== value && other !== other;
  }
  function getCleanupPrevState(prevState, state, stateBeforeCleanup, updatedKey) {
    let cleanupPrevState;
    for (const key of getKeys(state)) {
      if (isSameValue(state[key], stateBeforeCleanup[key])) continue;
      if (updatedKey !== void 0 && hasUpdatedKey([key], updatedKey)) continue;
      cleanupPrevState ??= { ...prevState };
      cleanupPrevState[key] = state[key];
    }
    return cleanupPrevState;
  }
  var MAX_REPAIR_PASSES = 100;
  function addKeyedListener(map, keys, listener) {
    if (!keys) return;
    for (const key of keys) {
      let listeners = map.get(key);
      if (!listeners) {
        listeners = /* @__PURE__ */ new Set();
        map.set(key, listeners);
      }
      listeners.add(listener);
    }
  }
  function deleteKeyedListener(map, keys, listener) {
    if (!map) return;
    if (!keys) return;
    for (const key of keys) {
      const listeners = map.get(key);
      if (!listeners) continue;
      listeners.delete(listener);
      if (!listeners.size) map.delete(key);
    }
  }
  function getFastPathNotifiedListeners(frame) {
    const notifiedListeners = /* @__PURE__ */ new Set();
    const currentListener = frame.currentListener;
    if (!currentListener) return notifiedListeners;
    for (const listener of frame.keyedListeners) {
      notifiedListeners.add(listener);
      if (listener === currentListener) return notifiedListeners;
    }
    notifiedListeners.clear();
    notifiedListeners.add(currentListener);
    return notifiedListeners;
  }
  function preserveFastPathNotifiedListeners(frame) {
    frame.notifiedListeners ??= getFastPathNotifiedListeners(frame);
  }
  function hasFastPathPassedListener(frame, listener) {
    if (!frame.currentListener) return false;
    let foundCurrentKeyedListener = false;
    for (const currentListener of frame.keyedListeners) {
      if (currentListener === frame.currentListener) {
        foundCurrentKeyedListener = true;
        continue;
      }
      if (!foundCurrentKeyedListener) continue;
      if (currentListener === listener) return false;
    }
    let foundListener = false;
    for (const currentListener of frame.group.listeners) {
      if (currentListener === frame.currentListener) return foundListener;
      if (currentListener === listener) foundListener = true;
    }
    return false;
  }
  function preserveFastPathFrames(fastPathFrames, group, listener) {
    for (const frame of fastPathFrames) {
      if (frame.group !== group) continue;
      if (frame.recovering) continue;
      if (listener && !frame.keyedListeners.has(listener)) continue;
      preserveFastPathNotifiedListeners(frame);
      for (const currentListener of frame.group.listeners) {
        if (currentListener === frame.currentListener) break;
        if (!hasFastPathPassedListener(frame, currentListener)) continue;
        frame.notifiedListeners?.add(currentListener);
      }
    }
  }
  function preserveFastPathPassedListeners(fastPathFrames, group, listener) {
    for (const frame of fastPathFrames) {
      if (frame.group !== group) continue;
      if (frame.recovering) continue;
      if (!hasFastPathPassedListener(frame, listener)) continue;
      preserveFastPathNotifiedListeners(frame);
      frame.notifiedListeners?.add(listener);
    }
  }
  function preserveFastPathPassedKeyedListeners({ fastPathFrames, group, keys, listener }) {
    const wasRegistered = group.listeners.has(listener);
    for (const frame of fastPathFrames) {
      if (frame.group !== group) continue;
      if (frame.recovering) continue;
      if (!keys.includes(frame.updatedKey)) continue;
      if (hasFastPathPassedListener(frame, listener)) {
        preserveFastPathNotifiedListeners(frame);
        frame.notifiedListeners?.add(listener);
      } else if (wasRegistered) {
        preserveFastPathNotifiedListeners(frame);
        frame.recoverToLive = true;
      }
    }
  }
  function clearFastPathNotifiedListener(fastPathFrames, group, listener) {
    for (const frame of fastPathFrames) {
      if (frame.group !== group) continue;
      frame.notifiedListeners?.delete(listener);
    }
  }
  function addFastPathKeyedListener({ fastPathFrames, group, keys, listener }) {
    for (const frame of fastPathFrames) {
      if (frame.group !== group) continue;
      if (frame.recovering) continue;
      if (!keys.includes(frame.updatedKey)) continue;
      frame.keyedListeners.add(listener);
    }
  }
  function runPendingCleanup(group, listener) {
    if (!group.disposables.size) return;
    const cleanup = group.disposables.get(listener);
    if (!cleanup) return;
    group.disposables.delete(listener);
    cleanup();
  }
  function setListenerCleanup(group, listener, cleanup) {
    const currentCleanup = group.disposables.get(listener);
    if (!currentCleanup) {
      group.disposables.set(listener, cleanup);
      return;
    }
    group.disposables.set(listener, () => {
      currentCleanup();
      cleanup();
    });
  }
  function notifyStoreListener(group, listener, state, prevState, getState, updatedKey) {
    if (group.suspendCounts?.has(listener)) return;
    const { disposables } = group;
    const cleanup = disposables.size ? disposables.get(listener) : void 0;
    if (cleanup) {
      disposables.delete(listener);
      const stateBeforeCleanup = state;
      cleanup();
      state = getState?.() ?? state;
      if (state !== stateBeforeCleanup) prevState = getCleanupPrevState(prevState, state, stateBeforeCleanup, updatedKey) ?? prevState;
    }
    const result = listener(state, prevState);
    if (result) setListenerCleanup(group, listener, result);
  }
  function runLiveListeners({ group, getState, prevState, updatedKey, notifiedListeners }) {
    const allKeysListeners = group.allKeysListeners;
    for (const listener of group.listeners) {
      if (notifiedListeners?.has(listener)) continue;
      if (!allKeysListeners?.has(listener)) {
        if (!hasUpdatedKey(group.listenerKeys.get(listener), updatedKey)) continue;
      }
      notifiedListeners?.add(listener);
      notifyStoreListener(group, listener, getState(), prevState, getState, updatedKey);
    }
  }
  function createStore(initialState, ...stores) {
    let state = initialState;
    let prevStateBatch = state;
    let destroy = noop5;
    let batchPending = false;
    let inDispatch = false;
    let updatedKeys = /* @__PURE__ */ new Set();
    const instances = /* @__PURE__ */ new Set();
    const setups = /* @__PURE__ */ new Set();
    const syncListenerGroup = {
      listeners: /* @__PURE__ */ new Set(),
      disposables: /* @__PURE__ */ new Map(),
      listenerKeys: /* @__PURE__ */ new WeakMap()
    };
    const batchListenerGroup = {
      listeners: /* @__PURE__ */ new Set(),
      disposables: /* @__PURE__ */ new Map(),
      listenerKeys: /* @__PURE__ */ new WeakMap()
    };
    const storeSetup = (callback) => {
      setups.add(callback);
      return () => setups.delete(callback);
    };
    const storeInit = () => {
      const initializedInstances = instances.size;
      const instance = /* @__PURE__ */ Symbol();
      instances.add(instance);
      const maybeDestroy = () => {
        if (!instances.delete(instance)) return;
        if (instances.size) return;
        destroy();
      };
      if (initializedInstances) return maybeDestroy;
      const stateKeys = getKeys(state);
      const desyncs = [];
      for (const store2 of stores) {
        const storeState = store2?.getState?.();
        if (!storeState) continue;
        const keys = stateKeys.filter((key) => hasOwnProperty(storeState, key));
        if (!keys.length) continue;
        if (stores.length === 1 || keys.length === stateKeys.length) {
          for (const key of keys) desyncs.push(sync2(store2, [key], (state2) => {
            setState(key, state2[key], true);
          }));
          continue;
        }
        desyncs.push(subscribe2(store2, keys, (state2, prevState) => {
          for (const key of keys) {
            if (state2[key] === prevState[key]) continue;
            setState(key, state2[key], true);
          }
        }));
        for (const key of keys) {
          const liveState = store2?.getState?.();
          if (!liveState) continue;
          setState(key, liveState[key], true);
        }
      }
      const teardowns = [];
      for (const setup2 of setups) teardowns.push(setup2());
      const cleanups = stores.map(init);
      destroy = chain(...desyncs, ...teardowns, ...cleanups);
      return maybeDestroy;
    };
    const deleteListenerIndexes = (group, listener, keys) => {
      if (keys === void 0) return;
      if (keys) deleteKeyedListener(group.listenersByKey, keys, listener);
      else group.allKeysListeners?.delete(listener);
    };
    const fastPathFrames = [];
    const registerListener = (keys, listener, group = syncListenerGroup) => {
      const listenerKeysValue = keys ? [...keys] : null;
      const wasRegistered = group.listeners.has(listener);
      if (!wasRegistered) clearFastPathNotifiedListener(fastPathFrames, group, listener);
      if (!listenerKeysValue) {
        if (wasRegistered) preserveFastPathFrames(fastPathFrames, group);
        preserveFastPathPassedListeners(fastPathFrames, group, listener);
      } else preserveFastPathPassedKeyedListeners({
        fastPathFrames,
        group,
        keys: listenerKeysValue,
        listener
      });
      if (wasRegistered) {
        preserveFastPathFrames(fastPathFrames, group, listener);
        deleteListenerIndexes(group, listener, group.listenerKeys.get(listener));
      }
      group.listeners.add(listener);
      if (listenerKeysValue) {
        group.listenersByKey ??= /* @__PURE__ */ new Map();
        addKeyedListener(group.listenersByKey, listenerKeysValue, listener);
        addFastPathKeyedListener({
          fastPathFrames,
          group,
          keys: listenerKeysValue,
          listener
        });
      } else {
        group.allKeysListeners ??= /* @__PURE__ */ new Set();
        group.allKeysListeners.add(listener);
      }
      group.listenerKeys.set(listener, listenerKeysValue);
      return () => {
        const cleanup = group.disposables.get(listener);
        group.disposables.delete(listener);
        preserveFastPathFrames(fastPathFrames, group, listener);
        const currentKeys = group.listenerKeys.get(listener);
        deleteListenerIndexes(group, listener, listenerKeysValue);
        if (currentKeys !== listenerKeysValue) deleteListenerIndexes(group, listener, currentKeys);
        group.listenerKeys.delete(listener);
        group.listeners.delete(listener);
        cleanup?.();
      };
    };
    const storeSubscribe = (keys, listener) => registerListener(keys, listener);
    const runInitialListener = (group, listener, prevState) => {
      const shouldSuspend = group.listeners.has(listener);
      if (shouldSuspend) {
        group.suspendCounts ??= /* @__PURE__ */ new Map();
        const count = group.suspendCounts.get(listener) ?? 0;
        group.suspendCounts.set(listener, count + 1);
      }
      let cleanupPrevState;
      try {
        const stateBeforeCleanups = state;
        runPendingCleanup(group, listener);
        if (state !== stateBeforeCleanups) cleanupPrevState = getCleanupPrevState(prevState, state, stateBeforeCleanups);
        const cleanup = listener(state, cleanupPrevState ?? prevState);
        if (cleanup) setListenerCleanup(group, listener, cleanup);
      } finally {
        if (shouldSuspend) {
          const suspendCounts = group.suspendCounts;
          const count = suspendCounts?.get(listener);
          if (count && count > 1) suspendCounts?.set(listener, count - 1);
          else suspendCounts?.delete(listener);
          if (!suspendCounts?.size) delete group.suspendCounts;
        }
      }
    };
    const storeSync = (keys, listener) => {
      runInitialListener(syncListenerGroup, listener, state);
      return registerListener(keys, listener);
    };
    const storeBatch = (keys, listener) => {
      if (!batchListenerGroup.listeners.size && !inDispatch) prevStateBatch = state;
      runInitialListener(batchListenerGroup, listener, prevStateBatch);
      return registerListener(keys, listener, batchListenerGroup);
    };
    const storePick = (keys) => createStore(pick(state, keys), finalStore);
    const storeOmit = (keys) => createStore(omit(state, keys), finalStore);
    const getState = () => state;
    const runListeners = (group, prevState, updatedKey) => {
      if (!(updatedKey instanceof Set) && !group.allKeysListeners?.size) {
        const keyedListeners = group.listenersByKey?.get(updatedKey);
        if (!keyedListeners) return;
        const frame = {
          group,
          keyedListeners,
          updatedKey,
          currentListener: null
        };
        fastPathFrames.push(frame);
        try {
          for (const listener of keyedListeners) {
            if (frame.notifiedListeners?.has(listener)) continue;
            frame.currentListener = listener;
            frame.notifiedListeners?.add(listener);
            notifyStoreListener(group, listener, state, prevState, getState, updatedKey);
            if (!group.allKeysListeners?.size && !frame.recoverToLive) continue;
            const notifiedListeners = frame.notifiedListeners ?? getFastPathNotifiedListeners(frame);
            frame.notifiedListeners = notifiedListeners;
            frame.recovering = true;
            runLiveListeners({
              group,
              getState,
              prevState,
              updatedKey,
              notifiedListeners
            });
            return;
          }
        } finally {
          fastPathFrames.pop();
        }
        return;
      }
      runLiveListeners({
        group,
        getState,
        prevState,
        updatedKey
      });
    };
    const setState = (key, value, fromStores = false) => {
      if (!hasOwnProperty(state, key)) return;
      const currentValue = state[key];
      const nextValue = typeof value === "function" ? value(currentValue) : value;
      if (isSameValue(nextValue, currentValue)) return;
      const wasInDispatch = inDispatch;
      inDispatch = true;
      const prevState = state;
      const nextState = {
        ...state,
        [key]: nextValue
      };
      state = nextState;
      let superseded = false;
      try {
        if (!fromStores && stores.length) {
          for (const store2 of stores) {
            store2?.setState?.(key, nextValue);
            if (isSameValue(state[key], nextValue)) continue;
            superseded = true;
            break;
          }
          if (superseded) {
            let pass = 0;
            for (; pass < MAX_REPAIR_PASSES; pass += 1) {
              let changed = false;
              for (const store2 of stores) {
                const previousValue = state[key];
                store2?.setState?.(key, previousValue);
                if (!isSameValue(state[key], previousValue)) changed = true;
              }
              if (!changed) break;
            }
            if (pass === MAX_REPAIR_PASSES) console.warn("Parent stores did not converge after a superseded fan-out; a parent listener may be rewriting this key in a cycle.");
          }
        }
        if (!superseded) runListeners(syncListenerGroup, state === nextState ? prevState : {
          ...state,
          [key]: prevState[key]
        }, key);
      } finally {
        inDispatch = wasInDispatch;
      }
      if (!batchListenerGroup.listeners.size) {
        if (!inDispatch) prevStateBatch = state;
        return;
      }
      updatedKeys.add(key);
      if (batchPending) return;
      batchPending = true;
      queueMicrotask(() => {
        batchPending = false;
        const snapshot = state;
        const updatedKeysSnapshot = updatedKeys;
        updatedKeys = /* @__PURE__ */ new Set();
        const prevStateBatchBefore = prevStateBatch;
        runListeners(batchListenerGroup, prevStateBatchBefore, updatedKeysSnapshot);
        if (prevStateBatch === prevStateBatchBefore) prevStateBatch = snapshot;
      });
    };
    const finalStore = {
      getState,
      setState,
      __unstableInternals: {
        setup: storeSetup,
        init: storeInit,
        subscribe: storeSubscribe,
        sync: storeSync,
        batch: storeBatch,
        pick: storePick,
        omit: storeOmit
      }
    };
    return finalStore;
  }
  function setup(store2, ...args) {
    if (!store2) return;
    return getInternal(store2, "setup")(...args);
  }
  function init(store2, ...args) {
    if (!store2) return;
    return getInternal(store2, "init")(...args);
  }
  function subscribe2(store2, ...args) {
    if (!store2) return;
    return getInternal(store2, "subscribe")(...args);
  }
  function sync2(store2, ...args) {
    if (!store2) return;
    return getInternal(store2, "sync")(...args);
  }
  function batch(store2, ...args) {
    if (!store2) return;
    return getInternal(store2, "batch")(...args);
  }
  function omit2(store2, ...args) {
    if (!store2) return;
    return getInternal(store2, "omit")(...args);
  }
  function pick2(store2, ...args) {
    if (!store2) return;
    return getInternal(store2, "pick")(...args);
  }
  function mergeStore(...stores) {
    const initialState = {};
    for (const store3 of stores) {
      const nextState = store3?.getState?.();
      if (nextState) Object.assign(initialState, nextState);
    }
    const store2 = createStore(initialState, ...stores);
    return Object.assign({}, ...stores, store2);
  }
  function throwOnConflictingProps(props, store2) {
    if (false) return;
    if (!store2) return;
    const defaultKeys = Object.entries(props).filter(([key, value]) => key.startsWith("default") && value !== void 0).map(([key]) => {
      const stateKey = key.replace("default", "");
      return `${stateKey[0]?.toLowerCase() || ""}${stateKey.slice(1)}`;
    });
    if (!defaultKeys.length) return;
    const storeState = store2.getState();
    if (!defaultKeys.filter((key) => hasOwnProperty(storeState, key)).length) return;
    throw new Error(`Passing a store prop in conjunction with a default state is not supported.

const store = useSelectStore();
<SelectProvider store={store} defaultValue="Apple" />
                ^             ^

Instead, pass the default state to the topmost store:

const store = useSelectStore({ defaultValue: "Apple" });
<SelectProvider store={store} />

See https://github.com/ariakit/ariakit/pull/2745 for more details.

If there's a particular need for this, please submit a feature request at https://github.com/ariakit/ariakit
`);
  }

  // node_modules/@ariakit/components/dist/collection/collection-store.js
  function getCommonParent(items) {
    const firstItem = items.find((item) => !!item.element);
    const lastElement = [...items].reverse().find((item) => !!item.element)?.element;
    let parentElement = firstItem?.element?.parentElement;
    if (!lastElement) return getDocument(parentElement).body;
    while (parentElement) {
      if (parentElement.contains(lastElement)) return parentElement;
      parentElement = parentElement.parentElement;
    }
    return getDocument(parentElement).body;
  }
  function getPrivateStore(store2) {
    return store2?.__unstablePrivateStore;
  }
  function createCollectionStore(props = {}) {
    throwOnConflictingProps(props, props.store);
    const syncState = props.store?.getState();
    const items = defaultValue(props.items, syncState?.items, props.defaultItems, []);
    const itemsMap = new Map(items.map((item) => [item.id, item]));
    const initialState = {
      items,
      renderedItems: defaultValue(syncState?.renderedItems, [])
    };
    const syncPrivateStore = getPrivateStore(props.store);
    const privateStore = createStore({
      items,
      renderedItems: initialState.renderedItems
    }, syncPrivateStore);
    const collection = createStore(initialState, props.store);
    const sortItems = (renderedItems) => {
      const sortedItems = sortBasedOnDOMPosition(renderedItems, (i2) => i2.element);
      privateStore.setState("renderedItems", sortedItems);
      collection.setState("renderedItems", sortedItems);
    };
    setup(collection, () => init(privateStore));
    setup(privateStore, () => {
      return batch(privateStore, ["items"], (state) => {
        collection.setState("items", state.items);
      });
    });
    setup(privateStore, () => {
      return batch(privateStore, ["renderedItems"], (state) => {
        let firstRun = true;
        let raf2 = requestAnimationFrame(() => {
          const { renderedItems } = collection.getState();
          if (state.renderedItems === renderedItems) return;
          sortItems(state.renderedItems);
        });
        if (typeof IntersectionObserver !== "function") return () => cancelAnimationFrame(raf2);
        const ioCallback = () => {
          if (firstRun) {
            firstRun = false;
            return;
          }
          cancelAnimationFrame(raf2);
          raf2 = requestAnimationFrame(() => sortItems(state.renderedItems));
        };
        const root = getCommonParent(state.renderedItems);
        const observer = new IntersectionObserver(ioCallback, { root });
        for (const item of state.renderedItems) {
          if (!item.element) continue;
          observer.observe(item.element);
        }
        return () => {
          cancelAnimationFrame(raf2);
          observer.disconnect();
        };
      });
    });
    const mergeItem = (item, setItems, canDeleteFromMap = false) => {
      let prevItem;
      setItems((items2) => {
        const index2 = items2.findIndex(({ id }) => id === item.id);
        const nextItems = items2.slice();
        if (index2 !== -1) {
          prevItem = items2[index2];
          const nextItem = {
            ...prevItem,
            ...item
          };
          nextItems[index2] = nextItem;
          itemsMap.set(item.id, nextItem);
        } else {
          nextItems.push(item);
          itemsMap.set(item.id, item);
        }
        return nextItems;
      });
      const unmergeItem = () => {
        setItems((items2) => {
          if (!prevItem) {
            if (canDeleteFromMap) itemsMap.delete(item.id);
            return items2.filter(({ id }) => id !== item.id);
          }
          const index2 = items2.findIndex(({ id }) => id === item.id);
          if (index2 === -1) return items2;
          const nextItems = items2.slice();
          nextItems[index2] = prevItem;
          itemsMap.set(item.id, prevItem);
          return nextItems;
        });
      };
      return unmergeItem;
    };
    const registerItem = (item) => mergeItem(item, (getItems) => privateStore.setState("items", getItems), true);
    return {
      ...collection,
      registerItem,
      renderItem: (item) => chain(registerItem(item), mergeItem(item, (getItems) => privateStore.setState("renderedItems", getItems))),
      item: (id) => {
        if (!id) return null;
        let item = itemsMap.get(id);
        if (!item) {
          const { items: items2 } = privateStore.getState();
          item = items2.find((item2) => item2.id === id);
          if (item) itemsMap.set(id, item);
        }
        return item || null;
      },
      __unstablePrivateStore: privateStore
    };
  }

  // node_modules/@ariakit/components/dist/composite/composite-store.js
  var NULL_ITEM = { id: null };
  function findFirstEnabledItem(items, excludeId) {
    return items.find((item) => {
      if (excludeId) return !item.disabled && item.id !== excludeId;
      return !item.disabled;
    });
  }
  function getEnabledItems(items, excludeId) {
    return items.filter((item) => {
      if (excludeId) return !item.disabled && item.id !== excludeId;
      return !item.disabled;
    });
  }
  function getItemsInRow(items, rowId) {
    return items.filter((item) => item.rowId === rowId);
  }
  function findEnabledItemId({ items, fromIndex, step, rowId, excludeId }) {
    for (let i2 = fromIndex; i2 >= 0 && i2 < items.length; i2 += step) {
      const item = items[i2];
      if (!item) continue;
      if (item.rowId !== rowId) continue;
      if (item.disabled) continue;
      if (excludeId != null && item.id === excludeId) continue;
      return item.id;
    }
  }
  function flipItems(items, activeId, shouldInsertNullItem = false) {
    const index2 = items.findIndex((item) => item.id === activeId);
    return [
      ...items.slice(index2 + 1),
      ...shouldInsertNullItem ? [NULL_ITEM] : [],
      ...items.slice(0, index2)
    ];
  }
  function groupItemsByRows(items) {
    const rows = [];
    for (const item of items) {
      const row = rows.find((currentRow) => currentRow[0]?.rowId === item.rowId);
      if (row) row.push(item);
      else rows.push([item]);
    }
    return rows;
  }
  function getMaxRowLength(array) {
    let maxLength = 0;
    for (const { length } of array) if (length > maxLength) maxLength = length;
    return maxLength;
  }
  function createEmptyItem(rowId) {
    return {
      id: "__EMPTY_ITEM__",
      disabled: true,
      rowId
    };
  }
  function normalizeRows(rows, activeId, focusShift) {
    const maxLength = getMaxRowLength(rows);
    for (const row of rows) for (let i2 = 0; i2 < maxLength; i2 += 1) {
      const item = row[i2];
      if (!item || focusShift && item.disabled) {
        const previousItem = i2 === 0 && focusShift ? findFirstEnabledItem(row) : row[i2 - 1];
        row[i2] = previousItem && activeId !== previousItem.id && focusShift ? previousItem : createEmptyItem(previousItem?.rowId);
      }
    }
    return rows;
  }
  function verticalizeItems(items) {
    const rows = groupItemsByRows(items);
    const maxLength = getMaxRowLength(rows);
    const verticalized = [];
    for (let i2 = 0; i2 < maxLength; i2 += 1) for (const row of rows) {
      const item = row[i2];
      if (item) verticalized.push({
        ...item,
        rowId: item.rowId ? `${i2}` : void 0
      });
    }
    return verticalized;
  }
  function createCompositeStore(props = {}) {
    const syncState = props.store?.getState();
    const collection = createCollectionStore(props);
    const activeId = defaultValue(props.activeId, syncState?.activeId, props.defaultActiveId);
    const composite = createStore({
      ...collection.getState(),
      id: defaultValue(props.id, syncState?.id) ?? `id-${Math.random().toString(36).slice(2, 8)}`,
      activeId,
      baseElement: defaultValue(syncState?.baseElement, null),
      includesBaseElement: defaultValue(props.includesBaseElement, syncState?.includesBaseElement, activeId === null),
      moves: defaultValue(syncState?.moves, 0),
      orientation: defaultValue(props.orientation, syncState?.orientation, "both"),
      rtl: defaultValue(props.rtl, syncState?.rtl, false),
      virtualFocus: defaultValue(props.virtualFocus, syncState?.virtualFocus, false),
      focusLoop: defaultValue(props.focusLoop, syncState?.focusLoop, false),
      focusWrap: defaultValue(props.focusWrap, syncState?.focusWrap, false),
      focusShift: defaultValue(props.focusShift, syncState?.focusShift, false)
    }, collection, props.store);
    setup(composite, () => sync2(composite, ["renderedItems", "activeId"], (state) => {
      composite.setState("activeId", (activeId2) => {
        if (activeId2 !== void 0) return activeId2;
        return findFirstEnabledItem(state.renderedItems)?.id;
      });
    }));
    const getNextId = (direction = "next", options = {}) => {
      const defaultState = composite.getState();
      const { skip = 0, activeId: activeId2 = defaultState.activeId, focusShift = defaultState.focusShift, focusLoop = defaultState.focusLoop, focusWrap = defaultState.focusWrap, includesBaseElement = defaultState.includesBaseElement, renderedItems = defaultState.renderedItems, rtl = defaultState.rtl } = options;
      const isVerticalDirection = direction === "up" || direction === "down";
      const isNextDirection = direction === "next" || direction === "down";
      const canReverse = isNextDirection ? rtl && !isVerticalDirection : !rtl || isVerticalDirection;
      const canShift = focusShift && !skip;
      if (!skip && !focusWrap && !includesBaseElement && activeId2 != null) {
        if (!isVerticalDirection ? true : !canShift && !renderedItems.some((item) => item.rowId != null)) {
          const activeIndex2 = renderedItems.findIndex((item) => item.id === activeId2);
          const activeItem2 = renderedItems[activeIndex2];
          if (activeItem2) {
            const step = canReverse ? -1 : 1;
            const nextId2 = findEnabledItemId({
              items: renderedItems,
              fromIndex: activeIndex2 + step,
              step,
              rowId: activeItem2.rowId,
              excludeId: activeId2
            });
            if (nextId2 !== void 0) return nextId2;
            if (!(focusLoop && (isVerticalDirection ? focusLoop !== "horizontal" : focusLoop !== "vertical"))) return void 0;
            return findEnabledItemId({
              items: renderedItems,
              fromIndex: step === 1 ? 0 : renderedItems.length - 1,
              step,
              rowId: activeItem2.rowId,
              excludeId: activeId2
            });
          }
        }
      }
      let items = !isVerticalDirection ? renderedItems : flatten2DArray(normalizeRows(groupItemsByRows(renderedItems), activeId2, canShift));
      items = canReverse ? reverseArray(items) : items;
      items = isVerticalDirection ? verticalizeItems(items) : items;
      if (activeId2 == null) return findFirstEnabledItem(items)?.id;
      const activeItem = items.find((item) => item.id === activeId2);
      if (!activeItem) return findFirstEnabledItem(items)?.id;
      const isGrid2 = items.some((item) => item.rowId);
      const activeIndex = items.indexOf(activeItem);
      const nextItems = items.slice(activeIndex + 1);
      const nextItemsInRow = getItemsInRow(nextItems, activeItem.rowId);
      if (skip) {
        const nextEnabledItemsInRow = getEnabledItems(nextItemsInRow, activeId2);
        return (nextEnabledItemsInRow.slice(skip)[0] || nextEnabledItemsInRow[nextEnabledItemsInRow.length - 1])?.id;
      }
      const canLoop = focusLoop && (isVerticalDirection ? focusLoop !== "horizontal" : focusLoop !== "vertical");
      const canWrap = isGrid2 && focusWrap && (isVerticalDirection ? focusWrap !== "horizontal" : focusWrap !== "vertical");
      const hasNullItem = isNextDirection ? (!isGrid2 || isVerticalDirection) && canLoop && includesBaseElement : isVerticalDirection ? includesBaseElement : false;
      if (canLoop) return findFirstEnabledItem(flipItems(canWrap && !hasNullItem ? items : getItemsInRow(items, activeItem.rowId), activeId2, hasNullItem), activeId2)?.id;
      if (canWrap) {
        const nextItem2 = findFirstEnabledItem(hasNullItem ? nextItemsInRow : nextItems, activeId2);
        return hasNullItem ? nextItem2?.id || null : nextItem2?.id;
      }
      const nextItem = findFirstEnabledItem(nextItemsInRow, activeId2);
      if (!nextItem && hasNullItem) return null;
      return nextItem?.id;
    };
    const getNextIdFromOptions = (direction, options) => {
      if (typeof options === "number") return getNextId(direction, { skip: options });
      return getNextId(direction, options);
    };
    return {
      ...collection,
      ...composite,
      setBaseElement: (element) => composite.setState("baseElement", element),
      setActiveId: (id) => composite.setState("activeId", id),
      move: (id) => {
        if (id === void 0) return;
        composite.setState("activeId", id);
        composite.setState("moves", (moves) => moves + 1);
      },
      first: () => findFirstEnabledItem(composite.getState().renderedItems)?.id,
      last: () => findFirstEnabledItem(reverseArray(composite.getState().renderedItems))?.id,
      next: (options) => getNextIdFromOptions("next", options),
      previous: (options) => getNextIdFromOptions("previous", options),
      down: (options) => getNextIdFromOptions("down", options),
      up: (options) => getNextIdFromOptions("up", options)
    };
  }

  // node_modules/@ariakit/react-components/dist/composite/utils.js
  var findFirstEnabledItem2 = findFirstEnabledItem;
  var groupItemsByRows2 = groupItemsByRows;
  function getEnabledItem(store2, id) {
    if (!id) return null;
    return store2.item(id) || null;
  }
  function selectTextField(element, collapseToEnd = false) {
    if (isTextField(element)) element.setSelectionRange(collapseToEnd ? element.value.length : 0, element.value.length);
    else if (element.isContentEditable) {
      const selection = getDocument(element).getSelection();
      selection?.selectAllChildren(element);
      if (collapseToEnd) selection?.collapseToEnd();
    }
  }
  var FOCUS_SILENTLY = /* @__PURE__ */ Symbol("FOCUS_SILENTLY");
  function focusSilently(element) {
    element[FOCUS_SILENTLY] = true;
    element.focus({ preventScroll: true });
  }
  function silentlyFocused(element) {
    const isSilentlyFocused = element[FOCUS_SILENTLY];
    delete element[FOCUS_SILENTLY];
    return isSilentlyFocused;
  }
  function isItem(store2, element, exclude) {
    if (!element) return false;
    if (element === exclude) return false;
    const item = store2.item(element.id);
    if (!item) return false;
    if (exclude && item.element === exclude) return false;
    return true;
  }

  // node_modules/@ariakit/react-components/dist/composite/composite-item.js
  var import_react22 = __toESM(require_react(), 1);
  var import_jsx_runtime149 = __toESM(require_jsx_runtime(), 1);

  // node_modules/@ariakit/react-store/dist/index.js
  var React60 = __toESM(require_react(), 1);
  var import_shim2 = __toESM(require_shim(), 1);
  var noopSubscribe = () => () => {
  };
  function useStoreState(store2, keyOrSelector = identity) {
    const storeSubscribe = React60.useCallback((callback) => {
      if (!store2) return noopSubscribe();
      return subscribe2(store2, null, callback);
    }, [store2]);
    const getSnapshot = () => {
      const key = typeof keyOrSelector === "string" ? keyOrSelector : null;
      const selector2 = typeof keyOrSelector === "function" ? keyOrSelector : null;
      const state = store2?.getState();
      if (selector2) return selector2(state);
      if (!state) return;
      if (!key) return;
      if (!hasOwnProperty(state, key)) return;
      return state[key];
    };
    return (0, import_shim2.useSyncExternalStore)(storeSubscribe, getSnapshot, getSnapshot);
  }
  function useStoreStateObject(store2, object) {
    const objRef = React60.useRef({});
    const storeSubscribe = React60.useCallback((callback) => {
      if (!store2) return noopSubscribe();
      return subscribe2(store2, null, callback);
    }, [store2]);
    const getSnapshot = () => {
      const state = store2?.getState();
      let updated = false;
      const obj = objRef.current;
      for (const prop in object) {
        const keyOrSelector = object[prop];
        if (typeof keyOrSelector === "function") {
          const value = keyOrSelector(state);
          if (!Object.is(value, obj[prop])) {
            obj[prop] = value;
            updated = true;
          }
        }
        if (typeof keyOrSelector === "string") {
          if (!state) continue;
          if (!hasOwnProperty(state, keyOrSelector)) continue;
          const value = state[keyOrSelector];
          if (!Object.is(value, obj[prop])) {
            obj[prop] = value;
            updated = true;
          }
        }
      }
      if (updated) objRef.current = { ...obj };
      return objRef.current;
    };
    return (0, import_shim2.useSyncExternalStore)(storeSubscribe, getSnapshot, getSnapshot);
  }
  function useStoreProps(store2, props, key, setKey) {
    const value = hasOwnProperty(props, key) ? props[key] : void 0;
    const propsRef = useLiveRef({
      value,
      setValue: setKey ? props[setKey] : void 0
    });
    useSafeLayoutEffect(() => {
      return sync2(store2, [key], (state, prev) => {
        const { value: value2, setValue } = propsRef.current;
        if (!setValue) return;
        if (state[key] === prev[key]) return;
        if (state[key] === value2) return;
        setValue(state[key]);
      });
    }, [store2, key]);
    useSafeLayoutEffect(() => {
      if (value === void 0) return;
      store2.setState(key, value);
      return batch(store2, [key], () => {
        if (value === void 0) return;
        store2.setState(key, value);
      });
    });
  }
  function useStore2(createStore2, props) {
    const [store2, setStore] = React60.useState(() => createStore2(props));
    useSafeLayoutEffect(() => init(store2), [store2]);
    const useState88 = React60.useCallback((keyOrSelector) => useStoreState(store2, keyOrSelector), [store2]);
    return [React60.useMemo(() => ({
      ...store2,
      useState: useState88
    }), [store2, useState88]), useEvent(() => {
      setStore((store3) => createStore2({
        ...props,
        ...store3.getState()
      }));
    })];
  }

  // node_modules/@ariakit/react-components/dist/composite/composite-item.js
  var TagName4 = "button";
  function isEditableElement(element) {
    if (isTextbox(element)) return true;
    return element.tagName === "INPUT" && !isButton(element);
  }
  function getNextPageOffset(scrollingElement, pageUp = false) {
    const height = scrollingElement.clientHeight;
    const { top } = scrollingElement.getBoundingClientRect();
    const pageSize = Math.max(height * 0.875, height - 40) * 1.5;
    const pageOffset = pageUp ? height - pageSize + top : pageSize + top;
    if (scrollingElement.tagName === "HTML") return pageOffset + scrollingElement.scrollTop;
    return pageOffset;
  }
  function getItemOffset(itemElement, pageUp = false) {
    const { top } = itemElement.getBoundingClientRect();
    if (pageUp) return top + itemElement.clientHeight;
    return top;
  }
  function findNextPageItemId(element, store2, next, pageUp = false) {
    if (!store2) return;
    if (!next) return;
    const { renderedItems } = store2.getState();
    const scrollingElement = getScrollingElement(element);
    if (!scrollingElement) return;
    const nextPageOffset = getNextPageOffset(scrollingElement, pageUp);
    let id;
    let prevDifference;
    for (let i2 = 0; i2 < renderedItems.length; i2 += 1) {
      const previousId = id;
      id = next(i2);
      if (!id) break;
      if (id === previousId) continue;
      const itemElement = getEnabledItem(store2, id)?.element;
      if (!itemElement) continue;
      const difference = getItemOffset(itemElement, pageUp) - nextPageOffset;
      const absDifference = Math.abs(difference);
      if (pageUp && difference <= 0 || !pageUp && difference >= 0) {
        if (prevDifference !== void 0 && prevDifference < absDifference) id = previousId;
        break;
      }
      prevDifference = absDifference;
    }
    return id;
  }
  function targetIsAnotherItem(event, store2) {
    if (isSelfTarget(event)) return false;
    return isItem(store2, event.target);
  }
  var useCompositeItem = createHook(function useCompositeItem2({ store: store2, rowId: rowIdProp, preventScrollOnKeyDown = false, moveOnKeyPress = true, tabbable: tabbable2 = false, getItem: getItemProp, "aria-setsize": ariaSetSizeProp, "aria-posinset": ariaPosInSetProp, ...props }) {
    const context = useCompositeScopedContext();
    store2 = store2 || context;
    const id = useId5(props.id);
    const ref = (0, import_react22.useRef)(null);
    const row = (0, import_react22.useContext)(CompositeRowContext);
    const trulyDisabled = disabledFromProps(props) && !props.accessibleWhenDisabled;
    const shouldRegisterItem = props.shouldRegisterItem;
    const getRowId = (state) => {
      if (rowIdProp) return rowIdProp;
      if (!state) return;
      if (!row?.baseElement) return;
      if (row.baseElement !== state.baseElement) return;
      return row.id;
    };
    const { rowId, baseElement, isActiveItem, ariaSetSize, ariaPosInSet, isTabbable } = useStoreStateObject(store2, {
      rowId: getRowId,
      baseElement(state) {
        return state?.baseElement || void 0;
      },
      isActiveItem(state) {
        return !!state && state.activeId === id;
      },
      ariaSetSize(state) {
        if (ariaSetSizeProp != null) return ariaSetSizeProp;
        if (!state) return;
        if (!row?.ariaSetSize) return;
        if (row.baseElement !== state.baseElement) return;
        return row.ariaSetSize;
      },
      ariaPosInSet(state) {
        if (ariaPosInSetProp != null) return ariaPosInSetProp;
        if (!state) return;
        if (!row?.ariaPosInSet) return;
        if (row.baseElement !== state.baseElement) return;
        const rowId2 = getRowId(state);
        const itemsInRow = state.renderedItems.filter((item) => item.rowId === rowId2);
        return row.ariaPosInSet + itemsInRow.findIndex((item) => item.id === id);
      },
      isTabbable(state) {
        if (!state?.renderedItems.length) return true;
        if (state.virtualFocus) return false;
        if (tabbable2) return true;
        if (state.activeId === null) return false;
        const item = store2?.item(state.activeId);
        if (item?.disabled) return true;
        if (!item?.element) return true;
        return state.activeId === id;
      }
    });
    const getItem = (0, import_react22.useCallback)((item) => {
      const nextItem = {
        ...item,
        id: id || item.id,
        rowId,
        disabled: trulyDisabled,
        children: item.element?.textContent
      };
      if (getItemProp) return getItemProp(nextItem);
      return nextItem;
    }, [
      id,
      rowId,
      trulyDisabled,
      getItemProp
    ]);
    const onFocusProp = props.onFocus;
    const hasFocusedComposite = (0, import_react22.useRef)(false);
    const cancelScheduledFocusRedirectRef = (0, import_react22.useRef)(null);
    const onFocus = useEvent((event) => {
      onFocusProp?.(event);
      if (event.defaultPrevented) return;
      if (isPortalEvent(event)) return;
      if (!id) return;
      if (!store2) return;
      if (targetIsAnotherItem(event, store2)) return;
      const { virtualFocus, baseElement: baseElement2 } = store2.getState();
      store2.setActiveId(id);
      if (isTextbox(event.currentTarget)) selectTextField(event.currentTarget);
      if (!virtualFocus) return;
      if (!isSelfTarget(event)) return;
      if (isEditableElement(event.currentTarget)) return;
      const redirectFocusToBaseElement = (currentTarget2, relatedTarget2, baseElement3) => {
        if (isSafari() && currentTarget2.hasAttribute("data-autofocus")) currentTarget2.scrollIntoView({
          block: "nearest",
          inline: "nearest"
        });
        hasFocusedComposite.current = true;
        if (relatedTarget2 === baseElement3 || isItem(store2, relatedTarget2)) focusSilently(baseElement3);
        else baseElement3.focus();
      };
      if (baseElement2?.isConnected) {
        redirectFocusToBaseElement(event.currentTarget, event.relatedTarget, baseElement2);
        return;
      }
      if (shouldRegisterItem === false) return;
      const { currentTarget, relatedTarget } = event;
      const cancelScheduledFocusRedirect = () => {
        cancelScheduledFocusRedirectRef.current?.();
        cancelScheduledFocusRedirectRef.current = null;
      };
      cancelScheduledFocusRedirect();
      cancelScheduledFocusRedirectRef.current = subscribe2(store2, null, () => {
        if (getActiveElement(currentTarget) !== currentTarget) {
          cancelScheduledFocusRedirect();
          return;
        }
        const state = store2.getState();
        const nextBaseElement = state.baseElement;
        if (!nextBaseElement?.isConnected) return;
        cancelScheduledFocusRedirect();
        if (!state.virtualFocus) return;
        redirectFocusToBaseElement(currentTarget, relatedTarget, nextBaseElement);
      });
    });
    const onBlurCaptureProp = props.onBlurCapture;
    const onBlurCapture = useEvent((event) => {
      onBlurCaptureProp?.(event);
      if (event.defaultPrevented) return;
      if (store2?.getState()?.virtualFocus && hasFocusedComposite.current) {
        hasFocusedComposite.current = false;
        event.preventDefault();
        event.stopPropagation();
      }
    });
    const onKeyDownProp = props.onKeyDown;
    const preventScrollOnKeyDownProp = useBooleanEvent(preventScrollOnKeyDown);
    const moveOnKeyPressProp = useBooleanEvent(moveOnKeyPress);
    const onKeyDown = useEvent((event) => {
      onKeyDownProp?.(event);
      if (event.defaultPrevented) return;
      if (!isSelfTarget(event)) return;
      if (!store2) return;
      const { currentTarget } = event;
      const state = store2.getState();
      const isGrid2 = !!store2.item(id)?.rowId;
      const isVertical = state.orientation !== "horizontal";
      const isHorizontal = state.orientation !== "vertical";
      const canHomeEnd = () => {
        if (isGrid2) return true;
        if (isHorizontal) return true;
        if (!state.baseElement) return true;
        if (!isTextField(state.baseElement)) return true;
        return false;
      };
      const action = {
        ArrowUp: (isGrid2 || isVertical) && store2.up,
        ArrowRight: (isGrid2 || isHorizontal) && store2.next,
        ArrowDown: (isGrid2 || isVertical) && store2.down,
        ArrowLeft: (isGrid2 || isHorizontal) && store2.previous,
        Home: () => {
          if (!canHomeEnd()) return;
          if (!isGrid2 || event.ctrlKey) return store2?.first();
          return store2?.previous(-1);
        },
        End: () => {
          if (!canHomeEnd()) return;
          if (!isGrid2 || event.ctrlKey) return store2?.last();
          return store2?.next(-1);
        },
        PageUp: () => {
          return findNextPageItemId(currentTarget, store2, store2?.up, true);
        },
        PageDown: () => {
          return findNextPageItemId(currentTarget, store2, store2?.down);
        }
      }[event.key];
      if (action) {
        if (isTextbox(currentTarget)) {
          const selection = getTextboxSelection(currentTarget);
          const isLeft = isHorizontal && event.key === "ArrowLeft";
          const isRight = isHorizontal && event.key === "ArrowRight";
          const isUp = isVertical && event.key === "ArrowUp";
          const isDown = isVertical && event.key === "ArrowDown";
          if (isRight || isDown) {
            const { length: valueLength } = getTextboxValue(currentTarget);
            if (selection.end !== valueLength) return;
          } else if ((isLeft || isUp) && selection.start !== 0) return;
        }
        const nextId2 = action();
        if (preventScrollOnKeyDownProp(event) || nextId2 !== void 0) {
          if (!moveOnKeyPressProp(event)) return;
          event.preventDefault();
          store2.move(nextId2);
        }
      }
    });
    const providerValue = (0, import_react22.useMemo)(() => ({
      id,
      baseElement
    }), [id, baseElement]);
    props = useWrapElement(props, (element) => /* @__PURE__ */ (0, import_jsx_runtime149.jsx)(CompositeItemContext.Provider, {
      value: providerValue,
      children: element
    }), [providerValue]);
    props = {
      "data-active-item": isActiveItem || void 0,
      ...props,
      id,
      ref: useMergeRefs(ref, props.ref),
      tabIndex: isTabbable ? props.tabIndex : -1,
      onFocus,
      onBlurCapture,
      onKeyDown
    };
    props = useCommand(props);
    props = useCollectionItem({
      store: store2,
      ...props,
      getItem,
      shouldRegisterItem: id ? shouldRegisterItem : false
    });
    return removeUndefinedValues({
      ...props,
      "aria-setsize": ariaSetSize,
      "aria-posinset": ariaPosInSet
    });
  });
  var CompositeItem = memo5(forwardRef43(function CompositeItem2(props) {
    return createElement5(TagName4, useCompositeItem(props));
  }));

  // node_modules/@ariakit/react-components/dist/composite/composite.js
  var import_react23 = __toESM(require_react(), 1);
  var import_jsx_runtime150 = __toESM(require_jsx_runtime(), 1);
  var TagName5 = "div";
  function isGrid(items) {
    return items.some((item) => !!item.rowId);
  }
  function isPrintableKey(event) {
    const target = event.target;
    if (target && !isTextField(target)) return false;
    return event.key.length === 1 && !event.ctrlKey && !event.metaKey;
  }
  function isModifierKey(event) {
    return event.key === "Shift" || event.key === "Control" || event.key === "Alt" || event.key === "Meta";
  }
  function useKeyboardEventProxy(store2, onKeyboardEvent, previousElementRef) {
    return useEvent((event) => {
      onKeyboardEvent?.(event);
      if (event.defaultPrevented) return;
      if (event.isPropagationStopped()) return;
      if (!isSelfTarget(event)) return;
      if (isModifierKey(event)) return;
      if (isPrintableKey(event)) return;
      const activeElement2 = getEnabledItem(store2, store2.getState().activeId)?.element;
      if (!activeElement2) return;
      const { view, ...eventInit } = event;
      if (activeElement2 !== previousElementRef?.current) activeElement2.focus();
      if (!fireKeyboardEvent(activeElement2, event.type, eventInit)) event.preventDefault();
      if (event.currentTarget.contains(activeElement2)) event.stopPropagation();
    });
  }
  function findFirstEnabledItemInTheLastRow(items) {
    return findFirstEnabledItem2(flatten2DArray(reverseArray(groupItemsByRows2(items))));
  }
  function withBaseScrollPreserved(store2, callback) {
    const { virtualFocus, baseElement } = store2.getState();
    if (!virtualFocus || !baseElement || !isTextField(baseElement)) {
      callback();
      return;
    }
    const savedScrollLeft = baseElement.scrollLeft;
    const savedScrollTop = baseElement.scrollTop;
    callback();
    baseElement.scrollLeft = savedScrollLeft;
    baseElement.scrollTop = savedScrollTop;
  }
  function useScheduleFocus(store2) {
    const [scheduled, setScheduled] = (0, import_react23.useState)(false);
    const schedule2 = (0, import_react23.useCallback)(() => setScheduled(true), []);
    const activeItem = useStoreState(store2, (state) => scheduled ? getEnabledItem(store2, state.activeId) : null);
    (0, import_react23.useEffect)(() => {
      const activeElement2 = activeItem?.element;
      if (!scheduled) return;
      if (!activeElement2) return;
      setScheduled(false);
      withBaseScrollPreserved(store2, () => {
        activeElement2.focus({ preventScroll: true });
      });
    }, [
      store2,
      activeItem,
      scheduled
    ]);
    return schedule2;
  }
  var CompositeFocusOnMove = memo5(function CompositeFocusOnMove2({ store: store2, focusOnMove, previousElementRef }) {
    const moves = useStoreState(store2, "moves");
    const baseElement = useStoreState(store2, "baseElement");
    (0, import_react23.useEffect)(() => {
      if (!moves) return;
      if (!focusOnMove) return;
      const { activeId } = store2.getState();
      const itemElement = getEnabledItem(store2, activeId)?.element;
      if (!itemElement) return;
      withBaseScrollPreserved(store2, () => focusIntoView(itemElement));
    }, [
      store2,
      moves,
      focusOnMove
    ]);
    useSafeLayoutEffect(() => {
      if (!moves) return;
      if (!baseElement) return;
      const { activeId } = store2.getState();
      if (!(activeId === null)) return;
      const previousElement = previousElementRef.current;
      previousElementRef.current = null;
      if (previousElement) fireBlurEvent(previousElement, { relatedTarget: baseElement });
      if (!hasFocus(baseElement)) baseElement.focus();
    }, [
      store2,
      moves,
      baseElement
    ]);
    return null;
  });
  var useComposite = createHook(function useComposite2({ store: store2, composite = true, focusOnMove = composite, moveOnKeyPress = true, ...props }) {
    const context = useCompositeProviderContext();
    store2 = store2 || context;
    invariant(store2, "Composite must receive a `store` prop or be wrapped in a CompositeProvider component.");
    const ref = (0, import_react23.useRef)(null);
    const previousElementRef = (0, import_react23.useRef)(null);
    const scheduleFocus = useScheduleFocus(store2);
    const [, setBaseElement] = useTransactionState(composite ? store2.setBaseElement : null);
    const virtualFocus = useStoreState(store2, "virtualFocus");
    const activeId = useStoreState(store2, (state) => state.virtualFocus ? state.activeId : null);
    useSafeLayoutEffect(() => {
      if (!store2) return;
      if (!composite) return;
      if (!virtualFocus) return;
      const previousElement = previousElementRef.current;
      previousElementRef.current = null;
      if (!previousElement) return;
      const relatedTarget = getEnabledItem(store2, activeId)?.element || getActiveElement(previousElement);
      if (relatedTarget === previousElement) return;
      fireBlurEvent(previousElement, { relatedTarget });
    }, [
      store2,
      activeId,
      virtualFocus,
      composite
    ]);
    const onKeyDownCapture = useKeyboardEventProxy(store2, props.onKeyDownCapture, previousElementRef);
    const onKeyUpCapture = useKeyboardEventProxy(store2, props.onKeyUpCapture, previousElementRef);
    const onFocusCaptureProp = props.onFocusCapture;
    const onFocusCapture = useEvent((event) => {
      onFocusCaptureProp?.(event);
      if (event.defaultPrevented) return;
      if (!store2) return;
      const { virtualFocus: virtualFocus2 } = store2.getState();
      if (!virtualFocus2) return;
      const previousActiveElement = event.relatedTarget;
      const isSilentlyFocused = silentlyFocused(event.currentTarget);
      if (isSelfTarget(event) && isSilentlyFocused) {
        event.stopPropagation();
        previousElementRef.current = previousActiveElement;
      }
    });
    const onFocusProp = props.onFocus;
    const onFocus = useEvent((event) => {
      onFocusProp?.(event);
      if (event.defaultPrevented) return;
      if (!composite) return;
      if (!store2) return;
      const { relatedTarget } = event;
      const { virtualFocus: virtualFocus2 } = store2.getState();
      if (virtualFocus2) {
        if (isSelfTarget(event) && !isItem(store2, relatedTarget)) queueMicrotask(scheduleFocus);
      } else if (isSelfTarget(event)) store2.setActiveId(null);
    });
    const onBlurCaptureProp = props.onBlurCapture;
    const onBlurCapture = useEvent((event) => {
      onBlurCaptureProp?.(event);
      if (event.defaultPrevented) return;
      if (!store2) return;
      const { virtualFocus: virtualFocus2, activeId: activeId2 } = store2.getState();
      if (!virtualFocus2) return;
      const activeElement2 = getEnabledItem(store2, activeId2)?.element;
      const nextActiveElement = event.relatedTarget;
      const nextActiveElementIsItem = isItem(store2, nextActiveElement);
      const previousElement = previousElementRef.current;
      previousElementRef.current = null;
      if (isSelfTarget(event) && nextActiveElementIsItem) {
        if (nextActiveElement === activeElement2) {
          if (previousElement && previousElement !== nextActiveElement) fireBlurEvent(previousElement, event);
        } else if (activeElement2) fireBlurEvent(activeElement2, event);
        else if (previousElement) fireBlurEvent(previousElement, event);
        event.stopPropagation();
      } else if (!isItem(store2, event.target) && activeElement2) fireBlurEvent(activeElement2, event);
    });
    const onKeyDownProp = props.onKeyDown;
    const moveOnKeyPressProp = useBooleanEvent(moveOnKeyPress);
    const onKeyDown = useEvent((event) => {
      onKeyDownProp?.(event);
      if (event.nativeEvent.isComposing) return;
      if (event.defaultPrevented) return;
      if (!store2) return;
      if (!isSelfTarget(event)) return;
      const { orientation, renderedItems, activeId: activeId2, rtl } = store2.getState();
      if (getEnabledItem(store2, activeId2)?.element?.isConnected) return;
      const isVertical = orientation !== "horizontal";
      const isHorizontal = orientation !== "vertical";
      const grid = isGrid(renderedItems);
      if ((event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === "Home" || event.key === "End") && isTextField(event.currentTarget)) return;
      const up = () => {
        if (grid) return findFirstEnabledItemInTheLastRow(renderedItems)?.id;
        return store2?.last();
      };
      const action = {
        ArrowUp: (grid || isVertical) && up,
        ArrowRight: (grid || isHorizontal) && (rtl ? store2.last : store2.first),
        ArrowDown: (grid || isVertical) && store2.first,
        ArrowLeft: (grid || isHorizontal) && (rtl ? store2.first : store2.last),
        Home: store2.first,
        End: store2.last,
        PageUp: store2.first,
        PageDown: store2.last
      }[event.key];
      if (action) {
        const id = action();
        if (id !== void 0) {
          if (!moveOnKeyPressProp(event)) return;
          event.preventDefault();
          store2.move(id);
        }
      }
    });
    props = useWrapElement(props, (element) => /* @__PURE__ */ (0, import_jsx_runtime150.jsxs)(CompositeScopedContextProvider, {
      value: store2,
      children: [element, composite && /* @__PURE__ */ (0, import_jsx_runtime150.jsx)(CompositeFocusOnMove, {
        store: store2,
        focusOnMove,
        previousElementRef
      })]
    }), [
      store2,
      composite,
      focusOnMove
    ]);
    props = {
      "aria-activedescendant": useStoreState(store2, (state) => {
        if (!store2) return;
        if (!composite) return;
        if (!state.virtualFocus) return;
        return getEnabledItem(store2, state.activeId)?.id;
      }),
      ...props,
      ref: useMergeRefs(ref, setBaseElement, props.ref),
      onKeyDownCapture,
      onKeyUpCapture,
      onFocusCapture,
      onFocus,
      onBlurCapture,
      onKeyDown
    };
    props = useFocusable({
      focusable: useStoreState(store2, (state) => composite && (state.virtualFocus || state.activeId === null)),
      ...props
    });
    return props;
  });
  var Composite6 = forwardRef43(function Composite7(props) {
    return createElement5(TagName5, useComposite(props));
  });

  // node_modules/@ariakit/react-components/dist/disclosure/disclosure-context.js
  var ctx4 = createStoreContext();
  var useDisclosureContext = ctx4.useContext;
  var useDisclosureScopedContext = ctx4.useScopedContext;
  var useDisclosureProviderContext = ctx4.useProviderContext;
  var DisclosureContextProvider = ctx4.ContextProvider;
  var DisclosureScopedContextProvider = ctx4.ScopedContextProvider;

  // node_modules/@ariakit/react-components/dist/dialog/dialog-context.js
  var import_react24 = __toESM(require_react(), 1);
  var ctx5 = createStoreContext([DisclosureContextProvider], [DisclosureScopedContextProvider]);
  var useDialogContext = ctx5.useContext;
  var useDialogScopedContext = ctx5.useScopedContext;
  var useDialogProviderContext = ctx5.useProviderContext;
  var DialogContextProvider = ctx5.ContextProvider;
  var DialogScopedContextProvider = ctx5.ScopedContextProvider;
  var DialogHeadingContext = (0, import_react24.createContext)(void 0);
  var DialogDescriptionContext = (0, import_react24.createContext)(void 0);

  // node_modules/@ariakit/react-components/dist/disclosure/disclosure-content.js
  var import_react25 = __toESM(require_react(), 1);
  var import_jsx_runtime151 = __toESM(require_jsx_runtime(), 1);
  var import_react_dom5 = __toESM(require_react_dom(), 1);
  var TagName6 = "div";
  function afterTimeout(timeoutMs, cb) {
    const timeoutId = setTimeout(cb, timeoutMs);
    return () => clearTimeout(timeoutId);
  }
  function parseCSSTime(time) {
    const value = time?.trim() || "0s";
    const multiplier = value.endsWith("ms") ? 1 : 1e3;
    const parsed = Number.parseFloat(value) * multiplier;
    return Number.isNaN(parsed) ? 0 : parsed;
  }
  function getEndTime(names, delays, durations) {
    const nameList = names.split(",");
    const delayList = delays.split(",");
    const durationList = durations.split(",");
    let endTime = 0;
    for (const [index2, name2] of nameList.entries()) {
      if (name2.trim() === "none") continue;
      const delay = parseCSSTime(delayList[index2 % delayList.length]);
      const duration = parseCSSTime(durationList[index2 % durationList.length]);
      endTime = Math.max(endTime, delay + duration);
    }
    return endTime;
  }
  function getElementEndTime(element) {
    const { transitionProperty, transitionDuration, transitionDelay, animationName, animationDuration, animationDelay } = getComputedStyle(element);
    return Math.max(getEndTime(transitionProperty, transitionDelay, transitionDuration), getEndTime(animationName, animationDelay, animationDuration));
  }
  function isHidden(mounted, hidden, alwaysVisible) {
    return !alwaysVisible && hidden !== false && (!mounted || !!hidden);
  }
  var useDisclosureContent = createHook(function useDisclosureContent2({ store: store2, alwaysVisible, unstable_otherElementRef: otherElementRef, ...props }) {
    const context = useDisclosureProviderContext();
    store2 = store2 || context;
    invariant(store2, "DisclosureContent must receive a `store` prop or be wrapped in a DisclosureProvider component.");
    const ref = (0, import_react25.useRef)(null);
    const id = useId5(props.id);
    const [transition, setTransition] = (0, import_react25.useState)(null);
    const open = useStoreState(store2, "open");
    const mounted = useStoreState(store2, "mounted");
    const animated2 = useStoreState(store2, "animated");
    const contentElement = useStoreState(store2, "contentElement");
    const otherElement = useStoreState(store2.disclosure, "contentElement");
    const hasClosedRef = (0, import_react25.useRef)(false);
    useSafeLayoutEffect(() => {
      if (!ref.current) return;
      store2?.setContentElement(ref.current);
    }, [store2]);
    useSafeLayoutEffect(() => {
      let previousAnimated;
      store2?.setState("animated", (animated3) => {
        previousAnimated = animated3;
        return true;
      });
      return () => {
        if (previousAnimated === void 0) return;
        store2?.setState("animated", previousAnimated);
      };
    }, [store2]);
    useSafeLayoutEffect(() => {
      if (!animated2) {
        if (!open) {
          hasClosedRef.current = true;
          setTransition(null);
        } else if (hasClosedRef.current) {
          hasClosedRef.current = false;
          setTransition("enter");
        }
        return;
      }
      if (!contentElement?.isConnected) {
        setTransition(null);
        return;
      }
      return afterPaint(() => {
        setTransition(open ? "enter" : mounted ? "leave" : null);
      });
    }, [
      animated2,
      contentElement,
      open,
      mounted
    ]);
    useSafeLayoutEffect(() => {
      if (!store2) return;
      if (!animated2) return;
      if (!transition) return;
      if (!contentElement) return;
      const stopAnimation = () => store2?.setState("animating", false);
      const stopAnimationSync = () => (0, import_react_dom5.flushSync)(stopAnimation);
      if (transition === "leave" && open) return;
      if (transition === "enter" && !open) return;
      if (typeof animated2 === "number") return afterTimeout(animated2, stopAnimationSync);
      const elements2 = [contentElement];
      if (otherElement) elements2.push(otherElement);
      const relatedElement = otherElementRef?.current;
      if (relatedElement) elements2.push(relatedElement);
      const timeout = Math.max(...elements2.map(getElementEndTime));
      if (!timeout) {
        if (transition === "enter") store2.setState("animated", false);
        stopAnimation();
        return;
      }
      return afterTimeout(Math.max(timeout - 1e3 / 60, 0), stopAnimationSync);
    }, [
      store2,
      animated2,
      contentElement,
      otherElement,
      otherElementRef,
      open,
      transition
    ]);
    props = useWrapElement(props, (element) => /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(DialogScopedContextProvider, {
      value: store2,
      children: element
    }), [store2]);
    const hidden = isHidden(mounted, props.hidden, alwaysVisible);
    const styleProp = props.style;
    const style = (0, import_react25.useMemo)(() => {
      if (hidden) return {
        ...styleProp,
        display: "none"
      };
      return styleProp;
    }, [hidden, styleProp]);
    props = {
      "data-open": open || void 0,
      "data-enter": transition === "enter" || void 0,
      "data-leave": transition === "leave" || void 0,
      hidden,
      ...props,
      id,
      ref: useMergeRefs(id ? store2.setContentElement : null, ref, props.ref),
      style
    };
    return removeUndefinedValues(props);
  });
  var DisclosureContentImpl = forwardRef43(function DisclosureContentImpl2(props) {
    return createElement5(TagName6, useDisclosureContent(props));
  });
  var DisclosureContent = forwardRef43(function DisclosureContent2({ unmountOnHide, ...props }) {
    const context = useDisclosureProviderContext();
    if (useStoreState(props.store || context, (state) => !unmountOnHide || state?.mounted) === false) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(DisclosureContentImpl, { ...props });
  });

  // node_modules/@ariakit/components/dist/disclosure/disclosure-store.js
  function createDisclosureStore(props = {}) {
    const store2 = mergeStore(props.store, omit2(props.disclosure, ["contentElement", "disclosureElement"]));
    throwOnConflictingProps(props, store2);
    const syncState = store2?.getState();
    const open = defaultValue(props.open, syncState?.open, props.defaultOpen, false);
    const animated2 = defaultValue(props.animated, syncState?.animated, false);
    const disclosure = createStore({
      open,
      animated: animated2,
      animating: !!animated2 && open,
      mounted: open,
      contentElement: defaultValue(syncState?.contentElement, null),
      disclosureElement: defaultValue(syncState?.disclosureElement, null)
    }, store2);
    setup(disclosure, () => sync2(disclosure, ["animated", "animating"], (state) => {
      if (state.animated) return;
      disclosure.setState("animating", false);
    }));
    setup(disclosure, () => subscribe2(disclosure, ["open"], () => {
      if (!disclosure.getState().animated) return;
      disclosure.setState("animating", true);
    }));
    setup(disclosure, () => sync2(disclosure, ["open", "animating"], (state) => {
      disclosure.setState("mounted", state.open || state.animating);
    }));
    return {
      ...disclosure,
      disclosure: props.disclosure,
      setOpen: (value) => disclosure.setState("open", value),
      show: () => disclosure.setState("open", true),
      hide: () => disclosure.setState("open", false),
      toggle: () => disclosure.setState("open", (open2) => !open2),
      stopAnimation: () => disclosure.setState("animating", false),
      setContentElement: (value) => disclosure.setState("contentElement", value),
      setDisclosureElement: (value) => disclosure.setState("disclosureElement", value)
    };
  }

  // node_modules/@ariakit/react-components/dist/disclosure/disclosure-store.js
  function useDisclosureStoreProps(store2, update4, props) {
    useUpdateEffect(update4, [props.store, props.disclosure]);
    useStoreProps(store2, props, "open", "setOpen");
    useStoreProps(store2, props, "mounted", "setMounted");
    useStoreProps(store2, props, "animated");
    return Object.assign(store2, { disclosure: props.disclosure });
  }

  // node_modules/@ariakit/react-components/dist/popover/popover-context.js
  var ctx6 = createStoreContext([DialogContextProvider], [DialogScopedContextProvider]);
  var usePopoverContext = ctx6.useContext;
  var usePopoverScopedContext = ctx6.useScopedContext;
  var usePopoverProviderContext = ctx6.useProviderContext;
  var PopoverContextProvider = ctx6.ContextProvider;
  var PopoverScopedContextProvider = ctx6.ScopedContextProvider;

  // node_modules/@ariakit/react-components/dist/combobox/combobox-context.js
  var import_react26 = __toESM(require_react(), 1);
  var ComboboxListRoleContext = (0, import_react26.createContext)(void 0);
  var ctx7 = createStoreContext([PopoverContextProvider, CompositeContextProvider], [PopoverScopedContextProvider, CompositeScopedContextProvider]);
  var useComboboxContext = ctx7.useContext;
  var useComboboxScopedContext = ctx7.useScopedContext;
  var useComboboxProviderContext = ctx7.useProviderContext;
  var ComboboxContextProvider = ctx7.ContextProvider;
  var ComboboxScopedContextProvider = ctx7.ScopedContextProvider;
  var ComboboxItemValueContext = (0, import_react26.createContext)(void 0);
  var ComboboxItemCheckedContext = (0, import_react26.createContext)(false);

  // node_modules/@ariakit/react-components/dist/collection/collection-store.js
  function useCollectionStoreProps(store2, update4, props) {
    useUpdateEffect(update4, [props.store]);
    useStoreProps(store2, props, "items", "setItems");
    return store2;
  }

  // node_modules/@ariakit/react-components/dist/composite/composite-store.js
  function useCompositeStoreOptions(props) {
    return {
      id: useId5(props.id),
      ...props
    };
  }
  function useCompositeStoreProps(store2, update4, props) {
    store2 = useCollectionStoreProps(store2, update4, props);
    useStoreProps(store2, props, "activeId", "setActiveId");
    useStoreProps(store2, props, "includesBaseElement");
    useStoreProps(store2, props, "virtualFocus");
    useStoreProps(store2, props, "orientation");
    useStoreProps(store2, props, "rtl");
    useStoreProps(store2, props, "focusLoop");
    useStoreProps(store2, props, "focusWrap");
    useStoreProps(store2, props, "focusShift");
    return store2;
  }

  // node_modules/@ariakit/components/dist/dialog/dialog-store.js
  function createDialogStore(props = {}) {
    return createDisclosureStore(props);
  }

  // node_modules/@ariakit/react-components/dist/dialog/dialog-store.js
  function useDialogStoreProps(store2, update4, props) {
    return useDisclosureStoreProps(store2, update4, props);
  }

  // node_modules/@ariakit/components/dist/popover/popover-store.js
  function createPopoverStore({ popover: otherPopover, ...props } = {}) {
    const store2 = mergeStore(props.store, omit2(otherPopover, [
      "arrowElement",
      "anchorElement",
      "contentElement",
      "popoverElement",
      "disclosureElement"
    ]));
    throwOnConflictingProps(props, store2);
    const syncState = store2?.getState();
    const dialog = createDialogStore({
      ...props,
      store: store2
    });
    const placement = defaultValue(props.placement, syncState?.placement, "bottom");
    const popover = createStore({
      ...dialog.getState(),
      placement,
      currentPlacement: placement,
      anchorElement: defaultValue(syncState?.anchorElement, null),
      popoverElement: defaultValue(syncState?.popoverElement, null),
      arrowElement: defaultValue(syncState?.arrowElement, null),
      rendered: /* @__PURE__ */ Symbol("rendered")
    }, dialog, store2);
    return {
      ...dialog,
      ...popover,
      setAnchorElement: (element) => popover.setState("anchorElement", element),
      setPopoverElement: (element) => popover.setState("popoverElement", element),
      setArrowElement: (element) => popover.setState("arrowElement", element),
      render: () => popover.setState("rendered", /* @__PURE__ */ Symbol("rendered"))
    };
  }

  // node_modules/@ariakit/react-components/dist/popover/popover-store.js
  function usePopoverStoreProps(store2, update4, props) {
    useUpdateEffect(update4, [props.popover]);
    useStoreProps(store2, props, "placement");
    return useDialogStoreProps(store2, update4, props);
  }

  // node_modules/@ariakit/react-components/dist/popover/popover-anchor.js
  var TagName7 = "div";
  var usePopoverAnchor = createHook(function usePopoverAnchor2({ store: store2, ...props }) {
    const context = usePopoverProviderContext();
    store2 = store2 || context;
    props = {
      ...props,
      ref: useMergeRefs(store2?.setAnchorElement, props.ref)
    };
    return props;
  });
  var PopoverAnchor = forwardRef43(function PopoverAnchor2(props) {
    return createElement5(TagName7, usePopoverAnchor(props));
  });

  // node_modules/@ariakit/react-components/dist/composite/composite-hover.js
  var import_react27 = __toESM(require_react(), 1);
  var TagName8 = "div";
  function hoveringInside(event) {
    const nextElement = event.relatedTarget;
    if (!isElement2(nextElement)) return false;
    return contains2(event.currentTarget, nextElement);
  }
  var symbol2 = /* @__PURE__ */ Symbol("composite-hover");
  function movingToAnotherItem(event) {
    const { relatedTarget } = event;
    if (!isElement2(relatedTarget)) return false;
    let dest = relatedTarget;
    do {
      if (hasOwnProperty(dest, symbol2) && dest[symbol2]) return true;
      dest = dest.parentElement;
    } while (dest);
    return false;
  }
  var useCompositeHover = createHook(function useCompositeHover2({ store: store2, focusOnHover = true, blurOnHoverEnd = !!focusOnHover, ...props }) {
    const context = useCompositeScopedContext();
    store2 = store2 || context;
    invariant(store2, "CompositeHover must be wrapped in a Composite component.");
    const isMouseMoving = useIsMouseMoving();
    const onMouseMoveProp = props.onMouseMove;
    const focusOnHoverProp = useBooleanEvent(focusOnHover);
    const onMouseMove = useEvent((event) => {
      onMouseMoveProp?.(event);
      if (event.defaultPrevented) return;
      if (!isMouseMoving()) return;
      if (!focusOnHoverProp(event)) return;
      if (!hasFocusWithin(event.currentTarget)) {
        const baseElement = store2?.getState().baseElement;
        if (baseElement && !hasFocus(baseElement)) baseElement.focus();
      }
      store2?.setActiveId(event.currentTarget.id);
    });
    const onMouseLeaveProp = props.onMouseLeave;
    const blurOnHoverEndProp = useBooleanEvent(blurOnHoverEnd);
    const onMouseLeave = useEvent((event) => {
      onMouseLeaveProp?.(event);
      if (event.defaultPrevented) return;
      if (!isMouseMoving()) return;
      if (hoveringInside(event)) return;
      if (movingToAnotherItem(event)) return;
      if (!focusOnHoverProp(event)) return;
      if (!blurOnHoverEndProp(event)) return;
      store2?.setActiveId(null);
      store2?.getState().baseElement?.focus();
    });
    const ref = (0, import_react27.useCallback)((element) => {
      if (!element) return;
      element[symbol2] = true;
    }, []);
    props = {
      ...props,
      ref: useMergeRefs(ref, props.ref),
      onMouseMove,
      onMouseLeave
    };
    return removeUndefinedValues(props);
  });
  var CompositeHover = memo5(forwardRef43(function CompositeHover2(props) {
    return createElement5(TagName8, useCompositeHover(props));
  }));

  // node_modules/@ariakit/react-components/dist/combobox/combobox.js
  var import_react28 = __toESM(require_react(), 1);
  var TagName9 = "input";
  function isFirstItemAutoSelected(items, activeValue, autoSelect) {
    if (!autoSelect) return false;
    return items.find((item) => !item.disabled && item.value)?.value === activeValue;
  }
  function hasCompletionString(value, activeValue) {
    if (!activeValue) return false;
    if (value == null) return false;
    const normalizedValue = normalizeString(value);
    const normalizedActiveValue = normalizeString(activeValue);
    if (normalizedValue.length !== value.length) return false;
    if (normalizedActiveValue.length !== activeValue.length) return false;
    return normalizedActiveValue.length > normalizedValue.length && normalizedActiveValue.toLowerCase().startsWith(normalizedValue.toLowerCase());
  }
  function isAriaAutoCompleteValue(value) {
    return value === "inline" || value === "list" || value === "both" || value === "none";
  }
  function getDefaultAutoSelectId(items) {
    return items.find((item) => {
      if (item.disabled) return false;
      return item.element?.getAttribute("role") !== "tab";
    })?.id;
  }
  var useCombobox = createHook(function useCombobox2({ store: store2, focusable: focusable2 = true, autoSelect: autoSelectProp = false, getAutoSelectId, setValueOnChange, showMinLength = 0, showOnChange, showOnMouseDown, showOnClick = showOnMouseDown, showOnKeyDown, showOnKeyPress = showOnKeyDown, blurActiveItemOnClick, setValueOnClick = true, moveOnKeyPress = true, autoComplete = "list", ...props }) {
    const context = useComboboxProviderContext();
    store2 = store2 || context;
    invariant(store2, "Combobox must receive a `store` prop or be wrapped in a ComboboxProvider component.");
    const ref = (0, import_react28.useRef)(null);
    const [valueUpdated, forceValueUpdate] = useForceUpdate2();
    const canAutoSelectRef = (0, import_react28.useRef)(false);
    const composingRef = (0, import_react28.useRef)(false);
    const autoSelect = useStoreState(store2, (state) => state.virtualFocus && autoSelectProp);
    const inline4 = autoComplete === "inline" || autoComplete === "both";
    const [canInline, setCanInline] = (0, import_react28.useState)(inline4);
    useUpdateLayoutEffect(() => {
      if (!inline4) return;
      setCanInline(true);
    }, [inline4]);
    const storeValue = useStoreState(store2, "value");
    const prevSelectedValueRef = (0, import_react28.useRef)(void 0);
    (0, import_react28.useEffect)(() => {
      return sync2(store2, ["selectedValue", "activeId"], (_, prev) => {
        prevSelectedValueRef.current = prev.selectedValue;
      });
    }, [store2]);
    const inlineActiveValue = useStoreState(store2, (state) => {
      if (!inline4) return;
      if (!canInline) return;
      if (state.activeValue && Array.isArray(state.selectedValue)) {
        if (state.selectedValue.includes(state.activeValue)) return;
        if (prevSelectedValueRef.current?.includes(state.activeValue)) return;
      }
      return state.activeValue;
    });
    const items = useStoreState(store2, "renderedItems");
    const open = useStoreState(store2, "open");
    const contentElement = useStoreState(store2, "contentElement");
    const value = (0, import_react28.useMemo)(() => {
      if (!inline4) return storeValue;
      if (!canInline) return storeValue;
      if (isFirstItemAutoSelected(items, inlineActiveValue, autoSelect)) {
        if (hasCompletionString(storeValue, inlineActiveValue)) return storeValue + (inlineActiveValue?.slice(storeValue.length) || "");
        return storeValue;
      }
      return inlineActiveValue || storeValue;
    }, [
      inline4,
      canInline,
      items,
      inlineActiveValue,
      autoSelect,
      storeValue
    ]);
    (0, import_react28.useEffect)(() => {
      const element = ref.current;
      if (!element) return;
      const onCompositeItemMove = () => setCanInline(true);
      element.addEventListener("combobox-item-move", onCompositeItemMove);
      return () => {
        element.removeEventListener("combobox-item-move", onCompositeItemMove);
      };
    }, []);
    (0, import_react28.useEffect)(() => {
      if (!inline4) return;
      if (!canInline) return;
      if (!inlineActiveValue) return;
      if (!isFirstItemAutoSelected(items, inlineActiveValue, autoSelect)) return;
      if (!hasCompletionString(storeValue, inlineActiveValue)) return;
      let cleanup = noop5;
      queueMicrotask(() => {
        const element = ref.current;
        if (!element) return;
        const { start: prevStart, end: prevEnd } = getTextboxSelection(element);
        const nextStart = storeValue.length;
        const nextEnd = inlineActiveValue.length;
        setSelectionRange(element, nextStart, nextEnd);
        cleanup = () => {
          if (!hasFocus(element)) return;
          const { start: start2, end } = getTextboxSelection(element);
          if (start2 !== nextStart) return;
          if (end !== nextEnd) return;
          setSelectionRange(element, prevStart, prevEnd);
        };
      });
      return () => cleanup();
    }, [
      valueUpdated,
      inline4,
      canInline,
      inlineActiveValue,
      items,
      autoSelect,
      storeValue
    ]);
    const getAutoSelectIdProp = useEvent(getAutoSelectId);
    const autoSelectIdRef = (0, import_react28.useRef)(null);
    const autoSelectMovedRef = (0, import_react28.useRef)(void 0);
    const userScrolledRef = (0, import_react28.useRef)(false);
    const isAutoScrollingRef = (0, import_react28.useRef)(false);
    (0, import_react28.useEffect)(() => {
      if (!open) return;
      if (!contentElement) return;
      const scrollingElement = getScrollingElement(contentElement);
      if (!scrollingElement) return;
      const onUserScroll = () => {
        canAutoSelectRef.current = false;
        userScrolledRef.current = true;
      };
      const onScroll = () => {
        if (!isAutoScrollingRef.current) userScrolledRef.current = true;
        if (!store2) return;
        if (!canAutoSelectRef.current) return;
        const { activeId } = store2.getState();
        if (activeId === null) return;
        if (activeId === autoSelectIdRef.current) return;
        canAutoSelectRef.current = false;
      };
      const options = {
        passive: true,
        capture: true
      };
      scrollingElement.addEventListener("wheel", onUserScroll, options);
      scrollingElement.addEventListener("touchmove", onUserScroll, options);
      scrollingElement.addEventListener("scroll", onScroll, options);
      return () => {
        scrollingElement.removeEventListener("wheel", onUserScroll, true);
        scrollingElement.removeEventListener("touchmove", onUserScroll, true);
        scrollingElement.removeEventListener("scroll", onScroll, true);
      };
    }, [
      open,
      contentElement,
      store2
    ]);
    useSafeLayoutEffect(() => {
      userScrolledRef.current = false;
      if (!storeValue) return;
      if (composingRef.current) return;
      canAutoSelectRef.current = true;
    }, [storeValue]);
    useSafeLayoutEffect(() => {
      if (autoSelect !== "always" && open) return;
      canAutoSelectRef.current = open;
    }, [autoSelect, open]);
    useSafeLayoutEffect(() => {
      if (open) return;
      autoSelectMovedRef.current = void 0;
    }, [open]);
    const resetValueOnSelect = useStoreState(store2, "resetValueOnSelect");
    useUpdateEffect(() => {
      const canAutoSelect = canAutoSelectRef.current;
      if (!store2) return;
      if (!open) return;
      if (!canAutoSelect && (!resetValueOnSelect || userScrolledRef.current)) return;
      const { baseElement, contentElement: contentElement2, activeId } = store2.getState();
      if (baseElement && !hasFocus(baseElement)) return;
      if (contentElement2?.hasAttribute("data-placing")) {
        const observer = new MutationObserver(forceValueUpdate);
        observer.observe(contentElement2, { attributeFilter: ["data-placing"] });
        return () => observer.disconnect();
      }
      if (autoSelect && canAutoSelect) {
        const userAutoSelectId = getAutoSelectIdProp(items);
        const autoSelectId = userAutoSelectId !== void 0 ? userAutoSelectId : getDefaultAutoSelectId(items) ?? store2.first();
        autoSelectIdRef.current = autoSelectId;
        const nextActiveId = autoSelectId ?? null;
        const nextActiveValue = store2.item(nextActiveId)?.value;
        const moved = autoSelectMovedRef.current;
        if (nextActiveId !== activeId || moved?.id !== nextActiveId || moved?.value !== nextActiveValue) {
          autoSelectMovedRef.current = {
            id: nextActiveId,
            value: nextActiveValue
          };
          store2.move(nextActiveId);
        } else store2.setState("activeValue", nextActiveValue);
      } else {
        const element = store2.item(activeId || store2.first())?.element;
        if (element && "scrollIntoView" in element) {
          isAutoScrollingRef.current = true;
          element.scrollIntoView({
            block: "nearest",
            inline: "nearest"
          });
          requestAnimationFrame(() => {
            isAutoScrollingRef.current = false;
          });
        }
      }
    }, [
      store2,
      open,
      valueUpdated,
      storeValue,
      autoSelect,
      resetValueOnSelect,
      getAutoSelectIdProp,
      items
    ]);
    (0, import_react28.useEffect)(() => {
      if (!inline4) return;
      const combobox = ref.current;
      if (!combobox) return;
      const elements2 = [combobox, contentElement].filter((value2) => !!value2);
      const onBlur2 = (event) => {
        if (elements2.every((el) => isFocusEventOutside(event, el))) store2?.setValue(value);
      };
      for (const element of elements2) element.addEventListener("focusout", onBlur2);
      return () => {
        for (const element of elements2) element.removeEventListener("focusout", onBlur2);
      };
    }, [
      inline4,
      contentElement,
      store2,
      value
    ]);
    const canShow = (event) => {
      return event.currentTarget.value.length >= showMinLength;
    };
    const onChangeProp = props.onChange;
    const showOnChangeProp = useBooleanEvent(showOnChange ?? canShow);
    const setValueOnChangeProp = useBooleanEvent(setValueOnChange ?? !store2.tag);
    const onChange = useEvent((event) => {
      onChangeProp?.(event);
      if (event.defaultPrevented) return;
      if (!store2) return;
      const currentTarget = event.currentTarget;
      const { value: value2, selectionStart, selectionEnd } = currentTarget;
      const nativeEvent = event.nativeEvent;
      canAutoSelectRef.current = true;
      if (isInputEvent(nativeEvent)) {
        if (nativeEvent.isComposing) {
          canAutoSelectRef.current = false;
          composingRef.current = true;
        }
        if (inline4) {
          const textInserted = nativeEvent.inputType === "insertText" || nativeEvent.inputType === "insertCompositionText";
          const caretAtEnd = selectionStart === value2.length;
          setCanInline(textInserted && caretAtEnd);
        }
      }
      if (setValueOnChangeProp(event)) {
        const isSameValue2 = value2 === store2.getState().value;
        store2.setValue(value2);
        queueMicrotask(() => {
          setSelectionRange(currentTarget, selectionStart, selectionEnd);
        });
        if (inline4 && autoSelect && isSameValue2) forceValueUpdate();
      }
      if (showOnChangeProp(event)) store2.show();
      if (!autoSelect || !canAutoSelectRef.current) store2.setActiveId(null);
    });
    const onCompositionEndProp = props.onCompositionEnd;
    const onCompositionEnd = useEvent((event) => {
      canAutoSelectRef.current = true;
      composingRef.current = false;
      onCompositionEndProp?.(event);
      if (event.defaultPrevented) return;
      if (!autoSelect) return;
      forceValueUpdate();
    });
    const onMouseDownProp = props.onMouseDown;
    const blurActiveItemOnClickProp = useBooleanEvent(blurActiveItemOnClick ?? (() => store2.getState().includesBaseElement));
    const setValueOnClickProp = useBooleanEvent(setValueOnClick);
    const showOnClickProp = useBooleanEvent(showOnClick ?? canShow);
    const onMouseDown = useEvent((event) => {
      onMouseDownProp?.(event);
      if (event.defaultPrevented) return;
      if (event.button) return;
      if (event.ctrlKey) return;
      if (!store2) return;
      if (blurActiveItemOnClickProp(event)) store2.setActiveId(null);
      if (setValueOnClickProp(event)) store2.setValue(value);
      if (showOnClickProp(event)) queueBeforeEvent(event.currentTarget, "mouseup", store2.show);
    });
    const onKeyDownProp = props.onKeyDown;
    const showOnKeyPressProp = useBooleanEvent(showOnKeyPress ?? canShow);
    const onKeyDown = useEvent((event) => {
      onKeyDownProp?.(event);
      if (!event.repeat) canAutoSelectRef.current = false;
      if (event.defaultPrevented) return;
      if (!store2) return;
      const { open: open2 } = store2.getState();
      if (open2 && event.key === "Enter") {
        event.preventDefault();
        return;
      }
      if (event.ctrlKey) return;
      if (event.altKey) return;
      if (event.shiftKey) return;
      if (event.metaKey) return;
      if (open2) return;
      if (event.key === "ArrowUp" || event.key === "ArrowDown") {
        if (showOnKeyPressProp(event)) {
          event.preventDefault();
          store2.show();
        }
      }
    });
    const onBlurProp = props.onBlur;
    const onBlur = useEvent((event) => {
      canAutoSelectRef.current = false;
      onBlurProp?.(event);
    });
    const id = useId5(props.id);
    const ariaAutoComplete = isAriaAutoCompleteValue(autoComplete) ? autoComplete : void 0;
    const isActiveItem = useStoreState(store2, (state) => state.activeId === null);
    props = {
      role: "combobox",
      "aria-autocomplete": ariaAutoComplete,
      "aria-haspopup": getPopupRole(contentElement, "listbox"),
      "aria-expanded": open,
      "aria-controls": contentElement?.id,
      "data-active-item": isActiveItem || void 0,
      value,
      ...props,
      id,
      ref: useMergeRefs(ref, props.ref),
      onChange,
      onCompositionEnd,
      onMouseDown,
      onKeyDown,
      onBlur
    };
    props = useComposite({
      store: store2,
      focusable: focusable2,
      ...props,
      moveOnKeyPress: (event) => {
        if (isFalsyBooleanCallback(moveOnKeyPress, event)) return false;
        if (inline4) setCanInline(true);
        return true;
      }
    });
    props = usePopoverAnchor({
      store: store2,
      ...props
    });
    return {
      autoComplete: "off",
      ...props
    };
  });
  var Combobox = forwardRef43(function Combobox2(props) {
    return createElement5(TagName9, useCombobox(props));
  });

  // node_modules/@ariakit/react-components/dist/combobox/combobox-item.js
  var import_react29 = __toESM(require_react(), 1);
  var import_jsx_runtime152 = __toESM(require_jsx_runtime(), 1);
  var TagName10 = "div";
  function isSelected(storeValue, itemValue) {
    if (itemValue == null) return;
    if (storeValue == null) return false;
    if (Array.isArray(storeValue)) return storeValue.includes(itemValue);
    return storeValue === itemValue;
  }
  function getItemRole(popupRole) {
    return getItemRoleByPopupRole(popupRole) ?? "option";
  }
  var useComboboxItem = createHook(function useComboboxItem2({ store: store2, value, hideOnClick, setValueOnClick, selectValueOnClick = true, resetValueOnSelect, focusOnHover = false, moveOnKeyPress = true, getItem: getItemProp, ...props }) {
    const context = useComboboxScopedContext();
    store2 = store2 || context;
    invariant(store2, "ComboboxItem must be wrapped in a ComboboxList or ComboboxPopover component.");
    const { resetValueOnSelectState, multiSelectable, selected } = useStoreStateObject(store2, {
      resetValueOnSelectState: "resetValueOnSelect",
      multiSelectable(state) {
        return Array.isArray(state.selectedValue);
      },
      selected(state) {
        return isSelected(state.selectedValue, value);
      }
    });
    const getItem = (0, import_react29.useCallback)((item) => {
      const nextItem = {
        ...item,
        value
      };
      if (getItemProp) return getItemProp(nextItem);
      return nextItem;
    }, [value, getItemProp]);
    setValueOnClick = setValueOnClick ?? !multiSelectable;
    hideOnClick = hideOnClick ?? (value != null && !multiSelectable);
    const onClickProp = props.onClick;
    const setValueOnClickProp = useBooleanEvent(setValueOnClick);
    const selectValueOnClickProp = useBooleanEvent(selectValueOnClick);
    const resetValueOnSelectProp = useBooleanEvent(resetValueOnSelect ?? resetValueOnSelectState ?? multiSelectable);
    const hideOnClickProp = useBooleanEvent(hideOnClick);
    const onClick = useEvent((event) => {
      onClickProp?.(event);
      if (event.defaultPrevented) return;
      if (isDownloading(event)) return;
      if (isOpeningInNewTab(event)) return;
      if (value != null) {
        if (selectValueOnClickProp(event)) {
          if (resetValueOnSelectProp(event)) store2?.resetValue();
          store2?.setSelectedValue((prevValue) => {
            if (!Array.isArray(prevValue)) return value;
            if (prevValue.includes(value)) return prevValue.filter((v2) => v2 !== value);
            return [...prevValue, value];
          });
        }
        if (setValueOnClickProp(event)) store2?.setValue(value);
      }
      if (hideOnClickProp(event)) store2?.hide();
    });
    const onKeyDownProp = props.onKeyDown;
    const onKeyDown = useEvent((event) => {
      onKeyDownProp?.(event);
      if (event.defaultPrevented) return;
      const baseElement = store2?.getState().baseElement;
      if (!baseElement) return;
      if (hasFocus(baseElement)) return;
      const printable = event.key.length === 1 && !event.ctrlKey && !event.metaKey;
      const paste = (!isApple() ? event.ctrlKey : event.metaKey) && event.key.toLowerCase() === "v";
      const deleteKey = event.key === "Backspace" || event.key === "Delete";
      if (printable || paste || deleteKey) {
        queueMicrotask(() => baseElement.focus());
        if (isTextField(baseElement)) store2?.setValue(baseElement.value);
      }
    });
    if (multiSelectable && selected != null) props = {
      "aria-selected": selected,
      ...props
    };
    props = useWrapElement(props, (element) => /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(ComboboxItemValueContext.Provider, {
      value,
      children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(ComboboxItemCheckedContext.Provider, {
        value: selected ?? false,
        children: element
      })
    }), [value, selected]);
    props = {
      role: getItemRole((0, import_react29.useContext)(ComboboxListRoleContext)),
      children: value,
      ...props,
      onClick,
      onKeyDown
    };
    const moveOnKeyPressProp = useBooleanEvent(moveOnKeyPress);
    props = useCompositeItem({
      store: store2,
      ...props,
      getItem,
      moveOnKeyPress: (event) => {
        if (!moveOnKeyPressProp(event)) return false;
        const moveEvent = new Event("combobox-item-move");
        store2?.getState().baseElement?.dispatchEvent(moveEvent);
        return true;
      }
    });
    props = useCompositeHover({
      store: store2,
      focusOnHover,
      ...props
    });
    return props;
  });
  var ComboboxItem = memo5(forwardRef43(function ComboboxItem2(props) {
    return createElement5(TagName10, useComboboxItem(props));
  }));

  // node_modules/@ariakit/react-components/dist/combobox/combobox-item-value.js
  var import_react30 = __toESM(require_react(), 1);
  var import_jsx_runtime153 = __toESM(require_jsx_runtime(), 1);
  var TagName11 = "span";
  function normalizeValue(value) {
    return normalizeString(value).toLowerCase();
  }
  function getOffsets(string, values) {
    const offsets = [];
    for (const value of values) {
      if (!value) continue;
      let pos = 0;
      const length = value.length;
      let index2 = string.indexOf(value, pos);
      while (index2 !== -1) {
        offsets.push([index2, length]);
        pos = index2 + 1;
        index2 = string.indexOf(value, pos);
      }
    }
    return offsets;
  }
  function mergeOverlappingOffsets(offsets) {
    offsets.sort(([a2], [b2]) => a2 - b2);
    const merged = [];
    for (const [offset4, length] of offsets) {
      const last = merged[merged.length - 1];
      if (last && offset4 < last[0] + last[1]) last[1] = Math.max(last[1], offset4 + length - last[0]);
      else merged.push([offset4, length]);
    }
    return merged;
  }
  function getNormalizedIndexes(itemValue) {
    const starts = [];
    const ends = [];
    let index2 = 0;
    for (const char of itemValue) {
      const normalizedLength = normalizeValue(char).length;
      for (let i2 = 0; i2 < normalizedLength; i2 += 1) {
        starts.push(i2 === 0 ? index2 : -1);
        ends.push(index2);
      }
      index2 += char.length;
    }
    starts.push(itemValue.length);
    ends.push(itemValue.length);
    let nextBoundary = itemValue.length;
    for (let i2 = starts.length - 1; i2 >= 0; i2 -= 1) {
      const start2 = starts[i2];
      if (start2 == null) continue;
      if (start2 === -1) starts[i2] = nextBoundary;
      else nextBoundary = start2;
    }
    return {
      starts,
      ends
    };
  }
  function toOriginalOffsets(itemValue, normalizedOffsets) {
    if (!normalizedOffsets.length) return normalizedOffsets;
    const { starts, ends } = getNormalizedIndexes(itemValue);
    const offsets = [];
    for (const [normalizedOffset, normalizedLength] of normalizedOffsets) {
      const start2 = starts[normalizedOffset];
      const end = ends[normalizedOffset + normalizedLength];
      if (start2 == null || end == null) continue;
      if (end <= start2) continue;
      offsets.push([start2, end - start2]);
    }
    return offsets;
  }
  function splitValue(itemValue, userValue) {
    if (!itemValue) return itemValue;
    if (!userValue) return itemValue;
    const userValues = toArray2(userValue).map(normalizeValue);
    const parts = [];
    const span = (value, autocomplete = false) => /* @__PURE__ */ (0, import_jsx_runtime153.jsx)("span", {
      "data-autocomplete-value": autocomplete ? "" : void 0,
      "data-user-value": autocomplete ? void 0 : "",
      children: value
    }, parts.length);
    const offsets = toOriginalOffsets(itemValue, mergeOverlappingOffsets(getOffsets(normalizeValue(itemValue), new Set(userValues))));
    const firstEntry = offsets[0];
    if (!firstEntry) {
      parts.push(span(itemValue, true));
      return parts;
    }
    const [firstOffset] = firstEntry;
    [itemValue.slice(0, firstOffset), ...offsets.flatMap(([offset4, length], i2) => {
      const value = itemValue.slice(offset4, offset4 + length);
      const nextOffset = offsets[i2 + 1]?.[0];
      return [value, itemValue.slice(offset4 + length, nextOffset)];
    })].forEach((value, i2) => {
      if (!value) return;
      parts.push(span(value, i2 % 2 === 0));
    });
    return parts;
  }
  var useComboboxItemValue = createHook(function useComboboxItemValue2({ store: store2, value, userValue, ...props }) {
    const context = useComboboxScopedContext();
    store2 = store2 || context;
    const itemContext = (0, import_react30.useContext)(ComboboxItemValueContext);
    const itemValue = value ?? itemContext;
    const inputValue = useStoreState(store2, (state) => userValue ?? state?.value);
    props = {
      children: (0, import_react30.useMemo)(() => {
        if (!itemValue) return;
        if (!inputValue) return itemValue;
        return splitValue(itemValue, inputValue);
      }, [itemValue, inputValue]),
      ...props
    };
    return removeUndefinedValues(props);
  });
  var ComboboxItemValue = forwardRef43(function ComboboxItemValue2(props) {
    return createElement5(TagName11, useComboboxItemValue(props));
  });

  // node_modules/@ariakit/react-components/dist/combobox/combobox-label.js
  var TagName12 = "label";
  var useComboboxLabel = createHook(function useComboboxLabel2({ store: store2, ...props }) {
    const context = useComboboxProviderContext();
    store2 = store2 || context;
    invariant(store2, "ComboboxLabel must receive a `store` prop or be wrapped in a ComboboxProvider component.");
    props = {
      htmlFor: useStoreState(store2, (state) => state.baseElement?.id),
      ...props
    };
    return removeUndefinedValues(props);
  });
  var ComboboxLabel = memo5(forwardRef43(function ComboboxLabel2(props) {
    return createElement5(TagName12, useComboboxLabel(props));
  }));

  // node_modules/@ariakit/react-components/dist/combobox/combobox-list.js
  var import_react31 = __toESM(require_react(), 1);
  var import_jsx_runtime154 = __toESM(require_jsx_runtime(), 1);
  var TagName13 = "div";
  var useComboboxList = createHook(function useComboboxList2({ store: store2, alwaysVisible, ...props }) {
    const scopedContext = useComboboxScopedContext(true);
    const context = useComboboxContext();
    store2 = store2 || context;
    const scopedContextSameStore = !!store2 && store2 === scopedContext;
    invariant(store2, "ComboboxList must receive a `store` prop or be wrapped in a ComboboxProvider component.");
    const ref = (0, import_react31.useRef)(null);
    const id = useId5(props.id);
    const mounted = useStoreState(store2, "mounted");
    const hidden = isHidden(mounted, props.hidden, alwaysVisible);
    const style = hidden ? {
      ...props.style,
      display: "none"
    } : props.style;
    const multiSelectable = useStoreState(store2, (state) => Array.isArray(state.selectedValue));
    const role = useAttribute(ref, "role", props.role);
    const ariaMultiSelectable = role === "listbox" || role === "tree" || role === "grid" ? multiSelectable || void 0 : void 0;
    const [hasListboxInside, setHasListboxInside] = (0, import_react31.useState)(false);
    const contentElement = useStoreState(store2, "contentElement");
    useSafeLayoutEffect(() => {
      if (!mounted) return;
      const element = ref.current;
      if (!element) return;
      if (contentElement !== element) return;
      const callback = () => {
        setHasListboxInside(!!element.querySelector("[role='listbox']"));
      };
      const observer = new MutationObserver(callback);
      observer.observe(element, {
        subtree: true,
        childList: true,
        attributeFilter: ["role"]
      });
      callback();
      return () => observer.disconnect();
    }, [mounted, contentElement]);
    if (!hasListboxInside) props = {
      role: "listbox",
      "aria-multiselectable": ariaMultiSelectable,
      ...props
    };
    props = useWrapElement(props, (element) => /* @__PURE__ */ (0, import_jsx_runtime154.jsx)(ComboboxScopedContextProvider, {
      value: store2,
      children: /* @__PURE__ */ (0, import_jsx_runtime154.jsx)(ComboboxListRoleContext.Provider, {
        value: role,
        children: element
      })
    }), [store2, role]);
    const setContentElement = id && (!scopedContext || !scopedContextSameStore) ? store2.setContentElement : null;
    props = {
      hidden,
      ...props,
      id,
      ref: useMergeRefs(setContentElement, ref, props.ref),
      style
    };
    return removeUndefinedValues(props);
  });
  var ComboboxList = forwardRef43(function ComboboxList2(props) {
    return createElement5(TagName13, useComboboxList(props));
  });

  // node_modules/@ariakit/react-components/dist/tag/tag-context.js
  var import_react32 = __toESM(require_react(), 1);
  var TagValueContext = (0, import_react32.createContext)(null);
  var TagRemoveIdContext = (0, import_react32.createContext)(null);
  var ctx8 = createStoreContext([CompositeContextProvider], [CompositeScopedContextProvider]);
  var useTagContext = ctx8.useContext;
  var useTagScopedContext = ctx8.useScopedContext;
  var useTagProviderContext = ctx8.useProviderContext;
  var TagContextProvider = ctx8.ContextProvider;
  var TagScopedContextProvider = ctx8.ScopedContextProvider;

  // node_modules/@ariakit/components/dist/combobox/combobox-store.js
  var isTouchSafari = isSafari() && isTouchDevice();
  function createComboboxStore({ tag, ...props } = {}) {
    const store2 = mergeStore(props.store, pick2(tag, ["value", "rtl"]));
    throwOnConflictingProps(props, store2);
    const tagState = tag?.getState();
    const syncState = store2?.getState();
    const activeId = defaultValue(props.activeId, syncState?.activeId, props.defaultActiveId, null);
    const composite = createCompositeStore({
      ...props,
      activeId,
      includesBaseElement: defaultValue(props.includesBaseElement, syncState?.includesBaseElement, true),
      orientation: defaultValue(props.orientation, syncState?.orientation, "vertical"),
      focusLoop: defaultValue(props.focusLoop, syncState?.focusLoop, true),
      focusWrap: defaultValue(props.focusWrap, syncState?.focusWrap, true),
      virtualFocus: defaultValue(props.virtualFocus, syncState?.virtualFocus, true)
    });
    const popover = createPopoverStore({
      ...props,
      placement: defaultValue(props.placement, syncState?.placement, "bottom-start")
    });
    const value = defaultValue(props.value, syncState?.value, props.defaultValue, "");
    const selectedValue = defaultValue(props.selectedValue, syncState?.selectedValue, tagState?.values, props.defaultSelectedValue, "");
    const multiSelectable = Array.isArray(selectedValue);
    const initialState = {
      ...composite.getState(),
      ...popover.getState(),
      value,
      selectedValue,
      resetValueOnSelect: defaultValue(props.resetValueOnSelect, syncState?.resetValueOnSelect, multiSelectable),
      resetValueOnHide: defaultValue(props.resetValueOnHide, syncState?.resetValueOnHide, multiSelectable && !tag),
      activeValue: syncState?.activeValue
    };
    const combobox = createStore(initialState, composite, popover, store2);
    if (isTouchSafari) setup(combobox, () => sync2(combobox, ["virtualFocus"], () => {
      combobox.setState("virtualFocus", false);
    }));
    setup(combobox, () => {
      if (!tag) return;
      return chain(sync2(combobox, ["selectedValue"], (state) => {
        if (!Array.isArray(state.selectedValue)) return;
        tag.setValues(state.selectedValue);
      }), sync2(tag, ["values"], (state) => {
        combobox.setState("selectedValue", state.values);
      }));
    });
    setup(combobox, () => sync2(combobox, ["resetValueOnHide", "mounted"], (state) => {
      if (!state.resetValueOnHide) return;
      if (state.mounted) return;
      combobox.setState("value", value);
    }));
    setup(combobox, () => sync2(combobox, ["open"], (state) => {
      if (state.open) return;
      combobox.setState("activeId", activeId);
      combobox.setState("moves", 0);
    }));
    setup(combobox, () => sync2(combobox, ["moves", "activeId"], (state, prevState) => {
      if (state.moves === prevState.moves) combobox.setState("activeValue", void 0);
    }));
    setup(combobox, () => batch(combobox, ["moves", "renderedItems"], (state, prev) => {
      if (state.moves === prev.moves) return;
      const { activeId: activeId2 } = combobox.getState();
      const activeItem = composite.item(activeId2);
      combobox.setState("activeValue", activeItem?.value);
    }));
    return {
      ...popover,
      ...composite,
      ...combobox,
      tag,
      setValue: (value2) => combobox.setState("value", value2),
      resetValue: () => combobox.setState("value", initialState.value),
      setSelectedValue: (selectedValue2) => combobox.setState("selectedValue", selectedValue2)
    };
  }

  // node_modules/@ariakit/react-components/dist/combobox/combobox-store.js
  function useComboboxStoreOptions(props) {
    const tag = useTagContext();
    props = {
      ...props,
      tag: props.tag !== void 0 ? props.tag : tag
    };
    return useCompositeStoreOptions(props);
  }
  function useComboboxStoreProps(store2, update4, props) {
    useUpdateEffect(update4, [props.tag]);
    useStoreProps(store2, props, "value", "setValue");
    useStoreProps(store2, props, "selectedValue", "setSelectedValue");
    useStoreProps(store2, props, "resetValueOnHide");
    useStoreProps(store2, props, "resetValueOnSelect");
    return Object.assign(useCompositeStoreProps(usePopoverStoreProps(store2, update4, props), update4, props), { tag: props.tag });
  }
  function useComboboxStore(props = {}) {
    props = useComboboxStoreOptions(props);
    const [store2, update4] = useStore2(createComboboxStore, props);
    return useComboboxStoreProps(store2, update4, props);
  }

  // node_modules/@ariakit/react-components/dist/combobox/combobox-provider.js
  var import_jsx_runtime155 = __toESM(require_jsx_runtime(), 1);
  function ComboboxProvider(props = {}) {
    return /* @__PURE__ */ (0, import_jsx_runtime155.jsx)(ComboboxContextProvider, {
      value: useComboboxStore(props),
      children: props.children
    });
  }

  // packages/dataviews/build-module/components/dataviews-filters/search-widget.mjs
  var import_remove_accents = __toESM(require_remove_accents(), 1);
  var import_compose12 = __toESM(require_compose(), 1);
  var import_i18n46 = __toESM(require_i18n(), 1);
  var import_element82 = __toESM(require_element(), 1);
  var import_components38 = __toESM(require_components(), 1);

  // packages/dataviews/build-module/components/dataviews-filters/utils.mjs
  var EMPTY_ARRAY4 = [];
  var getCurrentValue = (filterDefinition, currentFilter) => {
    if (filterDefinition.singleSelection) {
      return currentFilter?.value;
    }
    if (Array.isArray(currentFilter?.value)) {
      return currentFilter.value;
    }
    if (!Array.isArray(currentFilter?.value) && !!currentFilter?.value) {
      return [currentFilter.value];
    }
    return EMPTY_ARRAY4;
  };

  // packages/dataviews/build-module/hooks/use-elements.mjs
  var import_element81 = __toESM(require_element(), 1);
  var EMPTY_ARRAY5 = [];
  function useElements({
    elements: elements2,
    getElements
  }) {
    const staticElements = Array.isArray(elements2) && elements2.length > 0 ? elements2 : EMPTY_ARRAY5;
    const [records, setRecords] = (0, import_element81.useState)(staticElements);
    const [isLoading, setIsLoading] = (0, import_element81.useState)(false);
    (0, import_element81.useEffect)(() => {
      if (!getElements) {
        setRecords(staticElements);
        return;
      }
      let cancelled = false;
      setIsLoading(true);
      getElements().then((fetchedElements) => {
        if (!cancelled) {
          const dynamicElements = Array.isArray(fetchedElements) && fetchedElements.length > 0 ? fetchedElements : staticElements;
          setRecords(dynamicElements);
        }
      }).catch(() => {
        if (!cancelled) {
          setRecords(staticElements);
        }
      }).finally(() => {
        if (!cancelled) {
          setIsLoading(false);
        }
      });
      return () => {
        cancelled = true;
      };
    }, [getElements, staticElements]);
    return {
      elements: records,
      isLoading
    };
  }

  // packages/dataviews/build-module/components/dataviews-filters/search-widget.mjs
  var import_jsx_runtime156 = __toESM(require_jsx_runtime(), 1);
  function normalizeSearchInput(input = "") {
    return (0, import_remove_accents.default)(input.trim().toLowerCase());
  }
  var getNewValue = (filterDefinition, currentFilter, value) => {
    if (filterDefinition.singleSelection) {
      return value;
    }
    if (Array.isArray(currentFilter?.value)) {
      return currentFilter.value.includes(value) ? currentFilter.value.filter((v2) => v2 !== value) : [...currentFilter.value, value];
    }
    return [value];
  };
  function generateFilterElementCompositeItemId(prefix2, filterElementValue) {
    return `${prefix2}-${filterElementValue}`;
  }
  var MultiSelectionOption = ({ selected }) => {
    return /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
      "span",
      {
        className: clsx_default(
          "dataviews-filters__search-widget-listitem-multi-selection",
          { "is-selected": selected }
        ),
        children: selected && /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(import_components38.Icon, { icon: check_default })
      }
    );
  };
  var SingleSelectionOption = ({ selected }) => {
    return /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
      "span",
      {
        className: clsx_default(
          "dataviews-filters__search-widget-listitem-single-selection",
          { "is-selected": selected }
        )
      }
    );
  };
  function ListBox({ view, filter, onChangeView }) {
    const baseId = (0, import_compose12.useInstanceId)(ListBox, "dataviews-filter-list-box");
    const [activeCompositeId, setActiveCompositeId] = (0, import_element82.useState)(
      // When there are one or less operators, the first item is set as active
      // (by setting the initial `activeId` to `undefined`).
      // With 2 or more operators, the focus is moved on the operators control
      // (by setting the initial `activeId` to `null`), meaning that there won't
      // be an active item initially. Focus is then managed via the
      // `onFocusVisible` callback.
      filter.operators?.length === 1 ? void 0 : null
    );
    const currentFilter = view.filters?.find(
      (f2) => f2.field === filter.field
    );
    const currentValue = getCurrentValue(filter, currentFilter);
    return /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
      import_components38.Composite,
      {
        virtualFocus: true,
        focusLoop: true,
        activeId: activeCompositeId,
        setActiveId: setActiveCompositeId,
        role: "listbox",
        className: "dataviews-filters__search-widget-listbox",
        "aria-label": (0, import_i18n46.sprintf)(
          /* translators: List of items for a filter. 1: Filter name. e.g.: "List of: Author". */
          (0, import_i18n46.__)("List of: %1$s"),
          filter.name
        ),
        onFocusVisible: () => {
          if (!activeCompositeId && filter.elements.length) {
            setActiveCompositeId(
              generateFilterElementCompositeItemId(
                baseId,
                filter.elements[0].value
              )
            );
          }
        },
        render: /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(import_components38.Composite.Typeahead, {}),
        children: filter.elements.map((element) => /* @__PURE__ */ (0, import_jsx_runtime156.jsxs)(
          import_components38.Composite.Hover,
          {
            render: /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
              import_components38.Composite.Item,
              {
                id: generateFilterElementCompositeItemId(
                  baseId,
                  element.value
                ),
                render: /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
                  "div",
                  {
                    "aria-label": element.label,
                    role: "option",
                    className: "dataviews-filters__search-widget-listitem"
                  }
                ),
                onClick: () => {
                  const newFilters = currentFilter ? [
                    ...(view.filters ?? []).map(
                      (_filter) => {
                        if (_filter.field === filter.field) {
                          return {
                            ..._filter,
                            operator: currentFilter.operator || filter.operators[0],
                            value: getNewValue(
                              filter,
                              currentFilter,
                              element.value
                            )
                          };
                        }
                        return _filter;
                      }
                    )
                  ] : [
                    ...view.filters ?? [],
                    {
                      field: filter.field,
                      operator: filter.operators[0],
                      value: getNewValue(
                        filter,
                        currentFilter,
                        element.value
                      )
                    }
                  ];
                  onChangeView({
                    ...view,
                    page: 1,
                    filters: newFilters
                  });
                }
              }
            ),
            children: [
              filter.singleSelection && /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
                SingleSelectionOption,
                {
                  selected: currentValue === element.value
                }
              ),
              !filter.singleSelection && /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
                MultiSelectionOption,
                {
                  selected: currentValue.includes(element.value)
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
                "span",
                {
                  className: "dataviews-filters__search-widget-listitem-value",
                  title: element.label,
                  children: element.label
                }
              )
            ]
          },
          element.value
        ))
      }
    );
  }
  function ComboboxList22({ view, filter, onChangeView }) {
    const [searchValue, setSearchValue] = (0, import_element82.useState)("");
    const deferredSearchValue = (0, import_element82.useDeferredValue)(searchValue);
    const currentFilter = view.filters?.find(
      (_filter) => _filter.field === filter.field
    );
    const currentValue = getCurrentValue(filter, currentFilter);
    const matches = (0, import_element82.useMemo)(() => {
      const normalizedSearch = normalizeSearchInput(deferredSearchValue);
      return filter.elements.filter(
        (item) => normalizeSearchInput(item.label).includes(normalizedSearch)
      );
    }, [filter.elements, deferredSearchValue]);
    return /* @__PURE__ */ (0, import_jsx_runtime156.jsxs)(
      ComboboxProvider,
      {
        selectedValue: currentValue,
        setSelectedValue: (value) => {
          const newFilters = currentFilter ? [
            ...(view.filters ?? []).map((_filter) => {
              if (_filter.field === filter.field) {
                return {
                  ..._filter,
                  operator: currentFilter.operator || filter.operators[0],
                  value
                };
              }
              return _filter;
            })
          ] : [
            ...view.filters ?? [],
            {
              field: filter.field,
              operator: filter.operators[0],
              value
            }
          ];
          onChangeView({
            ...view,
            page: 1,
            filters: newFilters
          });
        },
        setValue: setSearchValue,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime156.jsxs)("div", { className: "dataviews-filters__search-widget-filter-combobox__wrapper", children: [
            /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(ComboboxLabel, {}), children: (0, import_i18n46.__)("Search items") }),
            /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
              Combobox,
              {
                autoSelect: "always",
                placeholder: (0, import_i18n46.__)("Search"),
                className: "dataviews-filters__search-widget-filter-combobox__input"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime156.jsx)("div", { className: "dataviews-filters__search-widget-filter-combobox__icon", children: /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(import_components38.Icon, { icon: search_default }) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime156.jsxs)(
            ComboboxList,
            {
              className: "dataviews-filters__search-widget-filter-combobox-list",
              alwaysVisible: true,
              children: [
                matches.map((element) => {
                  return /* @__PURE__ */ (0, import_jsx_runtime156.jsxs)(
                    ComboboxItem,
                    {
                      resetValueOnSelect: false,
                      value: element.value,
                      className: "dataviews-filters__search-widget-listitem",
                      hideOnClick: false,
                      setValueOnClick: false,
                      focusOnHover: true,
                      children: [
                        filter.singleSelection && /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
                          SingleSelectionOption,
                          {
                            selected: currentValue === element.value
                          }
                        ),
                        !filter.singleSelection && /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
                          MultiSelectionOption,
                          {
                            selected: currentValue.includes(
                              element.value
                            )
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime156.jsxs)(
                          "span",
                          {
                            className: "dataviews-filters__search-widget-listitem-value",
                            title: element.label,
                            children: [
                              /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(
                                ComboboxItemValue,
                                {
                                  className: "dataviews-filters__search-widget-filter-combobox-item-value",
                                  value: element.label
                                }
                              ),
                              !!element.description && /* @__PURE__ */ (0, import_jsx_runtime156.jsx)("span", { className: "dataviews-filters__search-widget-listitem-description", children: element.description })
                            ]
                          }
                        )
                      ]
                    },
                    element.value
                  );
                }),
                !matches.length && /* @__PURE__ */ (0, import_jsx_runtime156.jsx)("p", { children: (0, import_i18n46.__)("No results found") })
              ]
            }
          )
        ]
      }
    );
  }
  function SearchWidget(props) {
    const { elements: elements2, isLoading } = useElements({
      elements: props.filter.elements,
      getElements: props.filter.getElements
    });
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime156.jsx)("div", { className: "dataviews-filters__search-widget-no-elements", children: /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(import_components38.Spinner, {}) });
    }
    if (elements2.length === 0) {
      return /* @__PURE__ */ (0, import_jsx_runtime156.jsx)("div", { className: "dataviews-filters__search-widget-no-elements", children: (0, import_i18n46.__)("No elements found") });
    }
    const Widget = elements2.length > 10 ? ComboboxList22 : ListBox;
    return /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(Widget, { ...props, filter: { ...props.filter, elements: elements2 } });
  }

  // packages/dataviews/build-module/components/dataviews-filters/input-widget.mjs
  var import_es62 = __toESM(require_es6(), 1);
  var import_compose13 = __toESM(require_compose(), 1);
  var import_element83 = __toESM(require_element(), 1);
  var import_components39 = __toESM(require_components(), 1);
  var import_jsx_runtime157 = __toESM(require_jsx_runtime(), 1);
  function InputWidget({
    filter,
    view,
    onChangeView,
    fields: fields2
  }) {
    const currentFilter = view.filters?.find(
      (f2) => f2.field === filter.field
    );
    const currentValue = getCurrentValue(filter, currentFilter);
    const field = (0, import_element83.useMemo)(() => {
      const currentField = fields2.find((f2) => f2.id === filter.field);
      if (currentField) {
        return {
          ...currentField,
          // Deactivate validation for filters.
          isValid: {},
          // Filter controls are always enabled.
          isDisabled: () => false,
          // Filter controls are always visible.
          isVisible: () => true,
          // Configure getValue/setValue as if Item was a plain object.
          getValue: ({ item }) => item[currentField.id],
          setValue: ({ value }) => ({
            [currentField.id]: value
          })
        };
      }
      return currentField;
    }, [fields2, filter.field]);
    const data = (0, import_element83.useMemo)(() => {
      return (view.filters ?? []).reduce(
        (acc, activeFilter) => {
          acc[activeFilter.field] = activeFilter.value;
          return acc;
        },
        {}
      );
    }, [view.filters]);
    const handleChange = (0, import_compose13.useEvent)((updatedData) => {
      if (!field || !currentFilter) {
        return;
      }
      const nextValue = field.getValue({ item: updatedData });
      if ((0, import_es62.default)(nextValue, currentValue)) {
        return;
      }
      onChangeView({
        ...view,
        filters: (view.filters ?? []).map(
          (_filter) => _filter.field === filter.field ? {
            ..._filter,
            operator: currentFilter.operator || filter.operators[0],
            // Consider empty strings as undefined:
            //
            // - undefined as value means the filter is unset: the filter widget displays no value and the search returns all records
            // - empty string as value means "search empty string": returns only the records that have an empty string as value
            //
            // In practice, this means the filter will not be able to find an empty string as the value.
            value: nextValue === "" ? void 0 : nextValue
          } : _filter
        )
      });
    });
    if (!field || !field.Edit || !currentFilter) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime157.jsx)(
      import_components39.Flex,
      {
        className: "dataviews-filters__user-input-widget",
        gap: 2.5,
        direction: "column",
        children: /* @__PURE__ */ (0, import_jsx_runtime157.jsx)(
          field.Edit,
          {
            hideLabelFromVision: true,
            data,
            field,
            operator: currentFilter.operator,
            onChange: handleChange
          }
        )
      }
    );
  }

  // node_modules/date-fns/constants.js
  var daysInYear = 365.2425;
  var maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1e3;
  var minTime = -maxTime;
  var millisecondsInWeek = 6048e5;
  var millisecondsInDay = 864e5;
  var secondsInHour = 3600;
  var secondsInDay = secondsInHour * 24;
  var secondsInWeek = secondsInDay * 7;
  var secondsInYear = secondsInDay * daysInYear;
  var secondsInMonth = secondsInYear / 12;
  var secondsInQuarter = secondsInMonth * 3;
  var constructFromSymbol = /* @__PURE__ */ Symbol.for("constructDateFrom");

  // node_modules/date-fns/constructFrom.js
  function constructFrom(date, value) {
    if (typeof date === "function") return date(value);
    if (date && typeof date === "object" && constructFromSymbol in date)
      return date[constructFromSymbol](value);
    if (date instanceof Date) return new date.constructor(value);
    return new Date(value);
  }

  // node_modules/date-fns/toDate.js
  function toDate(argument, context) {
    return constructFrom(context || argument, argument);
  }

  // node_modules/date-fns/addDays.js
  function addDays(date, amount, options) {
    const _date = toDate(date, options?.in);
    if (isNaN(amount)) return constructFrom(options?.in || date, NaN);
    if (!amount) return _date;
    _date.setDate(_date.getDate() + amount);
    return _date;
  }

  // node_modules/date-fns/addMonths.js
  function addMonths(date, amount, options) {
    const _date = toDate(date, options?.in);
    if (isNaN(amount)) return constructFrom(options?.in || date, NaN);
    if (!amount) {
      return _date;
    }
    const dayOfMonth = _date.getDate();
    const endOfDesiredMonth = constructFrom(options?.in || date, _date.getTime());
    endOfDesiredMonth.setMonth(_date.getMonth() + amount + 1, 0);
    const daysInMonth = endOfDesiredMonth.getDate();
    if (dayOfMonth >= daysInMonth) {
      return endOfDesiredMonth;
    } else {
      _date.setFullYear(
        endOfDesiredMonth.getFullYear(),
        endOfDesiredMonth.getMonth(),
        dayOfMonth
      );
      return _date;
    }
  }

  // node_modules/date-fns/_lib/defaultOptions.js
  var defaultOptions = {};
  function getDefaultOptions() {
    return defaultOptions;
  }

  // node_modules/date-fns/startOfWeek.js
  function startOfWeek(date, options) {
    const defaultOptions2 = getDefaultOptions();
    const weekStartsOn = options?.weekStartsOn ?? options?.locale?.options?.weekStartsOn ?? defaultOptions2.weekStartsOn ?? defaultOptions2.locale?.options?.weekStartsOn ?? 0;
    const _date = toDate(date, options?.in);
    const day = _date.getDay();
    const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
    _date.setDate(_date.getDate() - diff);
    _date.setHours(0, 0, 0, 0);
    return _date;
  }

  // node_modules/date-fns/startOfISOWeek.js
  function startOfISOWeek(date, options) {
    return startOfWeek(date, { ...options, weekStartsOn: 1 });
  }

  // node_modules/date-fns/getISOWeekYear.js
  function getISOWeekYear(date, options) {
    const _date = toDate(date, options?.in);
    const year = _date.getFullYear();
    const fourthOfJanuaryOfNextYear = constructFrom(_date, 0);
    fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
    fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
    const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);
    const fourthOfJanuaryOfThisYear = constructFrom(_date, 0);
    fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
    fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
    const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);
    if (_date.getTime() >= startOfNextYear.getTime()) {
      return year + 1;
    } else if (_date.getTime() >= startOfThisYear.getTime()) {
      return year;
    } else {
      return year - 1;
    }
  }

  // node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.js
  function getTimezoneOffsetInMilliseconds(date) {
    const _date = toDate(date);
    const utcDate = new Date(
      Date.UTC(
        _date.getFullYear(),
        _date.getMonth(),
        _date.getDate(),
        _date.getHours(),
        _date.getMinutes(),
        _date.getSeconds(),
        _date.getMilliseconds()
      )
    );
    utcDate.setUTCFullYear(_date.getFullYear());
    return +date - +utcDate;
  }

  // node_modules/date-fns/_lib/normalizeDates.js
  function normalizeDates(context, ...dates) {
    const normalize = constructFrom.bind(
      null,
      context || dates.find((date) => typeof date === "object")
    );
    return dates.map(normalize);
  }

  // node_modules/date-fns/startOfDay.js
  function startOfDay(date, options) {
    const _date = toDate(date, options?.in);
    _date.setHours(0, 0, 0, 0);
    return _date;
  }

  // node_modules/date-fns/differenceInCalendarDays.js
  function differenceInCalendarDays(laterDate, earlierDate, options) {
    const [laterDate_, earlierDate_] = normalizeDates(
      options?.in,
      laterDate,
      earlierDate
    );
    const laterStartOfDay = startOfDay(laterDate_);
    const earlierStartOfDay = startOfDay(earlierDate_);
    const laterTimestamp = +laterStartOfDay - getTimezoneOffsetInMilliseconds(laterStartOfDay);
    const earlierTimestamp = +earlierStartOfDay - getTimezoneOffsetInMilliseconds(earlierStartOfDay);
    return Math.round((laterTimestamp - earlierTimestamp) / millisecondsInDay);
  }

  // node_modules/date-fns/startOfISOWeekYear.js
  function startOfISOWeekYear(date, options) {
    const year = getISOWeekYear(date, options);
    const fourthOfJanuary = constructFrom(options?.in || date, 0);
    fourthOfJanuary.setFullYear(year, 0, 4);
    fourthOfJanuary.setHours(0, 0, 0, 0);
    return startOfISOWeek(fourthOfJanuary);
  }

  // node_modules/date-fns/addWeeks.js
  function addWeeks(date, amount, options) {
    return addDays(date, amount * 7, options);
  }

  // node_modules/date-fns/addYears.js
  function addYears(date, amount, options) {
    return addMonths(date, amount * 12, options);
  }

  // node_modules/date-fns/isDate.js
  function isDate(value) {
    return value instanceof Date || typeof value === "object" && Object.prototype.toString.call(value) === "[object Date]";
  }

  // node_modules/date-fns/isValid.js
  function isValid(date) {
    return !(!isDate(date) && typeof date !== "number" || isNaN(+toDate(date)));
  }

  // node_modules/date-fns/startOfMonth.js
  function startOfMonth(date, options) {
    const _date = toDate(date, options?.in);
    _date.setDate(1);
    _date.setHours(0, 0, 0, 0);
    return _date;
  }

  // node_modules/date-fns/startOfYear.js
  function startOfYear(date, options) {
    const date_ = toDate(date, options?.in);
    date_.setFullYear(date_.getFullYear(), 0, 1);
    date_.setHours(0, 0, 0, 0);
    return date_;
  }

  // node_modules/date-fns/locale/en-US/_lib/formatDistance.js
  var formatDistanceLocale = {
    lessThanXSeconds: {
      one: "less than a second",
      other: "less than {{count}} seconds"
    },
    xSeconds: {
      one: "1 second",
      other: "{{count}} seconds"
    },
    halfAMinute: "half a minute",
    lessThanXMinutes: {
      one: "less than a minute",
      other: "less than {{count}} minutes"
    },
    xMinutes: {
      one: "1 minute",
      other: "{{count}} minutes"
    },
    aboutXHours: {
      one: "about 1 hour",
      other: "about {{count}} hours"
    },
    xHours: {
      one: "1 hour",
      other: "{{count}} hours"
    },
    xDays: {
      one: "1 day",
      other: "{{count}} days"
    },
    aboutXWeeks: {
      one: "about 1 week",
      other: "about {{count}} weeks"
    },
    xWeeks: {
      one: "1 week",
      other: "{{count}} weeks"
    },
    aboutXMonths: {
      one: "about 1 month",
      other: "about {{count}} months"
    },
    xMonths: {
      one: "1 month",
      other: "{{count}} months"
    },
    aboutXYears: {
      one: "about 1 year",
      other: "about {{count}} years"
    },
    xYears: {
      one: "1 year",
      other: "{{count}} years"
    },
    overXYears: {
      one: "over 1 year",
      other: "over {{count}} years"
    },
    almostXYears: {
      one: "almost 1 year",
      other: "almost {{count}} years"
    }
  };
  var formatDistance = (token, count, options) => {
    let result;
    const tokenValue = formatDistanceLocale[token];
    if (typeof tokenValue === "string") {
      result = tokenValue;
    } else if (count === 1) {
      result = tokenValue.one;
    } else {
      result = tokenValue.other.replace("{{count}}", count.toString());
    }
    if (options?.addSuffix) {
      if (options.comparison && options.comparison > 0) {
        return "in " + result;
      } else {
        return result + " ago";
      }
    }
    return result;
  };

  // node_modules/date-fns/locale/_lib/buildFormatLongFn.js
  function buildFormatLongFn(args) {
    return (options = {}) => {
      const width = options.width ? String(options.width) : args.defaultWidth;
      const format6 = args.formats[width] || args.formats[args.defaultWidth];
      return format6;
    };
  }

  // node_modules/date-fns/locale/en-US/_lib/formatLong.js
  var dateFormats = {
    full: "EEEE, MMMM do, y",
    long: "MMMM do, y",
    medium: "MMM d, y",
    short: "MM/dd/yyyy"
  };
  var timeFormats = {
    full: "h:mm:ss a zzzz",
    long: "h:mm:ss a z",
    medium: "h:mm:ss a",
    short: "h:mm a"
  };
  var dateTimeFormats = {
    full: "{{date}} 'at' {{time}}",
    long: "{{date}} 'at' {{time}}",
    medium: "{{date}}, {{time}}",
    short: "{{date}}, {{time}}"
  };
  var formatLong = {
    date: buildFormatLongFn({
      formats: dateFormats,
      defaultWidth: "full"
    }),
    time: buildFormatLongFn({
      formats: timeFormats,
      defaultWidth: "full"
    }),
    dateTime: buildFormatLongFn({
      formats: dateTimeFormats,
      defaultWidth: "full"
    })
  };

  // node_modules/date-fns/locale/en-US/_lib/formatRelative.js
  var formatRelativeLocale = {
    lastWeek: "'last' eeee 'at' p",
    yesterday: "'yesterday at' p",
    today: "'today at' p",
    tomorrow: "'tomorrow at' p",
    nextWeek: "eeee 'at' p",
    other: "P"
  };
  var formatRelative = (token, _date, _baseDate, _options) => formatRelativeLocale[token];

  // node_modules/date-fns/locale/_lib/buildLocalizeFn.js
  function buildLocalizeFn(args) {
    return (value, options) => {
      const context = options?.context ? String(options.context) : "standalone";
      let valuesArray;
      if (context === "formatting" && args.formattingValues) {
        const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
        const width = options?.width ? String(options.width) : defaultWidth;
        valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
      } else {
        const defaultWidth = args.defaultWidth;
        const width = options?.width ? String(options.width) : args.defaultWidth;
        valuesArray = args.values[width] || args.values[defaultWidth];
      }
      const index2 = args.argumentCallback ? args.argumentCallback(value) : value;
      return valuesArray[index2];
    };
  }

  // node_modules/date-fns/locale/en-US/_lib/localize.js
  var eraValues = {
    narrow: ["B", "A"],
    abbreviated: ["BC", "AD"],
    wide: ["Before Christ", "Anno Domini"]
  };
  var quarterValues = {
    narrow: ["1", "2", "3", "4"],
    abbreviated: ["Q1", "Q2", "Q3", "Q4"],
    wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
  };
  var monthValues = {
    narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
    abbreviated: [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ],
    wide: [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ]
  };
  var dayValues = {
    narrow: ["S", "M", "T", "W", "T", "F", "S"],
    short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
    abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    wide: [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday"
    ]
  };
  var dayPeriodValues = {
    narrow: {
      am: "a",
      pm: "p",
      midnight: "mi",
      noon: "n",
      morning: "morning",
      afternoon: "afternoon",
      evening: "evening",
      night: "night"
    },
    abbreviated: {
      am: "AM",
      pm: "PM",
      midnight: "midnight",
      noon: "noon",
      morning: "morning",
      afternoon: "afternoon",
      evening: "evening",
      night: "night"
    },
    wide: {
      am: "a.m.",
      pm: "p.m.",
      midnight: "midnight",
      noon: "noon",
      morning: "morning",
      afternoon: "afternoon",
      evening: "evening",
      night: "night"
    }
  };
  var formattingDayPeriodValues = {
    narrow: {
      am: "a",
      pm: "p",
      midnight: "mi",
      noon: "n",
      morning: "in the morning",
      afternoon: "in the afternoon",
      evening: "in the evening",
      night: "at night"
    },
    abbreviated: {
      am: "AM",
      pm: "PM",
      midnight: "midnight",
      noon: "noon",
      morning: "in the morning",
      afternoon: "in the afternoon",
      evening: "in the evening",
      night: "at night"
    },
    wide: {
      am: "a.m.",
      pm: "p.m.",
      midnight: "midnight",
      noon: "noon",
      morning: "in the morning",
      afternoon: "in the afternoon",
      evening: "in the evening",
      night: "at night"
    }
  };
  var ordinalNumber = (dirtyNumber, _options) => {
    const number = Number(dirtyNumber);
    const rem100 = number % 100;
    if (rem100 > 20 || rem100 < 10) {
      switch (rem100 % 10) {
        case 1:
          return number + "st";
        case 2:
          return number + "nd";
        case 3:
          return number + "rd";
      }
    }
    return number + "th";
  };
  var localize = {
    ordinalNumber,
    era: buildLocalizeFn({
      values: eraValues,
      defaultWidth: "wide"
    }),
    quarter: buildLocalizeFn({
      values: quarterValues,
      defaultWidth: "wide",
      argumentCallback: (quarter) => quarter - 1
    }),
    month: buildLocalizeFn({
      values: monthValues,
      defaultWidth: "wide"
    }),
    day: buildLocalizeFn({
      values: dayValues,
      defaultWidth: "wide"
    }),
    dayPeriod: buildLocalizeFn({
      values: dayPeriodValues,
      defaultWidth: "wide",
      formattingValues: formattingDayPeriodValues,
      defaultFormattingWidth: "wide"
    })
  };

  // node_modules/date-fns/locale/_lib/buildMatchFn.js
  function buildMatchFn(args) {
    return (string, options = {}) => {
      const width = options.width;
      const matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
      const matchResult = string.match(matchPattern);
      if (!matchResult) {
        return null;
      }
      const matchedString = matchResult[0];
      const parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
      const key = Array.isArray(parsePatterns) ? findIndex2(parsePatterns, (pattern) => pattern.test(matchedString)) : (
        // [TODO] -- I challenge you to fix the type
        findKey(parsePatterns, (pattern) => pattern.test(matchedString))
      );
      let value;
      value = args.valueCallback ? args.valueCallback(key) : key;
      value = options.valueCallback ? (
        // [TODO] -- I challenge you to fix the type
        options.valueCallback(value)
      ) : value;
      const rest = string.slice(matchedString.length);
      return { value, rest };
    };
  }
  function findKey(object, predicate) {
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key) && predicate(object[key])) {
        return key;
      }
    }
    return void 0;
  }
  function findIndex2(array, predicate) {
    for (let key = 0; key < array.length; key++) {
      if (predicate(array[key])) {
        return key;
      }
    }
    return void 0;
  }

  // node_modules/date-fns/locale/_lib/buildMatchPatternFn.js
  function buildMatchPatternFn(args) {
    return (string, options = {}) => {
      const matchResult = string.match(args.matchPattern);
      if (!matchResult) return null;
      const matchedString = matchResult[0];
      const parseResult = string.match(args.parsePattern);
      if (!parseResult) return null;
      let value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
      value = options.valueCallback ? options.valueCallback(value) : value;
      const rest = string.slice(matchedString.length);
      return { value, rest };
    };
  }

  // node_modules/date-fns/locale/en-US/_lib/match.js
  var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
  var parseOrdinalNumberPattern = /\d+/i;
  var matchEraPatterns = {
    narrow: /^(b|a)/i,
    abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
    wide: /^(before christ|before common era|anno domini|common era)/i
  };
  var parseEraPatterns = {
    any: [/^b/i, /^(a|c)/i]
  };
  var matchQuarterPatterns = {
    narrow: /^[1234]/i,
    abbreviated: /^q[1234]/i,
    wide: /^[1234](th|st|nd|rd)? quarter/i
  };
  var parseQuarterPatterns = {
    any: [/1/i, /2/i, /3/i, /4/i]
  };
  var matchMonthPatterns = {
    narrow: /^[jfmasond]/i,
    abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
    wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
  };
  var parseMonthPatterns = {
    narrow: [
      /^j/i,
      /^f/i,
      /^m/i,
      /^a/i,
      /^m/i,
      /^j/i,
      /^j/i,
      /^a/i,
      /^s/i,
      /^o/i,
      /^n/i,
      /^d/i
    ],
    any: [
      /^ja/i,
      /^f/i,
      /^mar/i,
      /^ap/i,
      /^may/i,
      /^jun/i,
      /^jul/i,
      /^au/i,
      /^s/i,
      /^o/i,
      /^n/i,
      /^d/i
    ]
  };
  var matchDayPatterns = {
    narrow: /^[smtwf]/i,
    short: /^(su|mo|tu|we|th|fr|sa)/i,
    abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
    wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
  };
  var parseDayPatterns = {
    narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
    any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
  };
  var matchDayPeriodPatterns = {
    narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
    any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
  };
  var parseDayPeriodPatterns = {
    any: {
      am: /^a/i,
      pm: /^p/i,
      midnight: /^mi/i,
      noon: /^no/i,
      morning: /morning/i,
      afternoon: /afternoon/i,
      evening: /evening/i,
      night: /night/i
    }
  };
  var match = {
    ordinalNumber: buildMatchPatternFn({
      matchPattern: matchOrdinalNumberPattern,
      parsePattern: parseOrdinalNumberPattern,
      valueCallback: (value) => parseInt(value, 10)
    }),
    era: buildMatchFn({
      matchPatterns: matchEraPatterns,
      defaultMatchWidth: "wide",
      parsePatterns: parseEraPatterns,
      defaultParseWidth: "any"
    }),
    quarter: buildMatchFn({
      matchPatterns: matchQuarterPatterns,
      defaultMatchWidth: "wide",
      parsePatterns: parseQuarterPatterns,
      defaultParseWidth: "any",
      valueCallback: (index2) => index2 + 1
    }),
    month: buildMatchFn({
      matchPatterns: matchMonthPatterns,
      defaultMatchWidth: "wide",
      parsePatterns: parseMonthPatterns,
      defaultParseWidth: "any"
    }),
    day: buildMatchFn({
      matchPatterns: matchDayPatterns,
      defaultMatchWidth: "wide",
      parsePatterns: parseDayPatterns,
      defaultParseWidth: "any"
    }),
    dayPeriod: buildMatchFn({
      matchPatterns: matchDayPeriodPatterns,
      defaultMatchWidth: "any",
      parsePatterns: parseDayPeriodPatterns,
      defaultParseWidth: "any"
    })
  };

  // node_modules/date-fns/locale/en-US.js
  var enUS = {
    code: "en-US",
    formatDistance,
    formatLong,
    formatRelative,
    localize,
    match,
    options: {
      weekStartsOn: 0,
      firstWeekContainsDate: 1
    }
  };

  // node_modules/date-fns/getDayOfYear.js
  function getDayOfYear(date, options) {
    const _date = toDate(date, options?.in);
    const diff = differenceInCalendarDays(_date, startOfYear(_date));
    const dayOfYear = diff + 1;
    return dayOfYear;
  }

  // node_modules/date-fns/getISOWeek.js
  function getISOWeek(date, options) {
    const _date = toDate(date, options?.in);
    const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date);
    return Math.round(diff / millisecondsInWeek) + 1;
  }

  // node_modules/date-fns/getWeekYear.js
  function getWeekYear(date, options) {
    const _date = toDate(date, options?.in);
    const year = _date.getFullYear();
    const defaultOptions2 = getDefaultOptions();
    const firstWeekContainsDate = options?.firstWeekContainsDate ?? options?.locale?.options?.firstWeekContainsDate ?? defaultOptions2.firstWeekContainsDate ?? defaultOptions2.locale?.options?.firstWeekContainsDate ?? 1;
    const firstWeekOfNextYear = constructFrom(options?.in || date, 0);
    firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);
    firstWeekOfNextYear.setHours(0, 0, 0, 0);
    const startOfNextYear = startOfWeek(firstWeekOfNextYear, options);
    const firstWeekOfThisYear = constructFrom(options?.in || date, 0);
    firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);
    firstWeekOfThisYear.setHours(0, 0, 0, 0);
    const startOfThisYear = startOfWeek(firstWeekOfThisYear, options);
    if (+_date >= +startOfNextYear) {
      return year + 1;
    } else if (+_date >= +startOfThisYear) {
      return year;
    } else {
      return year - 1;
    }
  }

  // node_modules/date-fns/startOfWeekYear.js
  function startOfWeekYear(date, options) {
    const defaultOptions2 = getDefaultOptions();
    const firstWeekContainsDate = options?.firstWeekContainsDate ?? options?.locale?.options?.firstWeekContainsDate ?? defaultOptions2.firstWeekContainsDate ?? defaultOptions2.locale?.options?.firstWeekContainsDate ?? 1;
    const year = getWeekYear(date, options);
    const firstWeek = constructFrom(options?.in || date, 0);
    firstWeek.setFullYear(year, 0, firstWeekContainsDate);
    firstWeek.setHours(0, 0, 0, 0);
    const _date = startOfWeek(firstWeek, options);
    return _date;
  }

  // node_modules/date-fns/getWeek.js
  function getWeek(date, options) {
    const _date = toDate(date, options?.in);
    const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options);
    return Math.round(diff / millisecondsInWeek) + 1;
  }

  // node_modules/date-fns/_lib/addLeadingZeros.js
  function addLeadingZeros(number, targetLength) {
    const sign = number < 0 ? "-" : "";
    const output = Math.abs(number).toString().padStart(targetLength, "0");
    return sign + output;
  }

  // node_modules/date-fns/_lib/format/lightFormatters.js
  var lightFormatters = {
    // Year
    y(date, token) {
      const signedYear = date.getFullYear();
      const year = signedYear > 0 ? signedYear : 1 - signedYear;
      return addLeadingZeros(token === "yy" ? year % 100 : year, token.length);
    },
    // Month
    M(date, token) {
      const month = date.getMonth();
      return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2);
    },
    // Day of the month
    d(date, token) {
      return addLeadingZeros(date.getDate(), token.length);
    },
    // AM or PM
    a(date, token) {
      const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? "pm" : "am";
      switch (token) {
        case "a":
        case "aa":
          return dayPeriodEnumValue.toUpperCase();
        case "aaa":
          return dayPeriodEnumValue;
        case "aaaaa":
          return dayPeriodEnumValue[0];
        case "aaaa":
        default:
          return dayPeriodEnumValue === "am" ? "a.m." : "p.m.";
      }
    },
    // Hour [1-12]
    h(date, token) {
      return addLeadingZeros(date.getHours() % 12 || 12, token.length);
    },
    // Hour [0-23]
    H(date, token) {
      return addLeadingZeros(date.getHours(), token.length);
    },
    // Minute
    m(date, token) {
      return addLeadingZeros(date.getMinutes(), token.length);
    },
    // Second
    s(date, token) {
      return addLeadingZeros(date.getSeconds(), token.length);
    },
    // Fraction of second
    S(date, token) {
      const numberOfDigits = token.length;
      const milliseconds = date.getMilliseconds();
      const fractionalSeconds = Math.trunc(
        milliseconds * Math.pow(10, numberOfDigits - 3)
      );
      return addLeadingZeros(fractionalSeconds, token.length);
    }
  };

  // node_modules/date-fns/_lib/format/formatters.js
  var dayPeriodEnum = {
    am: "am",
    pm: "pm",
    midnight: "midnight",
    noon: "noon",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  };
  var formatters = {
    // Era
    G: function(date, token, localize2) {
      const era = date.getFullYear() > 0 ? 1 : 0;
      switch (token) {
        // AD, BC
        case "G":
        case "GG":
        case "GGG":
          return localize2.era(era, { width: "abbreviated" });
        // A, B
        case "GGGGG":
          return localize2.era(era, { width: "narrow" });
        // Anno Domini, Before Christ
        case "GGGG":
        default:
          return localize2.era(era, { width: "wide" });
      }
    },
    // Year
    y: function(date, token, localize2) {
      if (token === "yo") {
        const signedYear = date.getFullYear();
        const year = signedYear > 0 ? signedYear : 1 - signedYear;
        return localize2.ordinalNumber(year, { unit: "year" });
      }
      return lightFormatters.y(date, token);
    },
    // Local week-numbering year
    Y: function(date, token, localize2, options) {
      const signedWeekYear = getWeekYear(date, options);
      const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
      if (token === "YY") {
        const twoDigitYear = weekYear % 100;
        return addLeadingZeros(twoDigitYear, 2);
      }
      if (token === "Yo") {
        return localize2.ordinalNumber(weekYear, { unit: "year" });
      }
      return addLeadingZeros(weekYear, token.length);
    },
    // ISO week-numbering year
    R: function(date, token) {
      const isoWeekYear = getISOWeekYear(date);
      return addLeadingZeros(isoWeekYear, token.length);
    },
    // Extended year. This is a single number designating the year of this calendar system.
    // The main difference between `y` and `u` localizers are B.C. years:
    // | Year | `y` | `u` |
    // |------|-----|-----|
    // | AC 1 |   1 |   1 |
    // | BC 1 |   1 |   0 |
    // | BC 2 |   2 |  -1 |
    // Also `yy` always returns the last two digits of a year,
    // while `uu` pads single digit years to 2 characters and returns other years unchanged.
    u: function(date, token) {
      const year = date.getFullYear();
      return addLeadingZeros(year, token.length);
    },
    // Quarter
    Q: function(date, token, localize2) {
      const quarter = Math.ceil((date.getMonth() + 1) / 3);
      switch (token) {
        // 1, 2, 3, 4
        case "Q":
          return String(quarter);
        // 01, 02, 03, 04
        case "QQ":
          return addLeadingZeros(quarter, 2);
        // 1st, 2nd, 3rd, 4th
        case "Qo":
          return localize2.ordinalNumber(quarter, { unit: "quarter" });
        // Q1, Q2, Q3, Q4
        case "QQQ":
          return localize2.quarter(quarter, {
            width: "abbreviated",
            context: "formatting"
          });
        // 1, 2, 3, 4 (narrow quarter; could be not numerical)
        case "QQQQQ":
          return localize2.quarter(quarter, {
            width: "narrow",
            context: "formatting"
          });
        // 1st quarter, 2nd quarter, ...
        case "QQQQ":
        default:
          return localize2.quarter(quarter, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    // Stand-alone quarter
    q: function(date, token, localize2) {
      const quarter = Math.ceil((date.getMonth() + 1) / 3);
      switch (token) {
        // 1, 2, 3, 4
        case "q":
          return String(quarter);
        // 01, 02, 03, 04
        case "qq":
          return addLeadingZeros(quarter, 2);
        // 1st, 2nd, 3rd, 4th
        case "qo":
          return localize2.ordinalNumber(quarter, { unit: "quarter" });
        // Q1, Q2, Q3, Q4
        case "qqq":
          return localize2.quarter(quarter, {
            width: "abbreviated",
            context: "standalone"
          });
        // 1, 2, 3, 4 (narrow quarter; could be not numerical)
        case "qqqqq":
          return localize2.quarter(quarter, {
            width: "narrow",
            context: "standalone"
          });
        // 1st quarter, 2nd quarter, ...
        case "qqqq":
        default:
          return localize2.quarter(quarter, {
            width: "wide",
            context: "standalone"
          });
      }
    },
    // Month
    M: function(date, token, localize2) {
      const month = date.getMonth();
      switch (token) {
        case "M":
        case "MM":
          return lightFormatters.M(date, token);
        // 1st, 2nd, ..., 12th
        case "Mo":
          return localize2.ordinalNumber(month + 1, { unit: "month" });
        // Jan, Feb, ..., Dec
        case "MMM":
          return localize2.month(month, {
            width: "abbreviated",
            context: "formatting"
          });
        // J, F, ..., D
        case "MMMMM":
          return localize2.month(month, {
            width: "narrow",
            context: "formatting"
          });
        // January, February, ..., December
        case "MMMM":
        default:
          return localize2.month(month, { width: "wide", context: "formatting" });
      }
    },
    // Stand-alone month
    L: function(date, token, localize2) {
      const month = date.getMonth();
      switch (token) {
        // 1, 2, ..., 12
        case "L":
          return String(month + 1);
        // 01, 02, ..., 12
        case "LL":
          return addLeadingZeros(month + 1, 2);
        // 1st, 2nd, ..., 12th
        case "Lo":
          return localize2.ordinalNumber(month + 1, { unit: "month" });
        // Jan, Feb, ..., Dec
        case "LLL":
          return localize2.month(month, {
            width: "abbreviated",
            context: "standalone"
          });
        // J, F, ..., D
        case "LLLLL":
          return localize2.month(month, {
            width: "narrow",
            context: "standalone"
          });
        // January, February, ..., December
        case "LLLL":
        default:
          return localize2.month(month, { width: "wide", context: "standalone" });
      }
    },
    // Local week of year
    w: function(date, token, localize2, options) {
      const week = getWeek(date, options);
      if (token === "wo") {
        return localize2.ordinalNumber(week, { unit: "week" });
      }
      return addLeadingZeros(week, token.length);
    },
    // ISO week of year
    I: function(date, token, localize2) {
      const isoWeek = getISOWeek(date);
      if (token === "Io") {
        return localize2.ordinalNumber(isoWeek, { unit: "week" });
      }
      return addLeadingZeros(isoWeek, token.length);
    },
    // Day of the month
    d: function(date, token, localize2) {
      if (token === "do") {
        return localize2.ordinalNumber(date.getDate(), { unit: "date" });
      }
      return lightFormatters.d(date, token);
    },
    // Day of year
    D: function(date, token, localize2) {
      const dayOfYear = getDayOfYear(date);
      if (token === "Do") {
        return localize2.ordinalNumber(dayOfYear, { unit: "dayOfYear" });
      }
      return addLeadingZeros(dayOfYear, token.length);
    },
    // Day of week
    E: function(date, token, localize2) {
      const dayOfWeek = date.getDay();
      switch (token) {
        // Tue
        case "E":
        case "EE":
        case "EEE":
          return localize2.day(dayOfWeek, {
            width: "abbreviated",
            context: "formatting"
          });
        // T
        case "EEEEE":
          return localize2.day(dayOfWeek, {
            width: "narrow",
            context: "formatting"
          });
        // Tu
        case "EEEEEE":
          return localize2.day(dayOfWeek, {
            width: "short",
            context: "formatting"
          });
        // Tuesday
        case "EEEE":
        default:
          return localize2.day(dayOfWeek, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    // Local day of week
    e: function(date, token, localize2, options) {
      const dayOfWeek = date.getDay();
      const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
      switch (token) {
        // Numerical value (Nth day of week with current locale or weekStartsOn)
        case "e":
          return String(localDayOfWeek);
        // Padded numerical value
        case "ee":
          return addLeadingZeros(localDayOfWeek, 2);
        // 1st, 2nd, ..., 7th
        case "eo":
          return localize2.ordinalNumber(localDayOfWeek, { unit: "day" });
        case "eee":
          return localize2.day(dayOfWeek, {
            width: "abbreviated",
            context: "formatting"
          });
        // T
        case "eeeee":
          return localize2.day(dayOfWeek, {
            width: "narrow",
            context: "formatting"
          });
        // Tu
        case "eeeeee":
          return localize2.day(dayOfWeek, {
            width: "short",
            context: "formatting"
          });
        // Tuesday
        case "eeee":
        default:
          return localize2.day(dayOfWeek, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    // Stand-alone local day of week
    c: function(date, token, localize2, options) {
      const dayOfWeek = date.getDay();
      const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
      switch (token) {
        // Numerical value (same as in `e`)
        case "c":
          return String(localDayOfWeek);
        // Padded numerical value
        case "cc":
          return addLeadingZeros(localDayOfWeek, token.length);
        // 1st, 2nd, ..., 7th
        case "co":
          return localize2.ordinalNumber(localDayOfWeek, { unit: "day" });
        case "ccc":
          return localize2.day(dayOfWeek, {
            width: "abbreviated",
            context: "standalone"
          });
        // T
        case "ccccc":
          return localize2.day(dayOfWeek, {
            width: "narrow",
            context: "standalone"
          });
        // Tu
        case "cccccc":
          return localize2.day(dayOfWeek, {
            width: "short",
            context: "standalone"
          });
        // Tuesday
        case "cccc":
        default:
          return localize2.day(dayOfWeek, {
            width: "wide",
            context: "standalone"
          });
      }
    },
    // ISO day of week
    i: function(date, token, localize2) {
      const dayOfWeek = date.getDay();
      const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
      switch (token) {
        // 2
        case "i":
          return String(isoDayOfWeek);
        // 02
        case "ii":
          return addLeadingZeros(isoDayOfWeek, token.length);
        // 2nd
        case "io":
          return localize2.ordinalNumber(isoDayOfWeek, { unit: "day" });
        // Tue
        case "iii":
          return localize2.day(dayOfWeek, {
            width: "abbreviated",
            context: "formatting"
          });
        // T
        case "iiiii":
          return localize2.day(dayOfWeek, {
            width: "narrow",
            context: "formatting"
          });
        // Tu
        case "iiiiii":
          return localize2.day(dayOfWeek, {
            width: "short",
            context: "formatting"
          });
        // Tuesday
        case "iiii":
        default:
          return localize2.day(dayOfWeek, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    // AM or PM
    a: function(date, token, localize2) {
      const hours = date.getHours();
      const dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
      switch (token) {
        case "a":
        case "aa":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "abbreviated",
            context: "formatting"
          });
        case "aaa":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "abbreviated",
            context: "formatting"
          }).toLowerCase();
        case "aaaaa":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "narrow",
            context: "formatting"
          });
        case "aaaa":
        default:
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    // AM, PM, midnight, noon
    b: function(date, token, localize2) {
      const hours = date.getHours();
      let dayPeriodEnumValue;
      if (hours === 12) {
        dayPeriodEnumValue = dayPeriodEnum.noon;
      } else if (hours === 0) {
        dayPeriodEnumValue = dayPeriodEnum.midnight;
      } else {
        dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
      }
      switch (token) {
        case "b":
        case "bb":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "abbreviated",
            context: "formatting"
          });
        case "bbb":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "abbreviated",
            context: "formatting"
          }).toLowerCase();
        case "bbbbb":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "narrow",
            context: "formatting"
          });
        case "bbbb":
        default:
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    // in the morning, in the afternoon, in the evening, at night
    B: function(date, token, localize2) {
      const hours = date.getHours();
      let dayPeriodEnumValue;
      if (hours >= 17) {
        dayPeriodEnumValue = dayPeriodEnum.evening;
      } else if (hours >= 12) {
        dayPeriodEnumValue = dayPeriodEnum.afternoon;
      } else if (hours >= 4) {
        dayPeriodEnumValue = dayPeriodEnum.morning;
      } else {
        dayPeriodEnumValue = dayPeriodEnum.night;
      }
      switch (token) {
        case "B":
        case "BB":
        case "BBB":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "abbreviated",
            context: "formatting"
          });
        case "BBBBB":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "narrow",
            context: "formatting"
          });
        case "BBBB":
        default:
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    // Hour [1-12]
    h: function(date, token, localize2) {
      if (token === "ho") {
        let hours = date.getHours() % 12;
        if (hours === 0) hours = 12;
        return localize2.ordinalNumber(hours, { unit: "hour" });
      }
      return lightFormatters.h(date, token);
    },
    // Hour [0-23]
    H: function(date, token, localize2) {
      if (token === "Ho") {
        return localize2.ordinalNumber(date.getHours(), { unit: "hour" });
      }
      return lightFormatters.H(date, token);
    },
    // Hour [0-11]
    K: function(date, token, localize2) {
      const hours = date.getHours() % 12;
      if (token === "Ko") {
        return localize2.ordinalNumber(hours, { unit: "hour" });
      }
      return addLeadingZeros(hours, token.length);
    },
    // Hour [1-24]
    k: function(date, token, localize2) {
      let hours = date.getHours();
      if (hours === 0) hours = 24;
      if (token === "ko") {
        return localize2.ordinalNumber(hours, { unit: "hour" });
      }
      return addLeadingZeros(hours, token.length);
    },
    // Minute
    m: function(date, token, localize2) {
      if (token === "mo") {
        return localize2.ordinalNumber(date.getMinutes(), { unit: "minute" });
      }
      return lightFormatters.m(date, token);
    },
    // Second
    s: function(date, token, localize2) {
      if (token === "so") {
        return localize2.ordinalNumber(date.getSeconds(), { unit: "second" });
      }
      return lightFormatters.s(date, token);
    },
    // Fraction of second
    S: function(date, token) {
      return lightFormatters.S(date, token);
    },
    // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
    X: function(date, token, _localize) {
      const timezoneOffset = date.getTimezoneOffset();
      if (timezoneOffset === 0) {
        return "Z";
      }
      switch (token) {
        // Hours and optional minutes
        case "X":
          return formatTimezoneWithOptionalMinutes(timezoneOffset);
        // Hours, minutes and optional seconds without `:` delimiter
        // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
        // so this token always has the same output as `XX`
        case "XXXX":
        case "XX":
          return formatTimezone(timezoneOffset);
        // Hours, minutes and optional seconds with `:` delimiter
        // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
        // so this token always has the same output as `XXX`
        case "XXXXX":
        case "XXX":
        // Hours and minutes with `:` delimiter
        default:
          return formatTimezone(timezoneOffset, ":");
      }
    },
    // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
    x: function(date, token, _localize) {
      const timezoneOffset = date.getTimezoneOffset();
      switch (token) {
        // Hours and optional minutes
        case "x":
          return formatTimezoneWithOptionalMinutes(timezoneOffset);
        // Hours, minutes and optional seconds without `:` delimiter
        // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
        // so this token always has the same output as `xx`
        case "xxxx":
        case "xx":
          return formatTimezone(timezoneOffset);
        // Hours, minutes and optional seconds with `:` delimiter
        // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
        // so this token always has the same output as `xxx`
        case "xxxxx":
        case "xxx":
        // Hours and minutes with `:` delimiter
        default:
          return formatTimezone(timezoneOffset, ":");
      }
    },
    // Timezone (GMT)
    O: function(date, token, _localize) {
      const timezoneOffset = date.getTimezoneOffset();
      switch (token) {
        // Short
        case "O":
        case "OO":
        case "OOO":
          return "GMT" + formatTimezoneShort(timezoneOffset, ":");
        // Long
        case "OOOO":
        default:
          return "GMT" + formatTimezone(timezoneOffset, ":");
      }
    },
    // Timezone (specific non-location)
    z: function(date, token, _localize) {
      const timezoneOffset = date.getTimezoneOffset();
      switch (token) {
        // Short
        case "z":
        case "zz":
        case "zzz":
          return "GMT" + formatTimezoneShort(timezoneOffset, ":");
        // Long
        case "zzzz":
        default:
          return "GMT" + formatTimezone(timezoneOffset, ":");
      }
    },
    // Seconds timestamp
    t: function(date, token, _localize) {
      const timestamp = Math.trunc(+date / 1e3);
      return addLeadingZeros(timestamp, token.length);
    },
    // Milliseconds timestamp
    T: function(date, token, _localize) {
      return addLeadingZeros(+date, token.length);
    }
  };
  function formatTimezoneShort(offset4, delimiter = "") {
    const sign = offset4 > 0 ? "-" : "+";
    const absOffset = Math.abs(offset4);
    const hours = Math.trunc(absOffset / 60);
    const minutes = absOffset % 60;
    if (minutes === 0) {
      return sign + String(hours);
    }
    return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
  }
  function formatTimezoneWithOptionalMinutes(offset4, delimiter) {
    if (offset4 % 60 === 0) {
      const sign = offset4 > 0 ? "-" : "+";
      return sign + addLeadingZeros(Math.abs(offset4) / 60, 2);
    }
    return formatTimezone(offset4, delimiter);
  }
  function formatTimezone(offset4, delimiter = "") {
    const sign = offset4 > 0 ? "-" : "+";
    const absOffset = Math.abs(offset4);
    const hours = addLeadingZeros(Math.trunc(absOffset / 60), 2);
    const minutes = addLeadingZeros(absOffset % 60, 2);
    return sign + hours + delimiter + minutes;
  }

  // node_modules/date-fns/_lib/format/longFormatters.js
  var dateLongFormatter = (pattern, formatLong2) => {
    switch (pattern) {
      case "P":
        return formatLong2.date({ width: "short" });
      case "PP":
        return formatLong2.date({ width: "medium" });
      case "PPP":
        return formatLong2.date({ width: "long" });
      case "PPPP":
      default:
        return formatLong2.date({ width: "full" });
    }
  };
  var timeLongFormatter = (pattern, formatLong2) => {
    switch (pattern) {
      case "p":
        return formatLong2.time({ width: "short" });
      case "pp":
        return formatLong2.time({ width: "medium" });
      case "ppp":
        return formatLong2.time({ width: "long" });
      case "pppp":
      default:
        return formatLong2.time({ width: "full" });
    }
  };
  var dateTimeLongFormatter = (pattern, formatLong2) => {
    const matchResult = pattern.match(/(P+)(p+)?/) || [];
    const datePattern = matchResult[1];
    const timePattern = matchResult[2];
    if (!timePattern) {
      return dateLongFormatter(pattern, formatLong2);
    }
    let dateTimeFormat;
    switch (datePattern) {
      case "P":
        dateTimeFormat = formatLong2.dateTime({ width: "short" });
        break;
      case "PP":
        dateTimeFormat = formatLong2.dateTime({ width: "medium" });
        break;
      case "PPP":
        dateTimeFormat = formatLong2.dateTime({ width: "long" });
        break;
      case "PPPP":
      default:
        dateTimeFormat = formatLong2.dateTime({ width: "full" });
        break;
    }
    return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2));
  };
  var longFormatters = {
    p: timeLongFormatter,
    P: dateTimeLongFormatter
  };

  // node_modules/date-fns/_lib/protectedTokens.js
  var dayOfYearTokenRE = /^D+$/;
  var weekYearTokenRE = /^Y+$/;
  var throwTokens = ["D", "DD", "YY", "YYYY"];
  function isProtectedDayOfYearToken(token) {
    return dayOfYearTokenRE.test(token);
  }
  function isProtectedWeekYearToken(token) {
    return weekYearTokenRE.test(token);
  }
  function warnOrThrowProtectedError(token, format6, input) {
    const _message = message(token, format6, input);
    console.warn(_message);
    if (throwTokens.includes(token)) throw new RangeError(_message);
  }
  function message(token, format6, input) {
    const subject = token[0] === "Y" ? "years" : "days of the month";
    return `Use \`${token.toLowerCase()}\` instead of \`${token}\` (in \`${format6}\`) for formatting ${subject} to the input \`${input}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`;
  }

  // node_modules/date-fns/format.js
  var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
  var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
  var escapedStringRegExp = /^'([^]*?)'?$/;
  var doubleQuoteRegExp = /''/g;
  var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
  function format(date, formatStr, options) {
    const defaultOptions2 = getDefaultOptions();
    const locale = options?.locale ?? defaultOptions2.locale ?? enUS;
    const firstWeekContainsDate = options?.firstWeekContainsDate ?? options?.locale?.options?.firstWeekContainsDate ?? defaultOptions2.firstWeekContainsDate ?? defaultOptions2.locale?.options?.firstWeekContainsDate ?? 1;
    const weekStartsOn = options?.weekStartsOn ?? options?.locale?.options?.weekStartsOn ?? defaultOptions2.weekStartsOn ?? defaultOptions2.locale?.options?.weekStartsOn ?? 0;
    const originalDate = toDate(date, options?.in);
    if (!isValid(originalDate)) {
      throw new RangeError("Invalid time value");
    }
    let parts = formatStr.match(longFormattingTokensRegExp).map((substring) => {
      const firstCharacter = substring[0];
      if (firstCharacter === "p" || firstCharacter === "P") {
        const longFormatter = longFormatters[firstCharacter];
        return longFormatter(substring, locale.formatLong);
      }
      return substring;
    }).join("").match(formattingTokensRegExp).map((substring) => {
      if (substring === "''") {
        return { isToken: false, value: "'" };
      }
      const firstCharacter = substring[0];
      if (firstCharacter === "'") {
        return { isToken: false, value: cleanEscapedString(substring) };
      }
      if (formatters[firstCharacter]) {
        return { isToken: true, value: substring };
      }
      if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
        throw new RangeError(
          "Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"
        );
      }
      return { isToken: false, value: substring };
    });
    if (locale.localize.preprocessor) {
      parts = locale.localize.preprocessor(originalDate, parts);
    }
    const formatterOptions = {
      firstWeekContainsDate,
      weekStartsOn,
      locale
    };
    return parts.map((part) => {
      if (!part.isToken) return part.value;
      const token = part.value;
      if (!options?.useAdditionalWeekYearTokens && isProtectedWeekYearToken(token) || !options?.useAdditionalDayOfYearTokens && isProtectedDayOfYearToken(token)) {
        warnOrThrowProtectedError(token, formatStr, String(date));
      }
      const formatter = formatters[token[0]];
      return formatter(originalDate, token, locale.localize, formatterOptions);
    }).join("");
  }
  function cleanEscapedString(input) {
    const matched = input.match(escapedStringRegExp);
    if (!matched) {
      return input;
    }
    return matched[1].replace(doubleQuoteRegExp, "'");
  }

  // node_modules/date-fns/subDays.js
  function subDays(date, amount, options) {
    return addDays(date, -amount, options);
  }

  // node_modules/date-fns/subMonths.js
  function subMonths(date, amount, options) {
    return addMonths(date, -amount, options);
  }

  // node_modules/date-fns/subWeeks.js
  function subWeeks(date, amount, options) {
    return addWeeks(date, -amount, options);
  }

  // node_modules/date-fns/subYears.js
  function subYears(date, amount, options) {
    return addYears(date, -amount, options);
  }

  // packages/dataviews/build-module/utils/operators.mjs
  var import_i18n47 = __toESM(require_i18n(), 1);
  var import_element84 = __toESM(require_element(), 1);
  var import_date = __toESM(require_date(), 1);
  var import_jsx_runtime158 = __toESM(require_jsx_runtime(), 1);
  var filterTextWrappers = {
    Name: /* @__PURE__ */ (0, import_jsx_runtime158.jsx)("span", { className: "dataviews-filters__summary-filter-text-name" }),
    Value: /* @__PURE__ */ (0, import_jsx_runtime158.jsx)("span", { className: "dataviews-filters__summary-filter-text-value" })
  };
  function getRelativeDate(value, unit) {
    switch (unit) {
      case "days":
        return subDays(/* @__PURE__ */ new Date(), value);
      case "weeks":
        return subWeeks(/* @__PURE__ */ new Date(), value);
      case "months":
        return subMonths(/* @__PURE__ */ new Date(), value);
      case "years":
        return subYears(/* @__PURE__ */ new Date(), value);
      default:
        return /* @__PURE__ */ new Date();
    }
  }
  var isNoneOperatorDefinition = {
    /* translators: DataViews operator name */
    label: (0, import_i18n47.__)("Is none of"),
    filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
      (0, import_i18n47.sprintf)(
        /* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is none of: Admin, Editor". */
        (0, import_i18n47.__)("<Name>%1$s is none of: </Name><Value>%2$s</Value>"),
        filter.name,
        activeElements.map((element) => element.label).join(", ")
      ),
      filterTextWrappers
    ),
    filter: ((item, field, filterValue) => {
      if (!filterValue?.length) {
        return true;
      }
      const fieldValue = field.getValue({ item });
      if (Array.isArray(fieldValue)) {
        return !filterValue.some(
          (fv) => fieldValue.includes(fv)
        );
      } else if (typeof fieldValue === "string") {
        return !filterValue.includes(fieldValue);
      }
      return false;
    }),
    selection: "multi"
  };
  var OPERATORS = [
    {
      name: OPERATOR_IS_ANY2,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Includes"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is any: Admin, Editor". */
          (0, import_i18n47.__)("<Name>%1$s includes: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements.map((element) => element.label).join(", ")
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (!filterValue?.length) {
          return true;
        }
        const fieldValue = field.getValue({ item });
        if (Array.isArray(fieldValue)) {
          return filterValue.some(
            (fv) => fieldValue.includes(fv)
          );
        } else if (typeof fieldValue === "string") {
          return filterValue.includes(fieldValue);
        }
        return false;
      },
      selection: "multi"
    },
    {
      name: OPERATOR_IS_NONE2,
      ...isNoneOperatorDefinition
    },
    {
      name: OPERATOR_IS_ALL,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Includes all"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author includes all: Admin, Editor". */
          (0, import_i18n47.__)("<Name>%1$s includes all: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements.map((element) => element.label).join(", ")
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (!filterValue?.length) {
          return true;
        }
        return filterValue.every((value) => {
          return field.getValue({ item })?.includes(value);
        });
      },
      selection: "multi"
    },
    {
      name: OPERATOR_IS_NOT_ALL,
      ...isNoneOperatorDefinition
    },
    {
      name: OPERATOR_BETWEEN,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Between (inc)"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Item count"). 2: Filter value min. 3: Filter value max. e.g.: "Item count between (inc): 10 and 180". */
          (0, import_i18n47.__)(
            "<Name>%1$s between (inc): </Name><Value>%2$s and %3$s</Value>"
          ),
          filter.name,
          activeElements[0].label[0],
          activeElements[0].label[1]
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (!Array.isArray(filterValue) || filterValue.length !== 2 || filterValue[0] === void 0 || filterValue[1] === void 0) {
          return true;
        }
        const fieldValue = field.getValue({ item });
        if (typeof fieldValue === "number" || fieldValue instanceof Date || typeof fieldValue === "string") {
          return fieldValue >= filterValue[0] && fieldValue <= filterValue[1];
        }
        return false;
      },
      selection: "custom"
    },
    {
      name: OPERATOR_IN_THE_PAST,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("In the past"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "7 days"): "Date is in the past: 7 days". */
          (0, import_i18n47.__)(
            "<Name>%1$s is in the past: </Name><Value>%2$s</Value>"
          ),
          filter.name,
          `${activeElements[0].value.value} ${activeElements[0].value.unit}`
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue?.value === void 0 || filterValue?.unit === void 0) {
          return true;
        }
        const targetDate = getRelativeDate(
          filterValue.value,
          filterValue.unit
        );
        const fieldValue = (0, import_date.getDate)(field.getValue({ item }));
        return fieldValue >= targetDate && fieldValue <= /* @__PURE__ */ new Date();
      },
      selection: "custom"
    },
    {
      name: OPERATOR_OVER,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Over"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "7 days"): "Date is over: 7 days". */
          (0, import_i18n47.__)("<Name>%1$s is over: </Name><Value>%2$s</Value>"),
          filter.name,
          `${activeElements[0].value.value} ${activeElements[0].value.unit}`
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue?.value === void 0 || filterValue?.unit === void 0) {
          return true;
        }
        const targetDate = getRelativeDate(
          filterValue.value,
          filterValue.unit
        );
        const fieldValue = (0, import_date.getDate)(field.getValue({ item }));
        return fieldValue < targetDate;
      },
      selection: "custom"
    },
    {
      name: OPERATOR_IS,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Is"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is: Admin". */
          (0, import_i18n47.__)("<Name>%1$s is: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        return filterValue === field.getValue({ item }) || filterValue === void 0;
      },
      selection: "single"
    },
    {
      name: OPERATOR_IS_NOT,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Is not"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is not: Admin". */
          (0, import_i18n47.__)("<Name>%1$s is not: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        return filterValue !== field.getValue({ item });
      },
      selection: "single"
    },
    {
      name: OPERATOR_LESS_THAN,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Less than"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is less than: 10". */
          (0, import_i18n47.__)("<Name>%1$s is less than: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const fieldValue = field.getValue({ item });
        return fieldValue < filterValue;
      },
      selection: "single"
    },
    {
      name: OPERATOR_GREATER_THAN,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Greater than"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is greater than: 10". */
          (0, import_i18n47.__)(
            "<Name>%1$s is greater than: </Name><Value>%2$s</Value>"
          ),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const fieldValue = field.getValue({ item });
        return fieldValue > filterValue;
      },
      selection: "single"
    },
    {
      name: OPERATOR_LESS_THAN_OR_EQUAL,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Less than or equal"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is less than or equal to: 10". */
          (0, import_i18n47.__)(
            "<Name>%1$s is less than or equal to: </Name><Value>%2$s</Value>"
          ),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const fieldValue = field.getValue({ item });
        return fieldValue <= filterValue;
      },
      selection: "single"
    },
    {
      name: OPERATOR_GREATER_THAN_OR_EQUAL,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Greater than or equal"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is greater than or equal to: 10". */
          (0, import_i18n47.__)(
            "<Name>%1$s is greater than or equal to: </Name><Value>%2$s</Value>"
          ),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const fieldValue = field.getValue({ item });
        return fieldValue >= filterValue;
      },
      selection: "single"
    },
    {
      name: OPERATOR_BEFORE2,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Before"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is before: 2024-01-01". */
          (0, import_i18n47.__)("<Name>%1$s is before: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const filterDate = (0, import_date.getDate)(filterValue);
        const fieldDate = (0, import_date.getDate)(field.getValue({ item }));
        return fieldDate < filterDate;
      },
      selection: "single"
    },
    {
      name: OPERATOR_AFTER2,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("After"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is after: 2024-01-01". */
          (0, import_i18n47.__)("<Name>%1$s is after: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const filterDate = (0, import_date.getDate)(filterValue);
        const fieldDate = (0, import_date.getDate)(field.getValue({ item }));
        return fieldDate > filterDate;
      },
      selection: "single"
    },
    {
      name: OPERATOR_BEFORE_INC,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Before (inc)"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is on or before: 2024-01-01". */
          (0, import_i18n47.__)(
            "<Name>%1$s is on or before: </Name><Value>%2$s</Value>"
          ),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const filterDate = (0, import_date.getDate)(filterValue);
        const fieldDate = (0, import_date.getDate)(field.getValue({ item }));
        return fieldDate <= filterDate;
      },
      selection: "single"
    },
    {
      name: OPERATOR_AFTER_INC,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("After (inc)"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is on or after: 2024-01-01". */
          (0, import_i18n47.__)(
            "<Name>%1$s is on or after: </Name><Value>%2$s</Value>"
          ),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const filterDate = (0, import_date.getDate)(filterValue);
        const fieldDate = (0, import_date.getDate)(field.getValue({ item }));
        return fieldDate >= filterDate;
      },
      selection: "single"
    },
    {
      name: OPERATOR_CONTAINS,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Contains"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title contains: Hello". */
          (0, import_i18n47.__)("<Name>%1$s contains: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const fieldValue = field.getValue({ item });
        return typeof fieldValue === "string" && filterValue && fieldValue.toLowerCase().includes(String(filterValue).toLowerCase());
      },
      selection: "single"
    },
    {
      name: OPERATOR_NOT_CONTAINS,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Doesn't contain"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title doesn't contain: Hello". */
          (0, import_i18n47.__)(
            "<Name>%1$s doesn't contain: </Name><Value>%2$s</Value>"
          ),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const fieldValue = field.getValue({ item });
        return typeof fieldValue === "string" && filterValue && !fieldValue.toLowerCase().includes(String(filterValue).toLowerCase());
      },
      selection: "single"
    },
    {
      name: OPERATOR_STARTS_WITH,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Starts with"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title starts with: Hello". */
          (0, import_i18n47.__)("<Name>%1$s starts with: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const fieldValue = field.getValue({ item });
        return typeof fieldValue === "string" && filterValue && fieldValue.toLowerCase().startsWith(String(filterValue).toLowerCase());
      },
      selection: "single"
    },
    {
      name: OPERATOR_ON,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("On"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is: 2024-01-01". */
          (0, import_i18n47.__)("<Name>%1$s is: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const filterDate = (0, import_date.getDate)(filterValue);
        const fieldDate = (0, import_date.getDate)(field.getValue({ item }));
        return filterDate.getTime() === fieldDate.getTime();
      },
      selection: "single"
    },
    {
      name: OPERATOR_NOT_ON,
      /* translators: DataViews operator name */
      label: (0, import_i18n47.__)("Not on"),
      filterText: (filter, activeElements) => (0, import_element84.createInterpolateElement)(
        (0, import_i18n47.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is not: 2024-01-01". */
          (0, import_i18n47.__)("<Name>%1$s is not: </Name><Value>%2$s</Value>"),
          filter.name,
          activeElements[0].label
        ),
        filterTextWrappers
      ),
      filter(item, field, filterValue) {
        if (filterValue === void 0) {
          return true;
        }
        const filterDate = (0, import_date.getDate)(filterValue);
        const fieldDate = (0, import_date.getDate)(field.getValue({ item }));
        return filterDate.getTime() !== fieldDate.getTime();
      },
      selection: "single"
    }
  ];
  var getOperatorByName = (name2) => OPERATORS.find((op) => op.name === name2);
  var getAllOperatorNames = () => OPERATORS.map((op) => op.name);
  var isSingleSelectionOperator = (name2) => OPERATORS.filter((op) => op.selection === "single").some(
    (op) => op.name === name2
  );
  var isRegisteredOperator = (name2) => OPERATORS.some((op) => op.name === name2);

  // packages/dataviews/build-module/components/dataviews-filters/filter.mjs
  var import_jsx_runtime159 = __toESM(require_jsx_runtime(), 1);
  var ENTER2 = "Enter";
  var SPACE2 = " ";
  var FilterText = ({
    activeElements,
    filterInView,
    filter
  }) => {
    if (activeElements === void 0 || activeElements.length === 0) {
      return filter.name;
    }
    const operator = getOperatorByName(filterInView?.operator);
    if (operator !== void 0) {
      return operator.filterText(filter, activeElements);
    }
    return (0, import_i18n48.sprintf)(
      /* translators: 1: Filter name e.g.: "Unknown status for Author". */
      (0, import_i18n48.__)("Unknown status for %1$s"),
      filter.name
    );
  };
  function OperatorSelector({
    filter,
    view,
    onChangeView
  }) {
    const operatorOptions = filter.operators?.map((operator) => ({
      value: operator,
      label: getOperatorByName(operator)?.label || operator
    }));
    const currentFilter = view.filters?.find(
      (_filter) => _filter.field === filter.field
    );
    const value = currentFilter?.operator || filter.operators[0];
    return operatorOptions.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime159.jsxs)(
      Stack,
      {
        direction: "row",
        gap: "sm",
        justify: "flex-start",
        className: "dataviews-filters__summary-operators-container",
        align: "center",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(import_components40.FlexItem, { className: "dataviews-filters__summary-operators-filter-name", children: filter.name }),
          /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
            import_components40.SelectControl,
            {
              className: "dataviews-filters__summary-operators-filter-select",
              label: (0, import_i18n48.__)("Conditions"),
              value,
              options: operatorOptions,
              onChange: (newValue) => {
                const newOperator = newValue;
                const currentOperator = currentFilter?.operator;
                const newFilters = currentFilter ? [
                  ...(view.filters ?? []).map(
                    (_filter) => {
                      if (_filter.field === filter.field) {
                        const currentOpSelectionModel = getOperatorByName(
                          currentOperator
                        )?.selection;
                        const newOpSelectionModel = getOperatorByName(
                          newOperator
                        )?.selection;
                        const shouldResetValue = currentOpSelectionModel !== newOpSelectionModel || [
                          currentOpSelectionModel,
                          newOpSelectionModel
                        ].includes("custom");
                        return {
                          ..._filter,
                          value: shouldResetValue ? void 0 : _filter.value,
                          operator: newOperator
                        };
                      }
                      return _filter;
                    }
                  )
                ] : [
                  ...view.filters ?? [],
                  {
                    field: filter.field,
                    operator: newOperator,
                    value: void 0
                  }
                ];
                onChangeView({
                  ...view,
                  page: 1,
                  filters: newFilters
                });
              },
              size: "small",
              variant: "minimal",
              hideLabelFromVision: true
            }
          )
        ]
      }
    );
  }
  function Filter({
    addFilterRef,
    openedFilter,
    fields: fields2,
    ...commonProps
  }) {
    const toggleRef = (0, import_element85.useRef)(null);
    const { filter, view, onChangeView } = commonProps;
    const filterInView = view.filters?.find(
      (f2) => f2.field === filter.field
    );
    let activeElements = [];
    const field = (0, import_element85.useMemo)(() => {
      const currentField = fields2.find((f2) => f2.id === filter.field);
      if (currentField) {
        return {
          ...currentField,
          // Configure getValue as if Item was a plain object.
          // See related input-widget.tsx
          getValue: ({ item }) => item[currentField.id]
        };
      }
      return currentField;
    }, [fields2, filter.field]);
    const { elements: elements2 } = useElements({
      elements: filter.elements,
      getElements: filter.getElements
    });
    if (elements2.length > 0) {
      activeElements = elements2.filter((element) => {
        if (filter.singleSelection) {
          return element.value === filterInView?.value;
        }
        return filterInView?.value?.includes(element.value);
      });
    } else if (Array.isArray(filterInView?.value)) {
      const label = filterInView.value.map((v2) => {
        const formattedValue = field?.getValueFormatted({
          item: { [field.id]: v2 },
          field
        });
        return formattedValue || String(v2);
      });
      activeElements = [
        {
          value: filterInView.value,
          // @ts-ignore
          label
        }
      ];
    } else if (typeof filterInView?.value === "object") {
      activeElements = [
        { value: filterInView.value, label: filterInView.value }
      ];
    } else if (filterInView?.value !== void 0) {
      const label = field !== void 0 ? field.getValueFormatted({
        item: { [field.id]: filterInView.value },
        field
      }) : String(filterInView.value);
      activeElements = [
        {
          value: filterInView.value,
          label
        }
      ];
    }
    const isPrimary = filter.isPrimary;
    const isLocked = filterInView?.isLocked;
    const hasValues = !isLocked && filterInView?.value !== void 0;
    const canResetOrRemove = !isLocked && (!isPrimary || hasValues);
    const resetOrRemoveLabel = isPrimary ? (0, import_i18n48.__)("Reset") : (0, import_i18n48.__)("Remove");
    return /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
      import_components40.Dropdown,
      {
        defaultOpen: openedFilter === filter.field,
        contentClassName: "dataviews-filters__summary-popover",
        popoverProps: { placement: "bottom-start", role: "dialog" },
        onClose: () => {
          toggleRef.current?.focus();
        },
        renderToggle: ({ isOpen, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime159.jsxs)("div", { className: "dataviews-filters__summary-chip-container", children: [
          /* @__PURE__ */ (0, import_jsx_runtime159.jsxs)(tooltip_exports.Root, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
              tooltip_exports.Trigger,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
                  "div",
                  {
                    className: clsx_default(
                      "dataviews-filters__summary-chip",
                      {
                        "has-reset": canResetOrRemove,
                        "has-values": hasValues,
                        "is-not-clickable": isLocked
                      }
                    ),
                    role: "button",
                    tabIndex: isLocked ? -1 : 0,
                    onClick: () => {
                      if (!isLocked) {
                        onToggle();
                      }
                    },
                    onKeyDown: (event) => {
                      if (!isLocked && [ENTER2, SPACE2].includes(
                        event.key
                      )) {
                        onToggle();
                        event.preventDefault();
                      }
                    },
                    "aria-disabled": isLocked,
                    "aria-pressed": isOpen,
                    "aria-expanded": isOpen,
                    ref: toggleRef,
                    children: /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
                      FilterText,
                      {
                        activeElements,
                        filterInView,
                        filter
                      }
                    )
                  }
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(tooltip_exports.Popup, { children: (0, import_i18n48.sprintf)(
              /* translators: 1: Filter name. */
              (0, import_i18n48.__)("Filter by: %1$s"),
              filter.name.toLowerCase()
            ) })
          ] }),
          canResetOrRemove && /* @__PURE__ */ (0, import_jsx_runtime159.jsxs)(tooltip_exports.Root, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
              tooltip_exports.Trigger,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
                  "button",
                  {
                    className: clsx_default(
                      "dataviews-filters__summary-chip-remove",
                      { "has-values": hasValues }
                    ),
                    "aria-label": resetOrRemoveLabel,
                    onClick: () => {
                      onChangeView({
                        ...view,
                        page: 1,
                        filters: view.filters?.filter(
                          (_filter) => _filter.field !== filter.field
                        )
                      });
                      if (!isPrimary) {
                        addFilterRef.current?.focus();
                      } else {
                        toggleRef.current?.focus();
                      }
                    },
                    children: /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(import_components40.Icon, { icon: close_small_default })
                  }
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(tooltip_exports.Popup, { children: resetOrRemoveLabel })
          ] })
        ] }),
        renderContent: () => {
          return /* @__PURE__ */ (0, import_jsx_runtime159.jsxs)(Stack, { direction: "column", justify: "flex-start", children: [
            /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(OperatorSelector, { ...commonProps }),
            commonProps.filter.hasElements ? /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
              SearchWidget,
              {
                ...commonProps,
                filter: {
                  ...commonProps.filter,
                  elements: elements2
                }
              }
            ) : /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(InputWidget, { ...commonProps, fields: fields2 })
          ] });
        }
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-filters/add-filter.mjs
  var import_components41 = __toESM(require_components(), 1);
  var import_i18n49 = __toESM(require_i18n(), 1);
  var import_element86 = __toESM(require_element(), 1);
  var import_jsx_runtime160 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu4 } = unlock4(import_components41.privateApis);
  function AddFilterMenu({
    filters,
    view,
    onChangeView,
    setOpenedFilter,
    triggerProps
  }) {
    const inactiveFilters = filters.filter((filter) => !filter.isVisible);
    return /* @__PURE__ */ (0, import_jsx_runtime160.jsxs)(Menu4, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime160.jsx)(Menu4.TriggerButton, { ...triggerProps }),
      /* @__PURE__ */ (0, import_jsx_runtime160.jsx)(Menu4.Popover, { children: inactiveFilters.map((filter) => {
        return /* @__PURE__ */ (0, import_jsx_runtime160.jsx)(
          Menu4.Item,
          {
            onClick: () => {
              setOpenedFilter(filter.field);
              onChangeView({
                ...view,
                page: 1,
                filters: [
                  ...view.filters || [],
                  {
                    field: filter.field,
                    value: void 0,
                    operator: filter.operators[0]
                  }
                ]
              });
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime160.jsx)(Menu4.ItemLabel, { children: filter.name })
          },
          filter.field
        );
      }) })
    ] });
  }
  function AddFilter({ filters, view, onChangeView, setOpenedFilter }, ref) {
    if (!filters.length || filters.every(({ isPrimary }) => isPrimary)) {
      return null;
    }
    const inactiveFilters = filters.filter((filter) => !filter.isVisible);
    return /* @__PURE__ */ (0, import_jsx_runtime160.jsx)(
      AddFilterMenu,
      {
        triggerProps: {
          render: /* @__PURE__ */ (0, import_jsx_runtime160.jsx)(
            import_components41.Button,
            {
              accessibleWhenDisabled: true,
              size: "compact",
              className: "dataviews-filters-button",
              variant: "tertiary",
              disabled: !inactiveFilters.length,
              ref
            }
          ),
          children: (0, import_i18n49.__)("Add filter")
        },
        ...{ filters, view, onChangeView, setOpenedFilter }
      }
    );
  }
  var add_filter_default = (0, import_element86.forwardRef)(AddFilter);

  // packages/dataviews/build-module/components/dataviews-filters/reset-filters.mjs
  var import_components42 = __toESM(require_components(), 1);
  var import_i18n50 = __toESM(require_i18n(), 1);
  var import_jsx_runtime161 = __toESM(require_jsx_runtime(), 1);
  function ResetFilter({
    filters,
    view,
    onChangeView
  }) {
    const isPrimary = (field) => filters.some(
      (_filter) => _filter.field === field && _filter.isPrimary
    );
    const isDisabled = !view.search && !view.filters?.some(
      (_filter) => !_filter.isLocked && (_filter.value !== void 0 || !isPrimary(_filter.field))
    );
    return /* @__PURE__ */ (0, import_jsx_runtime161.jsx)(
      import_components42.Button,
      {
        disabled: isDisabled,
        accessibleWhenDisabled: true,
        size: "compact",
        variant: "tertiary",
        className: "dataviews-filters__reset-button",
        onClick: () => {
          onChangeView({
            ...view,
            page: 1,
            search: "",
            filters: view.filters?.filter((f2) => !!f2.isLocked) || []
          });
        },
        children: (0, import_i18n50.__)("Reset")
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-filters/use-filters.mjs
  var import_element87 = __toESM(require_element(), 1);
  function useFilters(fields2, view) {
    return (0, import_element87.useMemo)(() => {
      const filters = [];
      fields2.forEach((field) => {
        if (field.filterBy === false || !field.hasElements && !field.Edit) {
          return;
        }
        const operators = field.filterBy.operators;
        const isPrimary = !!field.filterBy?.isPrimary;
        const isLocked = view.filters?.some(
          (f2) => f2.field === field.id && !!f2.isLocked
        ) ?? false;
        filters.push({
          field: field.id,
          name: field.label,
          elements: field.elements,
          getElements: field.getElements,
          hasElements: field.hasElements,
          singleSelection: operators.some(
            (op) => isSingleSelectionOperator(op)
          ),
          operators,
          isVisible: isLocked || isPrimary || !!view.filters?.some(
            (f2) => f2.field === field.id && isRegisteredOperator(f2.operator)
          ),
          isPrimary,
          isLocked
        });
      });
      filters.sort((a2, b2) => {
        if (a2.isLocked && !b2.isLocked) {
          return -1;
        }
        if (!a2.isLocked && b2.isLocked) {
          return 1;
        }
        if (a2.isPrimary && !b2.isPrimary) {
          return -1;
        }
        if (!a2.isPrimary && b2.isPrimary) {
          return 1;
        }
        return a2.name.localeCompare(b2.name);
      });
      return filters;
    }, [fields2, view]);
  }
  var use_filters_default = useFilters;

  // packages/dataviews/build-module/components/dataviews-filters/filters.mjs
  var import_jsx_runtime162 = __toESM(require_jsx_runtime(), 1);
  function Filters({ className }) {
    const { fields: fields2, view, onChangeView, openedFilter, setOpenedFilter } = (0, import_element88.useContext)(dataviews_context_default);
    const addFilterRef = (0, import_element88.useRef)(null);
    const filters = use_filters_default(fields2, view);
    const addFilter = /* @__PURE__ */ (0, import_jsx_runtime162.jsx)(
      add_filter_default,
      {
        filters,
        view,
        onChangeView,
        ref: addFilterRef,
        setOpenedFilter
      },
      "add-filter"
    );
    const visibleFilters = filters.filter((filter) => filter.isVisible);
    if (visibleFilters.length === 0) {
      return null;
    }
    const filterComponents = [
      ...visibleFilters.map((filter) => {
        return /* @__PURE__ */ (0, import_jsx_runtime162.jsx)(
          Filter,
          {
            filter,
            view,
            fields: fields2,
            onChangeView,
            addFilterRef,
            openedFilter
          },
          filter.field
        );
      }),
      addFilter
    ];
    filterComponents.push(
      /* @__PURE__ */ (0, import_jsx_runtime162.jsx)(
        ResetFilter,
        {
          filters,
          view,
          onChangeView
        },
        "reset-filters"
      )
    );
    return /* @__PURE__ */ (0, import_jsx_runtime162.jsx)(
      Stack,
      {
        direction: "row",
        justify: "flex-start",
        gap: "sm",
        style: { width: "fit-content" },
        wrap: "wrap",
        className,
        children: filterComponents
      }
    );
  }
  var filters_default = (0, import_element88.memo)(Filters);

  // packages/dataviews/build-module/components/dataviews-filters/toggle.mjs
  var import_element89 = __toESM(require_element(), 1);
  var import_components43 = __toESM(require_components(), 1);
  var import_i18n51 = __toESM(require_i18n(), 1);
  var import_jsx_runtime163 = __toESM(require_jsx_runtime(), 1);
  function FiltersToggle() {
    const {
      filters,
      view,
      onChangeView,
      setOpenedFilter,
      isShowingFilter,
      setIsShowingFilter
    } = (0, import_element89.useContext)(dataviews_context_default);
    const buttonRef = (0, import_element89.useRef)(null);
    const onChangeViewWithFilterVisibility = (0, import_element89.useCallback)(
      (_view) => {
        onChangeView(_view);
        setIsShowingFilter(true);
      },
      [onChangeView, setIsShowingFilter]
    );
    if (filters.length === 0) {
      return null;
    }
    const hasVisibleFilters = filters.some((filter) => filter.isVisible);
    const addFilterButtonProps = {
      label: (0, import_i18n51.__)("Add filter"),
      "aria-expanded": false,
      isPressed: false
    };
    const toggleFiltersButtonProps = {
      label: (0, import_i18n51._x)("Filter", "verb"),
      "aria-expanded": isShowingFilter,
      isPressed: isShowingFilter,
      onClick: () => {
        if (!isShowingFilter) {
          setOpenedFilter(null);
        }
        setIsShowingFilter(!isShowingFilter);
      }
    };
    const hasPrimaryOrLockedFilters = filters.some(
      (filter) => filter.isPrimary || filter.isLocked
    );
    const buttonComponent = /* @__PURE__ */ (0, import_jsx_runtime163.jsx)(
      import_components43.Button,
      {
        ref: buttonRef,
        className: "dataviews-filters__visibility-toggle",
        size: "compact",
        icon: funnel_default,
        disabled: hasPrimaryOrLockedFilters,
        accessibleWhenDisabled: true,
        ...hasVisibleFilters ? toggleFiltersButtonProps : addFilterButtonProps
      }
    );
    return /* @__PURE__ */ (0, import_jsx_runtime163.jsx)("div", { className: "dataviews-filters__container-visibility-toggle", children: !hasVisibleFilters ? /* @__PURE__ */ (0, import_jsx_runtime163.jsx)(
      AddFilterMenu,
      {
        filters,
        view,
        onChangeView: onChangeViewWithFilterVisibility,
        setOpenedFilter,
        triggerProps: { render: buttonComponent }
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime163.jsx)(
      FilterVisibilityToggle,
      {
        buttonRef,
        filtersCount: view.filters?.length,
        children: buttonComponent
      }
    ) });
  }
  function FilterVisibilityToggle({
    buttonRef,
    filtersCount,
    children
  }) {
    (0, import_element89.useEffect)(
      () => () => {
        buttonRef.current?.focus();
      },
      [buttonRef]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime163.jsxs)(import_jsx_runtime163.Fragment, { children: [
      children,
      !!filtersCount && /* @__PURE__ */ (0, import_jsx_runtime163.jsx)("span", { className: "dataviews-filters-toggle__count", children: filtersCount })
    ] });
  }
  var toggle_default = FiltersToggle;

  // packages/dataviews/build-module/components/dataviews-filters/filters-toggled.mjs
  var import_element90 = __toESM(require_element(), 1);
  var import_jsx_runtime164 = __toESM(require_jsx_runtime(), 1);
  function FiltersToggled(props) {
    const { isShowingFilter } = (0, import_element90.useContext)(dataviews_context_default);
    if (!isShowingFilter) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime164.jsx)(filters_default, { ...props });
  }
  var filters_toggled_default = FiltersToggled;

  // packages/dataviews/build-module/components/dataviews-layout/index.mjs
  var import_element91 = __toESM(require_element(), 1);
  var import_components44 = __toESM(require_components(), 1);
  var import_i18n52 = __toESM(require_i18n(), 1);
  var import_jsx_runtime165 = __toESM(require_jsx_runtime(), 1);
  function DataViewsLayout({ className }) {
    const {
      actions = [],
      data,
      fields: fields2,
      getItemId: getItemId2,
      getItemLevel: getItemLevel2,
      hasInitiallyLoaded,
      isLoading,
      view,
      onChangeView,
      selection,
      onChangeSelection,
      setOpenedFilter,
      onClickItem,
      isItemClickable,
      renderItemLink,
      defaultLayouts: defaultLayouts2,
      containerRef,
      empty = /* @__PURE__ */ (0, import_jsx_runtime165.jsx)("p", { children: (0, import_i18n52.__)("No results") })
    } = (0, import_element91.useContext)(dataviews_context_default);
    const isDelayedInitialLoading = useDelayedLoading(!hasInitiallyLoaded, {
      delay: 200
    });
    if (!hasInitiallyLoaded) {
      if (!isDelayedInitialLoading) {
        return null;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime165.jsx)("div", { className: "dataviews-loading", children: /* @__PURE__ */ (0, import_jsx_runtime165.jsx)("p", { children: /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(import_components44.Spinner, {}) }) });
    }
    const ViewComponent = VIEW_LAYOUTS.find(
      (v2) => v2.type === view.type && defaultLayouts2[v2.type]
    )?.component;
    return /* @__PURE__ */ (0, import_jsx_runtime165.jsx)("div", { className: "dataviews-layout__container", ref: containerRef, children: /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
      ViewComponent,
      {
        className,
        actions,
        data,
        fields: fields2,
        getItemId: getItemId2,
        getItemLevel: getItemLevel2,
        isLoading,
        onChangeView,
        onChangeSelection,
        selection,
        setOpenedFilter,
        onClickItem,
        renderItemLink,
        isItemClickable,
        view,
        empty
      }
    ) });
  }

  // packages/dataviews/build-module/components/dataviews-footer/index.mjs
  var import_element92 = __toESM(require_element(), 1);
  var import_jsx_runtime166 = __toESM(require_jsx_runtime(), 1);
  var EMPTY_ARRAY6 = [];
  function DataViewsFooter() {
    const {
      view,
      paginationInfo: { totalItems = 0, totalPages },
      data,
      actions = EMPTY_ARRAY6,
      isLoading,
      hasInitiallyLoaded
    } = (0, import_element92.useContext)(dataviews_context_default);
    const isRefreshing = !!isLoading && hasInitiallyLoaded && !!data?.length;
    const isDelayedRefreshing = useDelayedLoading(!!isRefreshing);
    const hasBulkActions = useSomeItemHasAPossibleBulkAction(actions, data) && [LAYOUT_TABLE, LAYOUT_GRID].includes(view.type);
    const hasPagination = hasPaginationControls(view, {
      totalItems,
      totalPages
    });
    if (!totalItems || !hasBulkActions && !hasPagination) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime166.jsx)(
      "div",
      {
        className: "dataviews-footer",
        inert: isRefreshing ? "true" : void 0,
        children: /* @__PURE__ */ (0, import_jsx_runtime166.jsxs)(
          Stack,
          {
            direction: "row",
            justify: "end",
            align: "center",
            className: clsx_default("dataviews-footer__content", {
              "is-refreshing": isDelayedRefreshing
            }),
            gap: "sm",
            children: [
              hasBulkActions && /* @__PURE__ */ (0, import_jsx_runtime166.jsx)(BulkActionsFooter, {}),
              /* @__PURE__ */ (0, import_jsx_runtime166.jsx)(dataviews_pagination_default, {})
            ]
          }
        )
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-search/index.mjs
  var import_i18n53 = __toESM(require_i18n(), 1);
  var import_element93 = __toESM(require_element(), 1);
  var import_components45 = __toESM(require_components(), 1);
  var import_compose14 = __toESM(require_compose(), 1);
  var import_jsx_runtime167 = __toESM(require_jsx_runtime(), 1);
  var DataViewsSearch = (0, import_element93.memo)(function Search({ label }) {
    const { view, onChangeView } = (0, import_element93.useContext)(dataviews_context_default);
    const [search, setSearch, debouncedSearch] = (0, import_compose14.useDebouncedInput)(
      view.search
    );
    (0, import_element93.useEffect)(() => {
      if (view.search !== debouncedSearch) {
        setSearch(view.search ?? "");
      }
    }, [view.search, setSearch]);
    const onChangeViewRef = (0, import_element93.useRef)(onChangeView);
    const viewRef = (0, import_element93.useRef)(view);
    (0, import_element93.useEffect)(() => {
      onChangeViewRef.current = onChangeView;
      viewRef.current = view;
    }, [onChangeView, view]);
    (0, import_element93.useEffect)(() => {
      if (debouncedSearch !== viewRef.current?.search) {
        onChangeViewRef.current({
          ...viewRef.current,
          page: view.page ? 1 : void 0,
          startPosition: view.startPosition ? 1 : void 0,
          search: debouncedSearch
        });
      }
    }, [debouncedSearch]);
    const searchLabel = label || (0, import_i18n53.__)("Search");
    return /* @__PURE__ */ (0, import_jsx_runtime167.jsx)(
      import_components45.SearchControl,
      {
        className: "dataviews-search",
        onChange: setSearch,
        value: search,
        label: searchLabel,
        placeholder: searchLabel,
        size: "compact"
      }
    );
  });
  var dataviews_search_default = DataViewsSearch;

  // packages/dataviews/build-module/components/dataviews-view-config/index.mjs
  var import_components46 = __toESM(require_components(), 1);
  var import_i18n54 = __toESM(require_i18n(), 1);
  var import_element94 = __toESM(require_element(), 1);
  var import_warning = __toESM(require_warning(), 1);
  var import_compose15 = __toESM(require_compose(), 1);
  var import_jsx_runtime168 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu5 } = unlock4(import_components46.privateApis);
  var DATAVIEWS_CONFIG_POPOVER_PROPS = {
    className: "dataviews-config__popover",
    placement: "bottom-end",
    offset: 9
  };
  function ViewTypeMenu() {
    const { view, onChangeView, defaultLayouts: defaultLayouts2 } = (0, import_element94.useContext)(dataviews_context_default);
    const availableLayouts = Object.keys(defaultLayouts2);
    if (availableLayouts.length <= 1) {
      return null;
    }
    const activeView = VIEW_LAYOUTS.find((v2) => view.type === v2.type);
    return /* @__PURE__ */ (0, import_jsx_runtime168.jsxs)(Menu5, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
        Menu5.TriggerButton,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
            import_components46.Button,
            {
              size: "compact",
              icon: activeView?.icon,
              label: (0, import_i18n54.__)("Layout")
            }
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(Menu5.Popover, { children: availableLayouts.map((layout) => {
        const config2 = VIEW_LAYOUTS.find(
          (v2) => v2.type === layout
        );
        if (!config2) {
          return null;
        }
        return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
          Menu5.RadioItem,
          {
            value: layout,
            name: "view-actions-available-view",
            checked: layout === view.type,
            hideOnClick: true,
            onChange: (e2) => {
              switch (e2.target.value) {
                case "list":
                case "grid":
                case "table":
                case "pickerGrid":
                case "pickerTable":
                case "pickerActivity":
                case "activity":
                  const viewWithoutLayout = { ...view };
                  if ("layout" in viewWithoutLayout) {
                    delete viewWithoutLayout.layout;
                  }
                  return onChangeView({
                    ...viewWithoutLayout,
                    type: e2.target.value,
                    ...defaultLayouts2[e2.target.value]
                  });
              }
              (0, import_warning.default)("Invalid dataview");
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(Menu5.ItemLabel, { children: config2.label })
          },
          layout
        );
      }) })
    ] });
  }
  function SortFieldControl() {
    const { view, fields: fields2, onChangeView } = (0, import_element94.useContext)(dataviews_context_default);
    const orderOptions = (0, import_element94.useMemo)(() => {
      const sortableFields = fields2.filter(
        (field) => field.enableSorting !== false
      );
      return sortableFields.map((field) => {
        return {
          label: field.label,
          value: field.id
        };
      });
    }, [fields2]);
    return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
      import_components46.SelectControl,
      {
        label: (0, import_i18n54.__)("Sort by"),
        value: view.sort?.field,
        options: orderOptions,
        onChange: (value) => {
          onChangeView({
            ...view,
            sort: {
              direction: view?.sort?.direction || "desc",
              field: value
            },
            showLevels: false
          });
        }
      }
    );
  }
  function SortDirectionControl() {
    const { view, fields: fields2, onChangeView } = (0, import_element94.useContext)(dataviews_context_default);
    const sortableFields = fields2.filter(
      (field) => field.enableSorting !== false
    );
    if (sortableFields.length === 0) {
      return null;
    }
    let value = view.sort?.direction;
    if (!value && view.sort?.field) {
      value = "desc";
    }
    return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
      import_components46.__experimentalToggleGroupControl,
      {
        className: "dataviews-view-config__sort-direction",
        isBlock: true,
        label: (0, import_i18n54.__)("Order"),
        value,
        onChange: (newDirection) => {
          if (newDirection === "asc" || newDirection === "desc") {
            onChangeView({
              ...view,
              sort: {
                direction: newDirection,
                field: view.sort?.field || // If there is no field assigned as the sorting field assign the first sortable field.
                fields2.find(
                  (field) => field.enableSorting !== false
                )?.id || ""
              },
              showLevels: false
            });
            return;
          }
          (0, import_warning.default)("Invalid direction");
        },
        children: SORTING_DIRECTIONS.map((direction) => {
          return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
            import_components46.__experimentalToggleGroupControlOptionIcon,
            {
              value: direction,
              icon: sortIcons[direction],
              label: sortLabels[direction]
            },
            direction
          );
        })
      }
    );
  }
  function ItemsPerPageControl() {
    const { view, config: config2, onChangeView } = (0, import_element94.useContext)(dataviews_context_default);
    const { infiniteScrollEnabled } = view;
    if (!config2 || !config2.perPageSizes || config2.perPageSizes.length < 2 || config2.perPageSizes.length > 6 || infiniteScrollEnabled) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
      import_components46.__experimentalToggleGroupControl,
      {
        isBlock: true,
        label: (0, import_i18n54.__)("Items per page"),
        value: view.perPage || 10,
        disabled: !view?.sort?.field,
        onChange: (newItemsPerPage) => {
          const newItemsPerPageNumber = typeof newItemsPerPage === "number" || newItemsPerPage === void 0 ? newItemsPerPage : parseInt(newItemsPerPage, 10);
          onChangeView({
            ...view,
            perPage: newItemsPerPageNumber,
            page: 1
          });
        },
        children: config2.perPageSizes.map((value) => {
          return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
            import_components46.__experimentalToggleGroupControlOption,
            {
              value,
              label: value.toString()
            },
            value
          );
        })
      }
    );
  }
  function ResetViewButton() {
    const { onReset } = (0, import_element94.useContext)(dataviews_context_default);
    if (onReset === void 0) {
      return null;
    }
    const isDisabled = onReset === false;
    return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
      import_components46.Button,
      {
        variant: "tertiary",
        size: "compact",
        disabled: isDisabled,
        accessibleWhenDisabled: true,
        className: "dataviews-view-config__reset-button",
        onClick: () => {
          if (typeof onReset === "function") {
            onReset();
          }
        },
        children: (0, import_i18n54.__)("Reset view")
      }
    );
  }
  function DataviewsViewConfigDropdown() {
    const { view, onReset } = (0, import_element94.useContext)(dataviews_context_default);
    const popoverId = (0, import_compose15.useInstanceId)(
      _DataViewsViewConfig,
      "dataviews-view-config-dropdown"
    );
    const activeLayout = VIEW_LAYOUTS.find(
      (layout) => layout.type === view.type
    );
    const isModified = typeof onReset === "function";
    return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
      import_components46.Dropdown,
      {
        expandOnMobile: true,
        popoverProps: {
          ...DATAVIEWS_CONFIG_POPOVER_PROPS,
          id: popoverId
        },
        renderToggle: ({ onToggle, isOpen }) => {
          return /* @__PURE__ */ (0, import_jsx_runtime168.jsxs)("div", { className: "dataviews-view-config__toggle-wrapper", children: [
            /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
              import_components46.Button,
              {
                size: "compact",
                icon: cog_default,
                label: (0, import_i18n54._x)(
                  "View options",
                  "View is used as a noun"
                ),
                onClick: onToggle,
                "aria-expanded": isOpen ? "true" : "false",
                "aria-controls": popoverId
              }
            ),
            isModified && /* @__PURE__ */ (0, import_jsx_runtime168.jsx)("span", { className: "dataviews-view-config__modified-indicator" })
          ] });
        },
        renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
          import_components46.__experimentalDropdownContentWrapper,
          {
            paddingSize: "medium",
            className: "dataviews-config__popover-content-wrapper",
            children: /* @__PURE__ */ (0, import_jsx_runtime168.jsxs)(
              Stack,
              {
                direction: "column",
                className: "dataviews-view-config",
                gap: "xl",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime168.jsxs)(
                    Stack,
                    {
                      direction: "row",
                      justify: "space-between",
                      align: "center",
                      className: "dataviews-view-config__header",
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(
                          import_components46.__experimentalHeading,
                          {
                            level: 2,
                            className: "dataviews-settings-section__title",
                            children: (0, import_i18n54.__)("Appearance")
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(ResetViewButton, {})
                      ]
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime168.jsxs)(Stack, { direction: "column", gap: "lg", children: [
                    /* @__PURE__ */ (0, import_jsx_runtime168.jsxs)(
                      Stack,
                      {
                        direction: "row",
                        gap: "sm",
                        className: "dataviews-view-config__sort-controls",
                        children: [
                          /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(SortFieldControl, {}),
                          /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(SortDirectionControl, {})
                        ]
                      }
                    ),
                    !!activeLayout?.viewConfigOptions && /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(activeLayout.viewConfigOptions, {}),
                    /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(ItemsPerPageControl, {}),
                    /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(PropertiesSection, {})
                  ] })
                ]
              }
            )
          }
        )
      }
    );
  }
  function _DataViewsViewConfig() {
    return /* @__PURE__ */ (0, import_jsx_runtime168.jsxs)(import_jsx_runtime168.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(ViewTypeMenu, {}),
      /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(DataviewsViewConfigDropdown, {})
    ] });
  }
  var DataViewsViewConfig = (0, import_element94.memo)(_DataViewsViewConfig);
  var dataviews_view_config_default = DataViewsViewConfig;

  // packages/dataviews/build-module/components/dataform-controls/checkbox.mjs
  var import_components47 = __toESM(require_components(), 1);
  var import_element95 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataform-controls/utils/get-custom-validity.mjs
  function getCustomValidity(isValid2, validity) {
    let customValidity;
    if (isValid2?.required && validity?.required) {
      customValidity = validity?.required?.message ? validity.required : void 0;
    } else if (isValid2?.pattern && validity?.pattern) {
      customValidity = validity.pattern;
    } else if (isValid2?.min && validity?.min) {
      customValidity = validity.min;
    } else if (isValid2?.max && validity?.max) {
      customValidity = validity.max;
    } else if (isValid2?.minLength && validity?.minLength) {
      customValidity = validity.minLength;
    } else if (isValid2?.maxLength && validity?.maxLength) {
      customValidity = validity.maxLength;
    } else if (isValid2?.elements && validity?.elements) {
      customValidity = validity.elements;
    } else if (validity?.custom) {
      customValidity = validity.custom;
    }
    return customValidity;
  }

  // packages/dataviews/build-module/components/dataform-controls/checkbox.mjs
  var import_jsx_runtime169 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedCheckboxControl } = unlock4(import_components47.privateApis);
  function Checkbox({
    field,
    onChange,
    data,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { getValue, setValue, label, description, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const onChangeControl = (0, import_element95.useCallback)(() => {
      onChange(
        setValue({ item: data, value: !getValue({ item: data }) })
      );
    }, [data, getValue, onChange, setValue]);
    return /* @__PURE__ */ (0, import_jsx_runtime169.jsx)(
      ValidatedCheckboxControl,
      {
        required: !!field.isValid?.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        hidden: hideLabelFromVision,
        label,
        help: description,
        checked: getValue({ item: data }),
        onChange: onChangeControl,
        disabled: disabled2
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/combobox.mjs
  var import_components48 = __toESM(require_components(), 1);
  var import_element96 = __toESM(require_element(), 1);
  var import_jsx_runtime170 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedComboboxControl } = unlock4(import_components48.privateApis);
  function Combobox3({
    data,
    field,
    onChange,
    hideLabelFromVision,
    validity
  }) {
    const { label, description, placeholder, getValue, setValue, isValid: isValid2 } = field;
    const value = getValue({ item: data }) ?? "";
    const onChangeControl = (0, import_element96.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue ?? "" })),
      [data, onChange, setValue]
    );
    const { elements: elements2, isLoading } = useElements({
      elements: field.elements,
      getElements: field.getElements
    });
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(import_components48.Spinner, {});
    }
    return /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(
      ValidatedComboboxControl,
      {
        required: !!field.isValid?.required,
        customValidity: getCustomValidity(isValid2, validity),
        label,
        value,
        help: description,
        placeholder,
        options: elements2,
        onChange: onChangeControl,
        hideLabelFromVision,
        allowReset: true,
        expandOnFocus: true
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/datetime.mjs
  var import_components50 = __toESM(require_components(), 1);
  var import_element99 = __toESM(require_element(), 1);
  var import_i18n56 = __toESM(require_i18n(), 1);
  var import_date3 = __toESM(require_date(), 1);

  // packages/dataviews/build-module/components/dataform-controls/utils/relative-date-control.mjs
  var import_components49 = __toESM(require_components(), 1);
  var import_element97 = __toESM(require_element(), 1);
  var import_i18n55 = __toESM(require_i18n(), 1);
  var import_jsx_runtime171 = __toESM(require_jsx_runtime(), 1);
  var TIME_UNITS_OPTIONS = {
    [OPERATOR_IN_THE_PAST]: [
      { value: "days", label: (0, import_i18n55.__)("Days") },
      { value: "weeks", label: (0, import_i18n55.__)("Weeks") },
      { value: "months", label: (0, import_i18n55.__)("Months") },
      { value: "years", label: (0, import_i18n55.__)("Years") }
    ],
    [OPERATOR_OVER]: [
      { value: "days", label: (0, import_i18n55.__)("Days ago") },
      { value: "weeks", label: (0, import_i18n55.__)("Weeks ago") },
      { value: "months", label: (0, import_i18n55.__)("Months ago") },
      { value: "years", label: (0, import_i18n55.__)("Years ago") }
    ]
  };
  function RelativeDateControl({
    className,
    data,
    field,
    onChange,
    hideLabelFromVision,
    operator
  }) {
    const options = TIME_UNITS_OPTIONS[operator === OPERATOR_IN_THE_PAST ? "inThePast" : "over"];
    const { id, label, description, getValue, setValue } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const fieldValue = getValue({ item: data });
    const { value: relValue = "", unit = options[0].value } = fieldValue && typeof fieldValue === "object" ? fieldValue : {};
    const onChangeValue = (0, import_element97.useCallback)(
      (newValue) => onChange(
        setValue({
          item: data,
          value: { value: Number(newValue), unit }
        })
      ),
      [onChange, setValue, data, unit]
    );
    const onChangeUnit = (0, import_element97.useCallback)(
      (newUnit) => onChange(
        setValue({
          item: data,
          value: { value: relValue, unit: newUnit }
        })
      ),
      [onChange, setValue, data, relValue]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime171.jsx)(
      import_components49.BaseControl,
      {
        id,
        className: clsx_default(className, "dataviews-controls__relative-date"),
        label,
        hideLabelFromVision,
        help: description,
        children: /* @__PURE__ */ (0, import_jsx_runtime171.jsxs)(Stack, { direction: "row", gap: "sm", children: [
          /* @__PURE__ */ (0, import_jsx_runtime171.jsx)(
            import_components49.__experimentalNumberControl,
            {
              className: "dataviews-controls__relative-date-number",
              spinControls: "none",
              min: 1,
              step: 1,
              value: relValue,
              onChange: onChangeValue,
              disabled: disabled2
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime171.jsx)(
            import_components49.SelectControl,
            {
              className: "dataviews-controls__relative-date-unit",
              label: (0, import_i18n55.__)("Unit"),
              value: unit,
              options,
              onChange: onChangeUnit,
              hideLabelFromVision: true,
              disabled: disabled2
            }
          )
        ] })
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/utils/use-disabled-date-matchers.mjs
  var import_element98 = __toESM(require_element(), 1);
  function useDisabledDateMatchers(isValid2, parseDateFn) {
    const minConstraint = typeof isValid2.min?.constraint === "string" ? isValid2.min.constraint : void 0;
    const maxConstraint = typeof isValid2.max?.constraint === "string" ? isValid2.max.constraint : void 0;
    const disabledMatchers = (0, import_element98.useMemo)(() => {
      const matchers = [];
      if (minConstraint) {
        const minDate = parseDateFn(minConstraint);
        if (minDate) {
          matchers.push({ before: minDate });
        }
      }
      if (maxConstraint) {
        const maxDate = parseDateFn(maxConstraint);
        if (maxDate) {
          matchers.push({ after: maxDate });
        }
      }
      return matchers.length > 0 ? matchers : void 0;
    }, [minConstraint, maxConstraint, parseDateFn]);
    return { minConstraint, maxConstraint, disabledMatchers };
  }

  // packages/dataviews/build-module/field-types/utils/parse-date-time.mjs
  var import_date2 = __toESM(require_date(), 1);
  function parseDateTime(dateTimeString) {
    if (!dateTimeString) {
      return null;
    }
    const parsed = (0, import_date2.getDate)(dateTimeString);
    return parsed && isValid(parsed) ? parsed : null;
  }

  // packages/dataviews/build-module/components/dataform-controls/datetime.mjs
  var import_jsx_runtime172 = __toESM(require_jsx_runtime(), 1);
  var { DateCalendar, ValidatedInputControl } = unlock4(import_components50.privateApis);
  var formatDateTime = (value) => {
    if (!value) {
      return "";
    }
    return (0, import_date3.dateI18n)("Y-m-d\\TH:i", (0, import_date3.getDate)(value));
  };
  function CalendarDateTimeControl({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity,
    config: config2
  }) {
    const { compact } = config2 || {};
    const { id, label, description, setValue, getValue, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const fieldValue = getValue({ item: data });
    const value = typeof fieldValue === "string" ? fieldValue : void 0;
    const [calendarMonth, setCalendarMonth] = (0, import_element99.useState)(() => {
      const parsedDate = parseDateTime(value);
      return parsedDate || /* @__PURE__ */ new Date();
    });
    const inputControlRef = (0, import_element99.useRef)(null);
    const validationTimeoutRef = (0, import_element99.useRef)(void 0);
    const previousFocusRef = (0, import_element99.useRef)(null);
    const { minConstraint, maxConstraint, disabledMatchers } = useDisabledDateMatchers(isValid2, parseDateTime);
    const onChangeCallback = (0, import_element99.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    (0, import_element99.useEffect)(() => {
      return () => {
        if (validationTimeoutRef.current) {
          clearTimeout(validationTimeoutRef.current);
        }
      };
    }, []);
    const onSelectDate = (0, import_element99.useCallback)(
      (newDate) => {
        let dateTimeValue;
        if (newDate) {
          const wpDate = (0, import_date3.dateI18n)("Y-m-d", newDate);
          let wpTime;
          if (value) {
            wpTime = (0, import_date3.dateI18n)("H:i", (0, import_date3.getDate)(value));
          } else {
            wpTime = (0, import_date3.dateI18n)("H:i", newDate);
          }
          const finalDateTime = (0, import_date3.getDate)(`${wpDate}T${wpTime}`);
          dateTimeValue = finalDateTime.toISOString();
          onChangeCallback(dateTimeValue);
          if (validationTimeoutRef.current) {
            clearTimeout(validationTimeoutRef.current);
          }
        } else {
          onChangeCallback(void 0);
        }
        previousFocusRef.current = inputControlRef.current && inputControlRef.current.ownerDocument.activeElement;
        validationTimeoutRef.current = setTimeout(() => {
          if (inputControlRef.current) {
            inputControlRef.current.focus();
            inputControlRef.current.blur();
            onChangeCallback(dateTimeValue);
            if (previousFocusRef.current && previousFocusRef.current instanceof HTMLElement) {
              previousFocusRef.current.focus();
            }
          }
        }, 0);
      },
      [onChangeCallback, value]
    );
    const handleManualDateTimeChange = (0, import_element99.useCallback)(
      (newValue) => {
        if (newValue) {
          const dateTime = (0, import_date3.getDate)(newValue);
          onChangeCallback(dateTime.toISOString());
          const parsedDate = parseDateTime(dateTime.toISOString());
          if (parsedDate) {
            setCalendarMonth(parsedDate);
          }
        } else {
          onChangeCallback(void 0);
        }
      },
      [onChangeCallback]
    );
    const { format: fieldFormat } = field;
    const weekStartsOn = fieldFormat.weekStartsOn ?? (0, import_date3.getSettings)().l10n.startOfWeek;
    const {
      timezone: { string: timezoneString }
    } = (0, import_date3.getSettings)();
    let displayLabel = label;
    if (isValid2?.required && !markWhenOptional && !hideLabelFromVision) {
      displayLabel = `${label} (${(0, import_i18n56.__)("Required")})`;
    } else if (!isValid2?.required && markWhenOptional && !hideLabelFromVision) {
      displayLabel = `${label} (${(0, import_i18n56.__)("Optional")})`;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime172.jsx)(
      import_components50.BaseControl,
      {
        id,
        label: displayLabel,
        help: description,
        hideLabelFromVision,
        children: /* @__PURE__ */ (0, import_jsx_runtime172.jsxs)(Stack, { direction: "column", gap: "lg", children: [
          /* @__PURE__ */ (0, import_jsx_runtime172.jsx)(
            ValidatedInputControl,
            {
              ref: inputControlRef,
              required: !!isValid2?.required,
              customValidity: getCustomValidity(isValid2, validity),
              type: "datetime-local",
              label: (0, import_i18n56.__)("Date time"),
              hideLabelFromVision: true,
              value: formatDateTime(value),
              onChange: handleManualDateTimeChange,
              disabled: disabled2,
              min: minConstraint ? formatDateTime(minConstraint) : void 0,
              max: maxConstraint ? formatDateTime(maxConstraint) : void 0
            }
          ),
          !compact && /* @__PURE__ */ (0, import_jsx_runtime172.jsx)(
            DateCalendar,
            {
              style: { width: "100%" },
              selected: value ? parseDateTime(value) || void 0 : void 0,
              onSelect: onSelectDate,
              month: calendarMonth,
              onMonthChange: setCalendarMonth,
              timeZone: timezoneString || void 0,
              weekStartsOn,
              disabled: disabled2 || disabledMatchers
            }
          )
        ] })
      }
    );
  }
  function DateTime({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    operator,
    validity,
    config: config2
  }) {
    if (operator === OPERATOR_IN_THE_PAST || operator === OPERATOR_OVER) {
      return /* @__PURE__ */ (0, import_jsx_runtime172.jsx)(
        RelativeDateControl,
        {
          className: "dataviews-controls__datetime",
          data,
          field,
          onChange,
          hideLabelFromVision,
          operator
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime172.jsx)(
      CalendarDateTimeControl,
      {
        data,
        field,
        onChange,
        hideLabelFromVision,
        markWhenOptional,
        validity,
        config: config2
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/date.mjs
  var import_components51 = __toESM(require_components(), 1);
  var import_a11y2 = __toESM(require_a11y(), 1);
  var import_element100 = __toESM(require_element(), 1);
  var import_i18n57 = __toESM(require_i18n(), 1);
  var import_date4 = __toESM(require_date(), 1);
  var import_jsx_runtime173 = __toESM(require_jsx_runtime(), 1);
  var { DateCalendar: DateCalendar2, DateRangeCalendar } = unlock4(import_components51.privateApis);
  var DATE_PRESETS = [
    {
      id: "today",
      label: (0, import_i18n57.__)("Today"),
      getValue: () => (0, import_date4.getDate)(null)
    },
    {
      id: "yesterday",
      label: (0, import_i18n57.__)("Yesterday"),
      getValue: () => {
        const today = (0, import_date4.getDate)(null);
        return subDays(today, 1);
      }
    },
    {
      id: "past-week",
      label: (0, import_i18n57.__)("Past week"),
      getValue: () => {
        const today = (0, import_date4.getDate)(null);
        return subDays(today, 7);
      }
    },
    {
      id: "past-month",
      label: (0, import_i18n57.__)("Past month"),
      getValue: () => {
        const today = (0, import_date4.getDate)(null);
        return subMonths(today, 1);
      }
    }
  ];
  var DATE_RANGE_PRESETS = [
    {
      id: "last-7-days",
      label: (0, import_i18n57.__)("Last 7 days"),
      getValue: () => {
        const today = (0, import_date4.getDate)(null);
        return [subDays(today, 7), today];
      }
    },
    {
      id: "last-30-days",
      label: (0, import_i18n57.__)("Last 30 days"),
      getValue: () => {
        const today = (0, import_date4.getDate)(null);
        return [subDays(today, 30), today];
      }
    },
    {
      id: "month-to-date",
      label: (0, import_i18n57.__)("Month to date"),
      getValue: () => {
        const today = (0, import_date4.getDate)(null);
        return [startOfMonth(today), today];
      }
    },
    {
      id: "last-year",
      label: (0, import_i18n57.__)("Last year"),
      getValue: () => {
        const today = (0, import_date4.getDate)(null);
        return [subYears(today, 1), today];
      }
    },
    {
      id: "year-to-date",
      label: (0, import_i18n57.__)("Year to date"),
      getValue: () => {
        const today = (0, import_date4.getDate)(null);
        return [startOfYear(today), today];
      }
    }
  ];
  var parseDate = (dateString) => {
    if (!dateString) {
      return null;
    }
    const parsed = (0, import_date4.getDate)(dateString);
    return parsed && isValid(parsed) ? parsed : null;
  };
  var formatDate = (date) => {
    if (!date) {
      return "";
    }
    return typeof date === "string" ? date : format(date, "yyyy-MM-dd");
  };
  function ValidatedDateControl({
    field,
    validity,
    inputRefs,
    isTouched,
    setIsTouched,
    children
  }) {
    const { isValid: isValid2 } = field;
    const [customValidity, setCustomValidity] = (0, import_element100.useState)(void 0);
    const validateRefs = (0, import_element100.useCallback)(() => {
      const refs = Array.isArray(inputRefs) ? inputRefs : [inputRefs];
      for (const ref of refs) {
        const input = ref.current;
        if (input && !input.validity.valid) {
          setCustomValidity({
            type: "invalid",
            message: input.validationMessage
          });
          return;
        }
      }
      setCustomValidity(void 0);
    }, [inputRefs]);
    (0, import_element100.useEffect)(() => {
      const refs = Array.isArray(inputRefs) ? inputRefs : [inputRefs];
      const result = validity ? getCustomValidity(isValid2, validity) : void 0;
      for (const ref of refs) {
        const input = ref.current;
        if (input) {
          input.setCustomValidity(
            result?.type === "invalid" && result.message ? result.message : ""
          );
        }
      }
    }, [inputRefs, isValid2, validity]);
    (0, import_element100.useEffect)(() => {
      const refs = Array.isArray(inputRefs) ? inputRefs : [inputRefs];
      const handleInvalid = (event) => {
        event.preventDefault();
        setIsTouched(true);
      };
      for (const ref of refs) {
        ref.current?.addEventListener("invalid", handleInvalid);
      }
      return () => {
        for (const ref of refs) {
          ref.current?.removeEventListener("invalid", handleInvalid);
        }
      };
    }, [inputRefs, setIsTouched]);
    (0, import_element100.useEffect)(() => {
      if (!isTouched) {
        return;
      }
      const result = validity ? getCustomValidity(isValid2, validity) : void 0;
      if (result) {
        setCustomValidity(result);
      } else {
        validateRefs();
      }
    }, [isTouched, isValid2, validity, validateRefs]);
    (0, import_element100.useEffect)(() => {
      if (isTouched && customValidity?.message) {
        (0, import_a11y2.speak)(customValidity.message);
      }
    }, [isTouched, customValidity?.message]);
    const onBlur = (event) => {
      if (isTouched) {
        return;
      }
      if (!event.relatedTarget || !event.currentTarget.contains(event.relatedTarget)) {
        setIsTouched(true);
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime173.jsxs)("div", { onBlur, children: [
      children,
      customValidity && /* @__PURE__ */ (0, import_jsx_runtime173.jsxs)(
        "p",
        {
          className: clsx_default(
            "components-validated-control__indicator",
            customValidity.type === "invalid" ? "is-invalid" : void 0
          ),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
              import_components51.Icon,
              {
                className: "components-validated-control__indicator-icon",
                icon: error_default,
                size: 16,
                fill: "currentColor"
              }
            ),
            customValidity.message
          ]
        }
      )
    ] });
  }
  function CalendarDateControl({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const {
      id,
      label,
      description,
      setValue,
      getValue,
      isValid: isValid2,
      format: fieldFormat
    } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const [selectedPresetId, setSelectedPresetId] = (0, import_element100.useState)(
      null
    );
    const weekStartsOn = fieldFormat.weekStartsOn ?? (0, import_date4.getSettings)().l10n.startOfWeek;
    const fieldValue = getValue({ item: data });
    const value = typeof fieldValue === "string" ? fieldValue : void 0;
    const [calendarMonth, setCalendarMonth] = (0, import_element100.useState)(() => {
      const parsedDate = parseDate(value);
      return parsedDate || /* @__PURE__ */ new Date();
    });
    const [isTouched, setIsTouched] = (0, import_element100.useState)(false);
    const validityTargetRef = (0, import_element100.useRef)(null);
    const { minConstraint, maxConstraint, disabledMatchers } = useDisabledDateMatchers(isValid2, parseDate);
    const onChangeCallback = (0, import_element100.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    const onSelectDate = (0, import_element100.useCallback)(
      (newDate) => {
        const dateValue = newDate ? format(newDate, "yyyy-MM-dd") : void 0;
        onChangeCallback(dateValue);
        setSelectedPresetId(null);
        setIsTouched(true);
      },
      [onChangeCallback]
    );
    const handlePresetClick = (0, import_element100.useCallback)(
      (preset) => {
        const presetDate = preset.getValue();
        const dateValue = formatDate(presetDate);
        setCalendarMonth(presetDate);
        onChangeCallback(dateValue);
        setSelectedPresetId(preset.id);
        setIsTouched(true);
      },
      [onChangeCallback]
    );
    const handleManualDateChange = (0, import_element100.useCallback)(
      (newValue) => {
        onChangeCallback(newValue);
        if (newValue) {
          const parsedDate = parseDate(newValue);
          if (parsedDate) {
            setCalendarMonth(parsedDate);
          }
        }
        setSelectedPresetId(null);
        setIsTouched(true);
      },
      [onChangeCallback]
    );
    const {
      timezone: { string: timezoneString }
    } = (0, import_date4.getSettings)();
    let displayLabel = label;
    if (isValid2?.required && !markWhenOptional) {
      displayLabel = `${label} (${(0, import_i18n57.__)("Required")})`;
    } else if (!isValid2?.required && markWhenOptional) {
      displayLabel = `${label} (${(0, import_i18n57.__)("Optional")})`;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
      ValidatedDateControl,
      {
        field,
        validity,
        inputRefs: validityTargetRef,
        isTouched,
        setIsTouched,
        children: /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
          import_components51.BaseControl,
          {
            id,
            className: "dataviews-controls__date",
            label: displayLabel,
            help: description,
            hideLabelFromVision,
            children: /* @__PURE__ */ (0, import_jsx_runtime173.jsxs)(Stack, { direction: "column", gap: "lg", children: [
              /* @__PURE__ */ (0, import_jsx_runtime173.jsxs)(
                Stack,
                {
                  direction: "row",
                  gap: "sm",
                  wrap: "wrap",
                  justify: "flex-start",
                  children: [
                    DATE_PRESETS.map((preset) => {
                      const isSelected2 = selectedPresetId === preset.id;
                      return /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
                        import_components51.Button,
                        {
                          className: "dataviews-controls__date-preset",
                          variant: "tertiary",
                          isPressed: isSelected2,
                          size: "small",
                          disabled: disabled2,
                          accessibleWhenDisabled: true,
                          onClick: () => handlePresetClick(preset),
                          children: preset.label
                        },
                        preset.id
                      );
                    }),
                    /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
                      import_components51.Button,
                      {
                        className: "dataviews-controls__date-preset",
                        variant: "tertiary",
                        isPressed: !selectedPresetId,
                        size: "small",
                        disabled: !!selectedPresetId || disabled2,
                        accessibleWhenDisabled: true,
                        children: (0, import_i18n57.__)("Custom")
                      }
                    )
                  ]
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
                import_components51.__experimentalInputControl,
                {
                  ref: validityTargetRef,
                  type: "date",
                  label: (0, import_i18n57.__)("Date"),
                  hideLabelFromVision: true,
                  value,
                  onChange: handleManualDateChange,
                  required: !!field.isValid?.required,
                  disabled: disabled2,
                  min: minConstraint,
                  max: maxConstraint
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
                DateCalendar2,
                {
                  style: { width: "100%" },
                  selected: value ? parseDate(value) || void 0 : void 0,
                  onSelect: onSelectDate,
                  month: calendarMonth,
                  onMonthChange: setCalendarMonth,
                  timeZone: timezoneString || void 0,
                  weekStartsOn,
                  disabled: disabled2 || disabledMatchers,
                  disableNavigation: disabled2
                }
              )
            ] })
          }
        )
      }
    );
  }
  function CalendarDateRangeControl({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const {
      id,
      label,
      description,
      getValue,
      setValue,
      isValid: isValid2,
      format: fieldFormat
    } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    let value;
    const fieldValue = getValue({ item: data });
    if (Array.isArray(fieldValue) && fieldValue.length === 2 && fieldValue.every((date) => typeof date === "string")) {
      value = fieldValue;
    }
    const weekStartsOn = fieldFormat.weekStartsOn ?? (0, import_date4.getSettings)().l10n.startOfWeek;
    const { minConstraint, maxConstraint, disabledMatchers } = useDisabledDateMatchers(isValid2, parseDate);
    const onChangeCallback = (0, import_element100.useCallback)(
      (newValue) => {
        onChange(
          setValue({
            item: data,
            value: newValue
          })
        );
      },
      [data, onChange, setValue]
    );
    const [selectedPresetId, setSelectedPresetId] = (0, import_element100.useState)(
      null
    );
    const selectedRange = (0, import_element100.useMemo)(() => {
      if (!value) {
        return { from: void 0, to: void 0 };
      }
      const [from, to2] = value;
      return {
        from: parseDate(from) || void 0,
        to: parseDate(to2) || void 0
      };
    }, [value]);
    const [calendarMonth, setCalendarMonth] = (0, import_element100.useState)(() => {
      return selectedRange.from || /* @__PURE__ */ new Date();
    });
    const [isTouched, setIsTouched] = (0, import_element100.useState)(false);
    const fromInputRef = (0, import_element100.useRef)(null);
    const toInputRef = (0, import_element100.useRef)(null);
    const updateDateRange = (0, import_element100.useCallback)(
      (fromDate, toDate2) => {
        if (fromDate && toDate2) {
          onChangeCallback([
            formatDate(fromDate),
            formatDate(toDate2)
          ]);
        } else if (!fromDate && !toDate2) {
          onChangeCallback(void 0);
        }
      },
      [onChangeCallback]
    );
    const onSelectCalendarRange = (0, import_element100.useCallback)(
      (newRange) => {
        updateDateRange(newRange?.from, newRange?.to);
        setSelectedPresetId(null);
        setIsTouched(true);
      },
      [updateDateRange]
    );
    const handlePresetClick = (0, import_element100.useCallback)(
      (preset) => {
        const [startDate2, endDate] = preset.getValue();
        setCalendarMonth(startDate2);
        updateDateRange(startDate2, endDate);
        setSelectedPresetId(preset.id);
        setIsTouched(true);
      },
      [updateDateRange]
    );
    const handleManualDateChange = (0, import_element100.useCallback)(
      (fromOrTo, newValue) => {
        const [currentFrom, currentTo] = value || [
          void 0,
          void 0
        ];
        const updatedFrom = fromOrTo === "from" ? newValue : currentFrom;
        const updatedTo = fromOrTo === "to" ? newValue : currentTo;
        updateDateRange(updatedFrom, updatedTo);
        if (newValue) {
          const parsedDate = parseDate(newValue);
          if (parsedDate) {
            setCalendarMonth(parsedDate);
          }
        }
        setSelectedPresetId(null);
        setIsTouched(true);
      },
      [value, updateDateRange]
    );
    const { timezone } = (0, import_date4.getSettings)();
    let displayLabel = label;
    if (field.isValid?.required && !markWhenOptional) {
      displayLabel = `${label} (${(0, import_i18n57.__)("Required")})`;
    } else if (!field.isValid?.required && markWhenOptional) {
      displayLabel = `${label} (${(0, import_i18n57.__)("Optional")})`;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
      ValidatedDateControl,
      {
        field,
        validity,
        inputRefs: [fromInputRef, toInputRef],
        isTouched,
        setIsTouched,
        children: /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
          import_components51.BaseControl,
          {
            id,
            className: "dataviews-controls__date",
            label: displayLabel,
            help: description,
            hideLabelFromVision,
            children: /* @__PURE__ */ (0, import_jsx_runtime173.jsxs)(Stack, { direction: "column", gap: "lg", children: [
              /* @__PURE__ */ (0, import_jsx_runtime173.jsxs)(
                Stack,
                {
                  direction: "row",
                  gap: "sm",
                  wrap: "wrap",
                  justify: "flex-start",
                  children: [
                    DATE_RANGE_PRESETS.map((preset) => {
                      const isSelected2 = selectedPresetId === preset.id;
                      return /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
                        import_components51.Button,
                        {
                          className: "dataviews-controls__date-preset",
                          variant: "tertiary",
                          isPressed: isSelected2,
                          size: "small",
                          disabled: disabled2,
                          accessibleWhenDisabled: true,
                          onClick: () => handlePresetClick(preset),
                          children: preset.label
                        },
                        preset.id
                      );
                    }),
                    /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
                      import_components51.Button,
                      {
                        className: "dataviews-controls__date-preset",
                        variant: "tertiary",
                        isPressed: !selectedPresetId,
                        size: "small",
                        accessibleWhenDisabled: true,
                        disabled: !!selectedPresetId || disabled2,
                        children: (0, import_i18n57.__)("Custom")
                      }
                    )
                  ]
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime173.jsxs)(
                Stack,
                {
                  direction: "row",
                  gap: "sm",
                  justify: "space-between",
                  className: "dataviews-controls__date-range-inputs",
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
                      import_components51.__experimentalInputControl,
                      {
                        ref: fromInputRef,
                        type: "date",
                        label: (0, import_i18n57.__)("From"),
                        hideLabelFromVision: true,
                        value: value?.[0],
                        onChange: (newValue) => handleManualDateChange("from", newValue),
                        required: !!field.isValid?.required,
                        disabled: disabled2,
                        min: minConstraint,
                        max: maxConstraint
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
                      import_components51.__experimentalInputControl,
                      {
                        ref: toInputRef,
                        type: "date",
                        label: (0, import_i18n57.__)("To"),
                        hideLabelFromVision: true,
                        value: value?.[1],
                        onChange: (newValue) => handleManualDateChange("to", newValue),
                        required: !!field.isValid?.required,
                        disabled: disabled2,
                        min: minConstraint,
                        max: maxConstraint
                      }
                    )
                  ]
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
                DateRangeCalendar,
                {
                  style: { width: "100%" },
                  selected: selectedRange,
                  onSelect: onSelectCalendarRange,
                  month: calendarMonth,
                  onMonthChange: setCalendarMonth,
                  timeZone: timezone.string || void 0,
                  weekStartsOn,
                  disabled: disabled2 || disabledMatchers
                }
              )
            ] })
          }
        )
      }
    );
  }
  function DateControl({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    operator,
    validity
  }) {
    if (operator === OPERATOR_IN_THE_PAST || operator === OPERATOR_OVER) {
      return /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
        RelativeDateControl,
        {
          className: "dataviews-controls__date",
          data,
          field,
          onChange,
          hideLabelFromVision,
          operator
        }
      );
    }
    if (operator === OPERATOR_BETWEEN) {
      return /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
        CalendarDateRangeControl,
        {
          data,
          field,
          onChange,
          hideLabelFromVision,
          markWhenOptional,
          validity
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
      CalendarDateControl,
      {
        data,
        field,
        onChange,
        hideLabelFromVision,
        markWhenOptional,
        validity
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/select.mjs
  var import_components52 = __toESM(require_components(), 1);
  var import_element101 = __toESM(require_element(), 1);
  var import_jsx_runtime174 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedSelectControl } = unlock4(import_components52.privateApis);
  function Select({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { type, label, description, getValue, setValue, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const isMultiple = type === "array";
    const value = getValue({ item: data }) ?? (isMultiple ? [] : "");
    const onChangeControl = (0, import_element101.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    const { elements: elements2, isLoading } = useElements({
      elements: field.elements,
      getElements: field.getElements
    });
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime174.jsx)(import_components52.Spinner, {});
    }
    return /* @__PURE__ */ (0, import_jsx_runtime174.jsx)(
      ValidatedSelectControl,
      {
        required: !!field.isValid?.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        label,
        value,
        help: description,
        options: elements2,
        onChange: onChangeControl,
        hideLabelFromVision,
        multiple: isMultiple,
        disabled: disabled2
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/adaptive-select.mjs
  var import_jsx_runtime175 = __toESM(require_jsx_runtime(), 1);
  var ELEMENTS_THRESHOLD = 10;
  function AdaptiveSelect(props) {
    const { field } = props;
    const { elements: elements2 } = useElements({
      elements: field.elements,
      getElements: field.getElements
    });
    if (elements2.length >= ELEMENTS_THRESHOLD) {
      return /* @__PURE__ */ (0, import_jsx_runtime175.jsx)(Combobox3, { ...props });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime175.jsx)(Select, { ...props });
  }

  // packages/dataviews/build-module/components/dataform-controls/email.mjs
  var import_components54 = __toESM(require_components(), 1);

  // packages/dataviews/build-module/components/dataform-controls/utils/validated-input.mjs
  var import_components53 = __toESM(require_components(), 1);
  var import_element102 = __toESM(require_element(), 1);
  var import_jsx_runtime176 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedInputControl: ValidatedInputControl2 } = unlock4(import_components53.privateApis);
  function ValidatedText({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    type,
    prefix: prefix2,
    suffix,
    validity
  }) {
    const { label, placeholder, description, getValue, setValue, isValid: isValid2 } = field;
    const value = getValue({ item: data });
    const disabled2 = field.isDisabled({ item: data, field });
    const onChangeControl = (0, import_element102.useCallback)(
      (newValue) => onChange(
        setValue({
          item: data,
          value: newValue
        })
      ),
      [data, setValue, onChange]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
      ValidatedInputControl2,
      {
        required: !!isValid2.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        label,
        placeholder,
        value: value ?? "",
        help: description,
        onChange: onChangeControl,
        hideLabelFromVision,
        type,
        prefix: prefix2,
        suffix,
        disabled: disabled2,
        pattern: isValid2.pattern ? isValid2.pattern.constraint : void 0,
        minLength: isValid2.minLength ? isValid2.minLength.constraint : void 0,
        maxLength: isValid2.maxLength ? isValid2.maxLength.constraint : void 0
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/email.mjs
  var import_jsx_runtime177 = __toESM(require_jsx_runtime(), 1);
  function Email({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime177.jsx)(
      ValidatedText,
      {
        ...{
          data,
          field,
          onChange,
          hideLabelFromVision,
          markWhenOptional,
          validity,
          type: "email",
          prefix: /* @__PURE__ */ (0, import_jsx_runtime177.jsx)(import_components54.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime177.jsx)(import_components54.Icon, { icon: envelope_default }) })
        }
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/telephone.mjs
  var import_components55 = __toESM(require_components(), 1);
  var import_jsx_runtime178 = __toESM(require_jsx_runtime(), 1);
  function Telephone({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime178.jsx)(
      ValidatedText,
      {
        ...{
          data,
          field,
          onChange,
          hideLabelFromVision,
          markWhenOptional,
          validity,
          type: "tel",
          prefix: /* @__PURE__ */ (0, import_jsx_runtime178.jsx)(import_components55.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime178.jsx)(import_components55.Icon, { icon: mobile_default }) })
        }
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/url.mjs
  var import_components56 = __toESM(require_components(), 1);
  var import_jsx_runtime179 = __toESM(require_jsx_runtime(), 1);
  function Url({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(
      ValidatedText,
      {
        ...{
          data,
          field,
          onChange,
          hideLabelFromVision,
          markWhenOptional,
          validity,
          type: "url",
          prefix: /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(import_components56.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(import_components56.Icon, { icon: link_default }) })
        }
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/utils/validated-number.mjs
  var import_components57 = __toESM(require_components(), 1);
  var import_element103 = __toESM(require_element(), 1);
  var import_i18n58 = __toESM(require_i18n(), 1);
  var import_jsx_runtime180 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedNumberControl } = unlock4(import_components57.privateApis);
  function toNumberOrEmpty(value) {
    if (value === "" || value === void 0) {
      return "";
    }
    const number = Number(value);
    return Number.isFinite(number) ? number : "";
  }
  function BetweenControls({
    value,
    onChange,
    hideLabelFromVision,
    step
  }) {
    const [min2 = "", max2 = ""] = value;
    const onChangeMin = (0, import_element103.useCallback)(
      (newValue) => onChange([toNumberOrEmpty(newValue), max2]),
      [onChange, max2]
    );
    const onChangeMax = (0, import_element103.useCallback)(
      (newValue) => onChange([min2, toNumberOrEmpty(newValue)]),
      [onChange, min2]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
      import_components57.BaseControl,
      {
        help: (0, import_i18n58.__)("The max. value must be greater than the min. value."),
        children: /* @__PURE__ */ (0, import_jsx_runtime180.jsxs)(import_components57.Flex, { direction: "row", gap: 4, children: [
          /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
            import_components57.__experimentalNumberControl,
            {
              label: (0, import_i18n58.__)("Min."),
              value: min2,
              max: max2 ? Number(max2) - step : void 0,
              onChange: onChangeMin,
              hideLabelFromVision,
              step
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
            import_components57.__experimentalNumberControl,
            {
              label: (0, import_i18n58.__)("Max."),
              value: max2,
              min: min2 ? Number(min2) + step : void 0,
              onChange: onChangeMax,
              hideLabelFromVision,
              step
            }
          )
        ] })
      }
    );
  }
  function ValidatedNumber({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    operator,
    validity
  }) {
    const decimals = field.format?.decimals ?? 0;
    const step = Math.pow(10, Math.abs(decimals) * -1);
    const { label, description, getValue, setValue, isValid: isValid2 } = field;
    const value = getValue({ item: data }) ?? "";
    const disabled2 = field.isDisabled({ item: data, field });
    const onChangeControl = (0, import_element103.useCallback)(
      (newValue) => {
        onChange(
          setValue({
            item: data,
            // Do not convert an empty string or undefined to a number,
            // otherwise there's a mismatch between the UI control (empty)
            // and the data relied by onChange (0).
            value: ["", void 0].includes(newValue) ? void 0 : Number(newValue)
          })
        );
      },
      [data, onChange, setValue]
    );
    const onChangeBetweenControls = (0, import_element103.useCallback)(
      (newValue) => {
        onChange(
          setValue({
            item: data,
            value: newValue
          })
        );
      },
      [data, onChange, setValue]
    );
    if (operator === OPERATOR_BETWEEN) {
      let valueBetween = ["", ""];
      if (Array.isArray(value) && value.length === 2 && value.every(
        (element) => typeof element === "number" || element === ""
      )) {
        valueBetween = value;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
        BetweenControls,
        {
          value: valueBetween,
          onChange: onChangeBetweenControls,
          hideLabelFromVision,
          step
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
      ValidatedNumberControl,
      {
        required: !!isValid2.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        label,
        help: description,
        value,
        onChange: onChangeControl,
        hideLabelFromVision,
        step,
        min: isValid2.min ? isValid2.min.constraint : void 0,
        max: isValid2.max ? isValid2.max.constraint : void 0,
        disabled: disabled2
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/integer.mjs
  var import_jsx_runtime181 = __toESM(require_jsx_runtime(), 1);
  function Integer(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime181.jsx)(ValidatedNumber, { ...props });
  }

  // packages/dataviews/build-module/components/dataform-controls/number.mjs
  var import_jsx_runtime182 = __toESM(require_jsx_runtime(), 1);
  function Number2(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime182.jsx)(ValidatedNumber, { ...props });
  }

  // packages/dataviews/build-module/components/dataform-controls/radio.mjs
  var import_components58 = __toESM(require_components(), 1);
  var import_element104 = __toESM(require_element(), 1);
  var import_jsx_runtime183 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedRadioControl } = unlock4(import_components58.privateApis);
  function Radio({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { label, description, getValue, setValue, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const { elements: elements2, isLoading } = useElements({
      elements: field.elements,
      getElements: field.getElements
    });
    const value = getValue({ item: data });
    const onChangeControl = (0, import_element104.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(import_components58.Spinner, {});
    }
    return /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(
      ValidatedRadioControl,
      {
        required: !!field.isValid?.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        label,
        help: description,
        onChange: onChangeControl,
        options: elements2,
        selected: value,
        hideLabelFromVision,
        disabled: disabled2
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/text.mjs
  var import_element105 = __toESM(require_element(), 1);
  var import_jsx_runtime184 = __toESM(require_jsx_runtime(), 1);
  function Text3({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    config: config2,
    validity
  }) {
    const { prefix: prefix2, suffix } = config2 || {};
    return /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
      ValidatedText,
      {
        ...{
          data,
          field,
          onChange,
          hideLabelFromVision,
          markWhenOptional,
          validity,
          prefix: prefix2 ? (0, import_element105.createElement)(prefix2) : void 0,
          suffix: suffix ? (0, import_element105.createElement)(suffix) : void 0
        }
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/toggle.mjs
  var import_components59 = __toESM(require_components(), 1);
  var import_element106 = __toESM(require_element(), 1);
  var import_jsx_runtime185 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedToggleControl } = unlock4(import_components59.privateApis);
  function Toggle({
    field,
    onChange,
    data,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { label, description, getValue, setValue, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const onChangeControl = (0, import_element106.useCallback)(() => {
      onChange(
        setValue({ item: data, value: !getValue({ item: data }) })
      );
    }, [onChange, setValue, data, getValue]);
    return /* @__PURE__ */ (0, import_jsx_runtime185.jsx)(
      ValidatedToggleControl,
      {
        required: !!isValid2.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        hidden: hideLabelFromVision,
        label,
        help: description,
        checked: getValue({ item: data }),
        onChange: onChangeControl,
        disabled: disabled2
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/textarea.mjs
  var import_components60 = __toESM(require_components(), 1);
  var import_element107 = __toESM(require_element(), 1);
  var import_jsx_runtime186 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedTextareaControl } = unlock4(import_components60.privateApis);
  function Textarea({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    config: config2,
    validity
  }) {
    const { rows = 4 } = config2 || {};
    const disabled2 = field.isDisabled({ item: data, field });
    const { label, placeholder, description, setValue, isValid: isValid2 } = field;
    const value = field.getValue({ item: data });
    const onChangeControl = (0, import_element107.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime186.jsx)(
      ValidatedTextareaControl,
      {
        required: !!isValid2.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        label,
        placeholder,
        value: value ?? "",
        help: description,
        onChange: onChangeControl,
        rows,
        disabled: disabled2,
        minLength: isValid2.minLength ? isValid2.minLength.constraint : void 0,
        maxLength: isValid2.maxLength ? isValid2.maxLength.constraint : void 0,
        __next40pxDefaultSize: true,
        hideLabelFromVision
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/richtext/index.mjs
  var import_element109 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataform-controls/richtext/control.mjs
  var import_components61 = __toESM(require_components(), 1);
  var import_compose16 = __toESM(require_compose(), 1);
  var import_element108 = __toESM(require_element(), 1);
  var import_rich_text2 = __toESM(require_rich_text(), 1);

  // packages/dataviews/build-module/components/dataform-controls/richtext/utils.mjs
  var EMPTY_ARRAY7 = [];
  function getAllowedFormats({
    allowedFormats,
    disableFormats
  }) {
    if (disableFormats) {
      return EMPTY_ARRAY7;
    }
    return allowedFormats;
  }

  // packages/dataviews/build-module/components/dataform-controls/richtext/format-edit.mjs
  var import_rich_text = __toESM(require_rich_text(), 1);
  var import_jsx_runtime187 = __toESM(require_jsx_runtime(), 1);
  var import_react33 = __toESM(require_react(), 1);
  var EMPTY_CONTEXT = {};
  function Edit({
    onChange,
    onFocus,
    value,
    forwardedRef,
    settings: settings2,
    isVisible: isVisible2
  }) {
    const { name: name2, edit: EditFunction } = settings2;
    if (!EditFunction) {
      return null;
    }
    const activeFormat = (0, import_rich_text.getActiveFormat)(value, name2);
    const isActive = activeFormat !== void 0;
    const activeObject = (0, import_rich_text.getActiveObject)(value);
    const isObjectActive = activeObject !== void 0 && activeObject.type === name2;
    return /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
      EditFunction,
      {
        isActive,
        isVisible: isVisible2,
        activeAttributes: isActive ? activeFormat.attributes || {} : {},
        isObjectActive,
        activeObjectAttributes: isObjectActive ? activeObject.attributes || {} : {},
        value,
        onChange,
        onFocus,
        contentRef: forwardedRef,
        context: EMPTY_CONTEXT
      },
      name2
    );
  }
  function FormatEdit({
    formatTypes,
    ...props
  }) {
    return formatTypes.map((settings2) => /* @__PURE__ */ (0, import_react33.createElement)(Edit, { settings: settings2, ...props, key: settings2.name }));
  }

  // packages/dataviews/build-module/components/dataform-controls/richtext/control.mjs
  var import_jsx_runtime188 = __toESM(require_jsx_runtime(), 1);
  var {
    ValidatedContentEditableControl: RichTextControlShell,
    withIgnoreIMEEvents
  } = unlock4(import_components61.privateApis);
  var {
    useRichText,
    KeyboardShortcutContext,
    InputEventContext,
    shortcutsListener,
    inputEventsListener
  } = unlock4(import_rich_text2.privateApis);
  var EMPTY_COMPLETERS = [];
  function RichTextControl({
    label,
    value: attrValue,
    onChange,
    placeholder,
    id,
    clientId,
    className,
    hideLabelFromVision,
    help,
    disabled: disabled2,
    required,
    markWhenOptional,
    customValidity,
    allowedFormats,
    disableFormats,
    withoutInteractiveFormatting,
    preserveWhiteSpace,
    disableLineBreaks,
    focusOnMount,
    completers = EMPTY_COMPLETERS
  }) {
    const [selection, setSelection] = (0, import_element108.useState)({
      start: void 0,
      end: void 0
    });
    const [isSelected2, setIsSelected] = (0, import_element108.useState)(false);
    const anchorRef = (0, import_element108.useRef)(void 0);
    const inputEvents = (0, import_element108.useRef)(/* @__PURE__ */ new Set());
    const keyboardShortcuts = (0, import_element108.useRef)(
      /* @__PURE__ */ new Set()
    );
    const focusOutside = (0, import_compose16.__experimentalUseFocusOutside)(() => setIsSelected(false));
    const adjustedAllowedFormats = getAllowedFormats({
      allowedFormats,
      disableFormats
    });
    const {
      value,
      onChange: onRichTextChange,
      ref: richTextRef,
      formatTypes,
      getValue
    } = useRichText({
      value: attrValue,
      onChange,
      selectionStart: selection.start,
      selectionEnd: selection.end,
      onSelectionChange: (start2, end) => setSelection({ start: start2, end }),
      __unstableIsSelected: isSelected2,
      preserveWhiteSpace: !!preserveWhiteSpace,
      placeholder,
      __unstableDisableFormats: disableFormats,
      allowedFormats: adjustedAllowedFormats,
      withoutInteractiveFormatting,
      __unstableFormatTypeHandlerContext: (0, import_element108.useMemo)(
        () => ({
          richTextIdentifier: id,
          blockClientId: clientId
        }),
        [id, clientId]
      )
    });
    function onFocus() {
      anchorRef.current?.focus();
    }
    const eventListenersPropsRef = (0, import_element108.useRef)({
      keyboardShortcuts,
      inputEvents
    });
    const inputRulePropsRef = (0, import_element108.useRef)({
      formatTypes,
      getValue,
      onChange: onRichTextChange
    });
    (0, import_element108.useInsertionEffect)(() => {
      inputRulePropsRef.current = {
        formatTypes,
        getValue,
        onChange: onRichTextChange
      };
    });
    const enterRef = (0, import_compose16.useRefEffect)(
      (element) => {
        if (disabled2) {
          return;
        }
        const onKeyDown = withIgnoreIMEEvents((event) => {
          if (event.key !== "Enter" || event.defaultPrevented || event.metaKey || event.ctrlKey) {
            return;
          }
          event.preventDefault();
          if (disableLineBreaks) {
            return;
          }
          const { getValue: getCurrentValue2, onChange: handleChange } = inputRulePropsRef.current;
          const current = getCurrentValue2();
          handleChange(
            (0, import_rich_text2.insert)(
              current,
              "\n",
              current.start ?? current.text.length,
              current.end ?? current.text.length
            )
          );
        });
        element.addEventListener("keydown", onKeyDown);
        return () => element.removeEventListener("keydown", onKeyDown);
      },
      [disableLineBreaks, disabled2]
    );
    const eventListenersRef = (0, import_compose16.useRefEffect)(
      (element) => {
        if (!isSelected2) {
          return;
        }
        const cleanupShortcuts = shortcutsListener(
          eventListenersPropsRef
        )(element);
        const cleanupInputEvents = inputEventsListener(
          eventListenersPropsRef
        )(element);
        function onFormatInput(event) {
          if (event.inputType !== "insertText" && event.type !== "compositionend") {
            return;
          }
          const {
            formatTypes: types,
            getValue: getCurrentValue2,
            onChange: handleChange
          } = inputRulePropsRef.current;
          const current = getCurrentValue2();
          const transformed = types.reduce(
            (accumulator, {
              __unstableInputRule
            }) => __unstableInputRule ? __unstableInputRule(accumulator) : accumulator,
            current
          );
          if (transformed !== current) {
            handleChange({
              ...transformed,
              activeFormats: current.activeFormats
            });
          }
        }
        element.addEventListener("input", onFormatInput);
        element.addEventListener("compositionend", onFormatInput);
        return () => {
          cleanupShortcuts();
          cleanupInputEvents();
          element.removeEventListener("input", onFormatInput);
          element.removeEventListener("compositionend", onFormatInput);
        };
      },
      [isSelected2]
    );
    const { ref: autocompleteRef, ...autocompleteProps } = (0, import_components61.__unstableUseAutocompleteProps)(
      {
        completers,
        record: value,
        onChange: onRichTextChange,
        // This control's completers insert their completion into the value;
        // none replace the whole value, so the required `onReplace` is a
        // no-op here.
        onReplace: () => {
        }
      }
    );
    const focusOnMountRef = (0, import_compose16.useRefEffect)(
      (element) => {
        if (focusOnMount && !disabled2) {
          element.focus();
        }
      },
      [focusOnMount, disabled2]
    );
    const editableRef = (0, import_compose16.useMergeRefs)([
      richTextRef,
      anchorRef,
      eventListenersRef,
      enterRef,
      focusOnMountRef,
      autocompleteRef
    ]);
    return (
      // Focus boundary for the field's selection: `onFocus` selects on entry;
      // the spread `useFocusOutside` handlers deselect once focus leaves.
      /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
        "div",
        {
          ...focusOutside,
          onFocus: (event) => {
            setIsSelected(true);
            focusOutside.onFocus(event);
          },
          children: /* @__PURE__ */ (0, import_jsx_runtime188.jsxs)(import_components61.SlotFillProvider, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
              RichTextControlShell,
              {
                label,
                id,
                className: clsx_default(
                  "dataviews-controls__richtext",
                  className
                ),
                placeholder,
                hideLabelFromVision,
                help,
                disabled: disabled2,
                required,
                markWhenOptional,
                customValidity,
                value: value.text,
                "aria-multiline": !disableLineBreaks,
                ...autocompleteProps,
                ref: editableRef
              }
            ),
            isSelected2 && !disabled2 && /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
              KeyboardShortcutContext.Provider,
              {
                value: keyboardShortcuts,
                children: /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(InputEventContext.Provider, { value: inputEvents, children: /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
                  FormatEdit,
                  {
                    value,
                    onChange: onRichTextChange,
                    onFocus,
                    formatTypes,
                    forwardedRef: anchorRef,
                    isVisible: true
                  }
                ) })
              }
            )
          ] })
        }
      )
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/richtext/index.mjs
  var import_jsx_runtime189 = __toESM(require_jsx_runtime(), 1);
  function RichText({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    config: config2,
    validity
  }) {
    const {
      className,
      clientId,
      allowedFormats,
      disableFormats,
      withoutInteractiveFormatting,
      preserveWhiteSpace,
      disableLineBreaks
    } = config2 || {};
    const disabled2 = field.isDisabled({ item: data, field });
    const { label, placeholder, description, id, setValue, isValid: isValid2 } = field;
    const value = field.getValue({ item: data }) ?? "";
    const onChangeControl = (0, import_element109.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
      RichTextControl,
      {
        label,
        value,
        onChange: onChangeControl,
        placeholder,
        id,
        hideLabelFromVision,
        help: description,
        disabled: disabled2,
        required: !!isValid2.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        className,
        clientId,
        allowedFormats,
        disableFormats,
        withoutInteractiveFormatting,
        preserveWhiteSpace,
        disableLineBreaks
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/toggle-group.mjs
  var import_components62 = __toESM(require_components(), 1);
  var import_element110 = __toESM(require_element(), 1);
  var import_jsx_runtime190 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedToggleGroupControl } = unlock4(import_components62.privateApis);
  function ToggleGroup({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { getValue, setValue, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const value = getValue({ item: data });
    const onChangeControl = (0, import_element110.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    const { elements: elements2, isLoading } = useElements({
      elements: field.elements,
      getElements: field.getElements
    });
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime190.jsx)(import_components62.Spinner, {});
    }
    if (elements2.length === 0) {
      return null;
    }
    const selectedOption = elements2.find((el) => el.value === value);
    return /* @__PURE__ */ (0, import_jsx_runtime190.jsx)(
      ValidatedToggleGroupControl,
      {
        required: !!field.isValid?.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        isBlock: true,
        label: field.label,
        help: selectedOption?.description || field.description,
        onChange: onChangeControl,
        value,
        hideLabelFromVision,
        children: elements2.map((el) => /* @__PURE__ */ (0, import_jsx_runtime190.jsx)(
          import_components62.__experimentalToggleGroupControlOption,
          {
            label: el.label,
            value: el.value,
            disabled: disabled2
          },
          el.value
        ))
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/array.mjs
  var import_components63 = __toESM(require_components(), 1);
  var import_element111 = __toESM(require_element(), 1);
  var import_jsx_runtime191 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedFormTokenField } = unlock4(import_components63.privateApis);
  function ArrayControl({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { label, placeholder, description, getValue, setValue, isValid: isValid2 } = field;
    const value = getValue({ item: data });
    const disabled2 = field.isDisabled({ item: data, field });
    const { elements: elements2, isLoading } = useElements({
      elements: field.elements,
      getElements: field.getElements
    });
    const arrayValueAsElements = (0, import_element111.useMemo)(
      () => Array.isArray(value) ? value.map((token) => {
        const element = elements2?.find(
          (suggestion) => suggestion.value === token
        );
        return element || { value: token, label: token };
      }) : [],
      [value, elements2]
    );
    const onChangeControl = (0, import_element111.useCallback)(
      (tokens) => {
        const valueTokens = tokens.map((token) => {
          if (typeof token === "object" && "value" in token) {
            return token.value;
          }
          return token;
        });
        onChange(setValue({ item: data, value: valueTokens }));
      },
      [onChange, setValue, data]
    );
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(import_components63.Spinner, {});
    }
    return /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
      ValidatedFormTokenField,
      {
        required: !!isValid2?.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        label: hideLabelFromVision ? void 0 : label,
        value: arrayValueAsElements,
        onChange: onChangeControl,
        placeholder,
        suggestions: elements2?.map((element) => element.value),
        disabled: disabled2,
        __experimentalValidateInput: (token) => {
          if (field.isValid?.elements && elements2) {
            return elements2.some(
              (element) => element.value === token || element.label === token
            );
          }
          return true;
        },
        __experimentalExpandOnFocus: elements2 && elements2.length > 0,
        help: description ?? (field.isValid?.elements ? "" : void 0),
        displayTransform: (token) => {
          if (typeof token === "object" && "label" in token) {
            return token.label;
          }
          if (typeof token === "string" && elements2) {
            const element = elements2.find(
              (el) => el.value === token
            );
            return element?.label || token;
          }
          return token;
        },
        __experimentalRenderItem: ({ item }) => {
          if (typeof item === "string" && elements2) {
            const element = elements2.find(
              (el) => el.value === item
            );
            return /* @__PURE__ */ (0, import_jsx_runtime191.jsx)("span", { children: element?.label || item });
          }
          return /* @__PURE__ */ (0, import_jsx_runtime191.jsx)("span", { children: item });
        }
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/color.mjs
  var import_components64 = __toESM(require_components(), 1);
  var import_element112 = __toESM(require_element(), 1);
  var import_i18n59 = __toESM(require_i18n(), 1);
  var import_jsx_runtime192 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedInputControl: ValidatedInputControl3 } = unlock4(import_components64.privateApis);
  var ColorPickerDropdown = ({
    color,
    onColorChange,
    disabled: disabled2
  }) => {
    const validColor = color && w(color).isValid() ? color : "#ffffff";
    return /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
      import_components64.Dropdown,
      {
        className: "dataviews-controls__color-picker-dropdown",
        popoverProps: { resize: false },
        renderToggle: ({ onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
          import_components64.Button,
          {
            onClick: onToggle,
            "aria-label": (0, import_i18n59.__)("Open color picker"),
            size: "small",
            disabled: disabled2,
            accessibleWhenDisabled: true,
            icon: () => /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(import_components64.ColorIndicator, { colorValue: validColor })
          }
        ),
        renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(import_components64.__experimentalDropdownContentWrapper, { paddingSize: "none", children: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
          import_components64.ColorPicker,
          {
            color: validColor,
            onChange: onColorChange,
            enableAlpha: true
          }
        ) })
      }
    );
  };
  function Color({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { label, placeholder, description, setValue, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const value = field.getValue({ item: data }) || "";
    const handleColorChange = (0, import_element112.useCallback)(
      (newColor) => {
        onChange(setValue({ item: data, value: newColor }));
      },
      [data, onChange, setValue]
    );
    const handleInputChange = (0, import_element112.useCallback)(
      (newValue) => {
        onChange(setValue({ item: data, value: newValue || "" }));
      },
      [data, onChange, setValue]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
      ValidatedInputControl3,
      {
        required: !!field.isValid?.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        label,
        placeholder,
        value,
        help: description,
        onChange: handleInputChange,
        hideLabelFromVision,
        type: "text",
        disabled: disabled2,
        prefix: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(import_components64.__experimentalInputControlPrefixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
          ColorPickerDropdown,
          {
            color: value,
            onColorChange: handleColorChange,
            disabled: disabled2
          }
        ) })
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/password.mjs
  var import_components65 = __toESM(require_components(), 1);
  var import_element113 = __toESM(require_element(), 1);
  var import_i18n60 = __toESM(require_i18n(), 1);
  var import_jsx_runtime193 = __toESM(require_jsx_runtime(), 1);
  function Password({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const [isVisible2, setIsVisible] = (0, import_element113.useState)(false);
    const disabled2 = field.isDisabled({ item: data, field });
    const toggleVisibility = (0, import_element113.useCallback)(() => {
      setIsVisible((prev) => !prev);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime193.jsx)(
      ValidatedText,
      {
        ...{
          data,
          field,
          onChange,
          hideLabelFromVision,
          markWhenOptional,
          validity,
          type: isVisible2 ? "text" : "password",
          suffix: /* @__PURE__ */ (0, import_jsx_runtime193.jsx)(import_components65.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime193.jsx)(
            import_components65.Button,
            {
              icon: isVisible2 ? unseen_default : seen_default,
              onClick: toggleVisibility,
              size: "small",
              label: isVisible2 ? (0, import_i18n60.__)("Hide password") : (0, import_i18n60.__)("Show password"),
              disabled: disabled2,
              accessibleWhenDisabled: true
            }
          ) })
        }
      }
    );
  }

  // packages/dataviews/build-module/field-types/utils/has-elements.mjs
  function hasElements(field) {
    return Array.isArray(field.elements) && field.elements.length > 0 || typeof field.getElements === "function";
  }

  // packages/dataviews/build-module/components/dataform-controls/index.mjs
  var import_jsx_runtime194 = __toESM(require_jsx_runtime(), 1);
  var FORM_CONTROLS = {
    adaptiveSelect: AdaptiveSelect,
    array: ArrayControl,
    checkbox: Checkbox,
    color: Color,
    combobox: Combobox3,
    datetime: DateTime,
    date: DateControl,
    email: Email,
    telephone: Telephone,
    url: Url,
    integer: Integer,
    number: Number2,
    password: Password,
    radio: Radio,
    select: Select,
    text: Text3,
    toggle: Toggle,
    textarea: Textarea,
    richtext: RichText,
    toggleGroup: ToggleGroup
  };
  function isEditConfig(value) {
    return value && typeof value === "object" && typeof value.control === "string";
  }
  function createConfiguredControl(config2) {
    const { control, ...controlConfig } = config2;
    const BaseControlType = getControlByType(control);
    if (BaseControlType === null) {
      return null;
    }
    return function ConfiguredControl(props) {
      return /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(BaseControlType, { ...props, config: controlConfig });
    };
  }
  function getControl(field, fallback) {
    if (typeof field.Edit === "function") {
      return field.Edit;
    }
    if (typeof field.Edit === "string") {
      return getControlByType(field.Edit);
    }
    if (isEditConfig(field.Edit)) {
      return createConfiguredControl(field.Edit);
    }
    if (hasElements(field) && field.type !== "array") {
      return getControlByType("adaptiveSelect");
    }
    if (fallback === null) {
      return null;
    }
    return getControlByType(fallback);
  }
  function getControlByType(type) {
    if (Object.keys(FORM_CONTROLS).includes(type)) {
      return FORM_CONTROLS[type];
    }
    return null;
  }

  // packages/dataviews/build-module/field-types/utils/get-filter-by.mjs
  function getFilterBy(field, defaultOperators, validOperators) {
    if (field.filterBy === false) {
      return false;
    }
    const operators = field.filterBy?.operators?.filter(
      (op) => validOperators.includes(op)
    ) ?? defaultOperators;
    if (operators.length === 0) {
      return false;
    }
    return {
      isPrimary: !!field.filterBy?.isPrimary,
      operators
    };
  }
  var get_filter_by_default = getFilterBy;

  // packages/dataviews/build-module/field-types/utils/get-value-from-id.mjs
  var getValueFromId = (id) => ({ item }) => {
    const path = id.split(".");
    let value = item;
    for (const segment of path) {
      if (value.hasOwnProperty(segment)) {
        value = value[segment];
      } else {
        value = void 0;
      }
    }
    return value;
  };
  var get_value_from_id_default = getValueFromId;

  // packages/dataviews/build-module/field-types/utils/set-value-from-id.mjs
  var setValueFromId = (id) => ({ value }) => {
    const path = id.split(".");
    const result = {};
    let current = result;
    for (const segment of path.slice(0, -1)) {
      current[segment] = {};
      current = current[segment];
    }
    current[path.at(-1)] = value;
    return result;
  };
  var set_value_from_id_default = setValueFromId;

  // packages/dataviews/build-module/field-types/email.mjs
  var import_i18n61 = __toESM(require_i18n(), 1);

  // packages/dataviews/build-module/field-types/utils/render-from-elements.mjs
  function RenderFromElements({
    item,
    field
  }) {
    const { elements: elements2, isLoading } = useElements({
      elements: field.elements,
      getElements: field.getElements
    });
    const value = field.getValue({ item });
    if (isLoading) {
      return value;
    }
    if (elements2.length === 0) {
      return value;
    }
    return elements2?.find((element) => element.value === value)?.label || field.getValue({ item });
  }

  // packages/dataviews/build-module/field-types/utils/render-default.mjs
  var import_jsx_runtime195 = __toESM(require_jsx_runtime(), 1);
  function render({
    item,
    field
  }) {
    if (field.hasElements) {
      return /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(RenderFromElements, { item, field });
    }
    return field.getValueFormatted({ item, field });
  }

  // packages/dataviews/build-module/field-types/utils/sort-text.mjs
  var sort_text_default = (a2, b2, direction) => {
    return direction === "asc" ? a2.localeCompare(b2) : b2.localeCompare(a2);
  };

  // packages/dataviews/build-module/field-types/utils/is-valid-required.mjs
  function isValidRequired(item, field) {
    const value = field.getValue({ item });
    return ![void 0, "", null].includes(value);
  }

  // packages/dataviews/build-module/field-types/utils/is-valid-min-length.mjs
  function isValidMinLength(item, field) {
    if (typeof field.isValid.minLength?.constraint !== "number") {
      return false;
    }
    const value = field.getValue({ item });
    if ([void 0, "", null].includes(value)) {
      return true;
    }
    return String(value).length >= field.isValid.minLength.constraint;
  }

  // packages/dataviews/build-module/field-types/utils/is-valid-max-length.mjs
  function isValidMaxLength(item, field) {
    if (typeof field.isValid.maxLength?.constraint !== "number") {
      return false;
    }
    const value = field.getValue({ item });
    if ([void 0, "", null].includes(value)) {
      return true;
    }
    return String(value).length <= field.isValid.maxLength.constraint;
  }

  // packages/dataviews/build-module/field-types/utils/is-valid-pattern.mjs
  function isValidPattern(item, field) {
    if (field.isValid.pattern?.constraint === void 0) {
      return true;
    }
    try {
      const regexp = new RegExp(field.isValid.pattern.constraint);
      const value = field.getValue({ item });
      if ([void 0, "", null].includes(value)) {
        return true;
      }
      return regexp.test(String(value));
    } catch {
      return false;
    }
  }

  // packages/dataviews/build-module/field-types/utils/is-valid-elements.mjs
  function isValidElements(item, field) {
    const elements2 = field.elements ?? [];
    const validValues = elements2.map((el) => el.value);
    if (validValues.length === 0) {
      return true;
    }
    const value = field.getValue({ item });
    return [].concat(value).every((v2) => validValues.includes(v2));
  }

  // packages/dataviews/build-module/field-types/utils/get-value-formatted-default.mjs
  function getValueFormatted({
    item,
    field
  }) {
    return field.getValue({ item });
  }
  var get_value_formatted_default_default = getValueFormatted;

  // packages/dataviews/build-module/field-types/email.mjs
  var emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
  function isValidCustom(item, field) {
    const value = field.getValue({ item });
    if (![void 0, "", null].includes(value) && !emailRegex.test(value)) {
      return (0, import_i18n61.__)("Value must be a valid email address.");
    }
    return null;
  }
  var email_default = {
    type: "email",
    render,
    Edit: "email",
    sort: sort_text_default,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE2],
    validOperators: [
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_CONTAINS,
      OPERATOR_NOT_CONTAINS,
      OPERATOR_STARTS_WITH,
      // Multiple selection
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE2,
      OPERATOR_IS_ALL,
      OPERATOR_IS_NOT_ALL
    ],
    format: {},
    getValueFormatted: get_value_formatted_default_default,
    validate: {
      required: isValidRequired,
      pattern: isValidPattern,
      minLength: isValidMinLength,
      maxLength: isValidMaxLength,
      elements: isValidElements,
      custom: isValidCustom
    }
  };

  // packages/dataviews/build-module/field-types/integer.mjs
  var import_i18n62 = __toESM(require_i18n(), 1);

  // packages/dataviews/build-module/field-types/utils/sort-number.mjs
  var sort_number_default = (a2, b2, direction) => {
    return direction === "asc" ? a2 - b2 : b2 - a2;
  };

  // packages/dataviews/build-module/field-types/utils/is-valid-min.mjs
  function isValidMin(item, field) {
    if (typeof field.isValid.min?.constraint !== "number") {
      return false;
    }
    const value = field.getValue({ item });
    if ([void 0, "", null].includes(value)) {
      return true;
    }
    return Number(value) >= field.isValid.min.constraint;
  }

  // packages/dataviews/build-module/field-types/utils/is-valid-max.mjs
  function isValidMax(item, field) {
    if (typeof field.isValid.max?.constraint !== "number") {
      return false;
    }
    const value = field.getValue({ item });
    if ([void 0, "", null].includes(value)) {
      return true;
    }
    return Number(value) <= field.isValid.max.constraint;
  }

  // packages/dataviews/build-module/field-types/integer.mjs
  var format2 = {
    separatorThousand: ","
  };
  function getValueFormatted2({
    item,
    field
  }) {
    let value = field.getValue({ item });
    if (value === null || value === void 0) {
      return "";
    }
    value = Number(value);
    if (!Number.isFinite(value)) {
      return String(value);
    }
    let formatInteger;
    if (field.type !== "integer") {
      formatInteger = format2;
    } else {
      formatInteger = field.format;
    }
    const { separatorThousand } = formatInteger;
    const integerValue = Math.trunc(value);
    if (!separatorThousand) {
      return String(integerValue);
    }
    return String(integerValue).replace(
      /\B(?=(\d{3})+(?!\d))/g,
      separatorThousand
    );
  }
  function isValidCustom2(item, field) {
    const value = field.getValue({ item });
    if (![void 0, "", null].includes(value) && !Number.isInteger(value)) {
      return (0, import_i18n62.__)("Value must be an integer.");
    }
    return null;
  }
  var integer_default = {
    type: "integer",
    render,
    Edit: "integer",
    sort: sort_number_default,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_LESS_THAN,
      OPERATOR_GREATER_THAN,
      OPERATOR_LESS_THAN_OR_EQUAL,
      OPERATOR_GREATER_THAN_OR_EQUAL,
      OPERATOR_BETWEEN
    ],
    validOperators: [
      // Single-selection
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_LESS_THAN,
      OPERATOR_GREATER_THAN,
      OPERATOR_LESS_THAN_OR_EQUAL,
      OPERATOR_GREATER_THAN_OR_EQUAL,
      OPERATOR_BETWEEN,
      // Multiple-selection
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE2,
      OPERATOR_IS_ALL,
      OPERATOR_IS_NOT_ALL
    ],
    format: format2,
    getValueFormatted: getValueFormatted2,
    validate: {
      required: isValidRequired,
      min: isValidMin,
      max: isValidMax,
      elements: isValidElements,
      custom: isValidCustom2
    }
  };

  // packages/dataviews/build-module/field-types/number.mjs
  var import_i18n63 = __toESM(require_i18n(), 1);
  var format3 = {
    separatorThousand: ",",
    separatorDecimal: ".",
    decimals: 2
  };
  function getValueFormatted3({
    item,
    field
  }) {
    let value = field.getValue({ item });
    if (value === null || value === void 0) {
      return "";
    }
    value = Number(value);
    if (!Number.isFinite(value)) {
      return String(value);
    }
    let formatNumber;
    if (field.type !== "number") {
      formatNumber = format3;
    } else {
      formatNumber = field.format;
    }
    const { separatorThousand, separatorDecimal, decimals } = formatNumber;
    const fixedValue = value.toFixed(decimals);
    const [integerPart, decimalPart] = fixedValue.split(".");
    const formattedInteger = separatorThousand ? integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, separatorThousand) : integerPart;
    return decimals === 0 ? formattedInteger : formattedInteger + separatorDecimal + decimalPart;
  }
  function isEmpty(value) {
    return value === "" || value === void 0 || value === null;
  }
  function isValidCustom3(item, field) {
    const value = field.getValue({ item });
    if (!isEmpty(value) && !Number.isFinite(value)) {
      return (0, import_i18n63.__)("Value must be a number.");
    }
    return null;
  }
  var number_default = {
    type: "number",
    render,
    Edit: "number",
    sort: sort_number_default,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_LESS_THAN,
      OPERATOR_GREATER_THAN,
      OPERATOR_LESS_THAN_OR_EQUAL,
      OPERATOR_GREATER_THAN_OR_EQUAL,
      OPERATOR_BETWEEN
    ],
    validOperators: [
      // Single-selection
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_LESS_THAN,
      OPERATOR_GREATER_THAN,
      OPERATOR_LESS_THAN_OR_EQUAL,
      OPERATOR_GREATER_THAN_OR_EQUAL,
      OPERATOR_BETWEEN,
      // Multiple-selection
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE2,
      OPERATOR_IS_ALL,
      OPERATOR_IS_NOT_ALL
    ],
    format: format3,
    getValueFormatted: getValueFormatted3,
    validate: {
      required: isValidRequired,
      min: isValidMin,
      max: isValidMax,
      elements: isValidElements,
      custom: isValidCustom3
    }
  };

  // packages/dataviews/build-module/field-types/text.mjs
  var text_default = {
    type: "text",
    render,
    Edit: "text",
    sort: sort_text_default,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE2],
    validOperators: [
      // Single selection
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_CONTAINS,
      OPERATOR_NOT_CONTAINS,
      OPERATOR_STARTS_WITH,
      // Multiple selection
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE2,
      OPERATOR_IS_ALL,
      OPERATOR_IS_NOT_ALL
    ],
    format: {},
    getValueFormatted: get_value_formatted_default_default,
    validate: {
      required: isValidRequired,
      pattern: isValidPattern,
      minLength: isValidMinLength,
      maxLength: isValidMaxLength,
      elements: isValidElements
    }
  };

  // packages/dataviews/build-module/field-types/datetime.mjs
  var import_date7 = __toESM(require_date(), 1);

  // packages/dataviews/build-module/field-types/utils/is-valid-date-boundary.mjs
  var import_date6 = __toESM(require_date(), 1);
  function parseDateLike(value) {
    if (!value) {
      return null;
    }
    if (!isValid(new Date(value))) {
      return null;
    }
    const parsed = (0, import_date6.getDate)(value);
    return parsed && isValid(parsed) ? parsed : null;
  }
  function validateDateLikeBoundary(item, field, boundary) {
    const constraint = field.isValid[boundary]?.constraint;
    if (typeof constraint !== "string") {
      return false;
    }
    const value = field.getValue({ item });
    const boundaryValue = Array.isArray(value) ? value[boundary === "min" ? 0 : value.length - 1] : value;
    if (boundaryValue === void 0 || boundaryValue === null || boundaryValue === "") {
      return true;
    }
    const parsedConstraint = parseDateLike(constraint);
    const parsedValue = parseDateLike(String(boundaryValue));
    return !!parsedConstraint && !!parsedValue && (boundary === "min" ? parsedValue.getTime() >= parsedConstraint.getTime() : parsedValue.getTime() <= parsedConstraint.getTime());
  }
  function isValidMinDate(item, field) {
    return validateDateLikeBoundary(item, field, "min");
  }
  function isValidMaxDate(item, field) {
    return validateDateLikeBoundary(item, field, "max");
  }

  // packages/dataviews/build-module/field-types/datetime.mjs
  var format4 = {
    datetime: (0, import_date7.getSettings)().formats.datetime,
    weekStartsOn: (0, import_date7.getSettings)().l10n.startOfWeek
  };
  function getValueFormatted4({
    item,
    field
  }) {
    const value = field.getValue({ item });
    if (["", void 0, null].includes(value)) {
      return "";
    }
    let formatDatetime;
    if (field.type !== "datetime") {
      formatDatetime = format4;
    } else {
      formatDatetime = field.format;
    }
    return (0, import_date7.dateI18n)(formatDatetime.datetime, (0, import_date7.getDate)(value));
  }
  var sort = (a2, b2, direction) => {
    const timeA = new Date(a2).getTime();
    const timeB = new Date(b2).getTime();
    return direction === "asc" ? timeA - timeB : timeB - timeA;
  };
  var datetime_default = {
    type: "datetime",
    render,
    Edit: "datetime",
    sort,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [
      OPERATOR_ON,
      OPERATOR_NOT_ON,
      OPERATOR_BEFORE2,
      OPERATOR_AFTER2,
      OPERATOR_BEFORE_INC,
      OPERATOR_AFTER_INC,
      OPERATOR_IN_THE_PAST,
      OPERATOR_OVER
    ],
    validOperators: [
      OPERATOR_ON,
      OPERATOR_NOT_ON,
      OPERATOR_BEFORE2,
      OPERATOR_AFTER2,
      OPERATOR_BEFORE_INC,
      OPERATOR_AFTER_INC,
      OPERATOR_IN_THE_PAST,
      OPERATOR_OVER
    ],
    format: format4,
    getValueFormatted: getValueFormatted4,
    validate: {
      required: isValidRequired,
      elements: isValidElements,
      min: isValidMinDate,
      max: isValidMaxDate
    }
  };

  // packages/dataviews/build-module/field-types/date.mjs
  var import_date8 = __toESM(require_date(), 1);
  var format5 = {
    date: (0, import_date8.getSettings)().formats.date,
    weekStartsOn: (0, import_date8.getSettings)().l10n.startOfWeek
  };
  function getValueFormatted5({
    item,
    field
  }) {
    const value = field.getValue({ item });
    if (["", void 0, null].includes(value)) {
      return "";
    }
    let formatDate2;
    if (field.type !== "date") {
      formatDate2 = format5;
    } else {
      formatDate2 = field.format;
    }
    return (0, import_date8.dateI18n)(formatDate2.date, (0, import_date8.getDate)(value));
  }
  var sort2 = (a2, b2, direction) => {
    const timeA = new Date(a2).getTime();
    const timeB = new Date(b2).getTime();
    return direction === "asc" ? timeA - timeB : timeB - timeA;
  };
  var date_default = {
    type: "date",
    render,
    Edit: "date",
    sort: sort2,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [
      OPERATOR_ON,
      OPERATOR_NOT_ON,
      OPERATOR_BEFORE2,
      OPERATOR_AFTER2,
      OPERATOR_BEFORE_INC,
      OPERATOR_AFTER_INC,
      OPERATOR_IN_THE_PAST,
      OPERATOR_OVER,
      OPERATOR_BETWEEN
    ],
    validOperators: [
      OPERATOR_ON,
      OPERATOR_NOT_ON,
      OPERATOR_BEFORE2,
      OPERATOR_AFTER2,
      OPERATOR_BEFORE_INC,
      OPERATOR_AFTER_INC,
      OPERATOR_IN_THE_PAST,
      OPERATOR_OVER,
      OPERATOR_BETWEEN
    ],
    format: format5,
    getValueFormatted: getValueFormatted5,
    validate: {
      required: isValidRequired,
      elements: isValidElements,
      min: isValidMinDate,
      max: isValidMaxDate
    }
  };

  // packages/dataviews/build-module/field-types/boolean.mjs
  var import_i18n64 = __toESM(require_i18n(), 1);

  // packages/dataviews/build-module/field-types/utils/is-valid-required-for-bool.mjs
  function isValidRequiredForBool(item, field) {
    const value = field.getValue({ item });
    return value === true;
  }

  // packages/dataviews/build-module/field-types/boolean.mjs
  function getValueFormatted6({
    item,
    field
  }) {
    const value = field.getValue({ item });
    if (value === true) {
      return (0, import_i18n64.__)("True");
    }
    if (value === false) {
      return (0, import_i18n64.__)("False");
    }
    return "";
  }
  function isValidCustom4(item, field) {
    const value = field.getValue({ item });
    if (![void 0, "", null].includes(value) && ![true, false].includes(value)) {
      return (0, import_i18n64.__)("Value must be true, false, or undefined");
    }
    return null;
  }
  var sort3 = (a2, b2, direction) => {
    const boolA = Boolean(a2);
    const boolB = Boolean(b2);
    if (boolA === boolB) {
      return 0;
    }
    if (direction === "asc") {
      return boolA ? 1 : -1;
    }
    return boolA ? -1 : 1;
  };
  var boolean_default = {
    type: "boolean",
    render,
    Edit: "checkbox",
    sort: sort3,
    validate: {
      required: isValidRequiredForBool,
      elements: isValidElements,
      custom: isValidCustom4
    },
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS, OPERATOR_IS_NOT],
    validOperators: [OPERATOR_IS, OPERATOR_IS_NOT],
    format: {},
    getValueFormatted: getValueFormatted6
  };

  // packages/dataviews/build-module/field-types/media.mjs
  var media_default2 = {
    type: "media",
    render: () => null,
    Edit: null,
    sort: () => 0,
    enableSorting: false,
    enableGlobalSearch: false,
    defaultOperators: [],
    validOperators: [],
    format: {},
    getValueFormatted: get_value_formatted_default_default,
    // cannot validate any constraint, so
    // the only available validation for the field author
    // would be providing a custom validator.
    validate: {}
  };

  // packages/dataviews/build-module/field-types/array.mjs
  var import_i18n65 = __toESM(require_i18n(), 1);

  // packages/dataviews/build-module/field-types/utils/is-valid-required-for-array.mjs
  function isValidRequiredForArray(item, field) {
    const value = field.getValue({ item });
    return Array.isArray(value) && value.length > 0 && value.every(
      (element) => ![void 0, "", null].includes(element)
    );
  }

  // packages/dataviews/build-module/field-types/array.mjs
  function getValueFormatted7({
    item,
    field
  }) {
    const value = field.getValue({ item });
    const arr = Array.isArray(value) ? value : [];
    return arr.join(", ");
  }
  function render2({ item, field }) {
    return getValueFormatted7({ item, field });
  }
  function isValidCustom5(item, field) {
    const value = field.getValue({ item });
    if (![void 0, "", null].includes(value) && !Array.isArray(value)) {
      return (0, import_i18n65.__)("Value must be an array.");
    }
    if (!value.every((v2) => typeof v2 === "string")) {
      return (0, import_i18n65.__)("Every value must be a string.");
    }
    return null;
  }
  var sort4 = (a2, b2, direction) => {
    const arrA = Array.isArray(a2) ? a2 : [];
    const arrB = Array.isArray(b2) ? b2 : [];
    if (arrA.length !== arrB.length) {
      return direction === "asc" ? arrA.length - arrB.length : arrB.length - arrA.length;
    }
    const joinedA = arrA.join(",");
    const joinedB = arrB.join(",");
    return direction === "asc" ? joinedA.localeCompare(joinedB) : joinedB.localeCompare(joinedA);
  };
  var array_default = {
    type: "array",
    render: render2,
    Edit: "array",
    sort: sort4,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE2],
    validOperators: [
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE2,
      OPERATOR_IS_ALL,
      OPERATOR_IS_NOT_ALL
    ],
    format: {},
    getValueFormatted: getValueFormatted7,
    validate: {
      required: isValidRequiredForArray,
      elements: isValidElements,
      custom: isValidCustom5
    }
  };

  // packages/dataviews/build-module/field-types/password.mjs
  function getValueFormatted8({
    item,
    field
  }) {
    return field.getValue({ item }) ? "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" : "";
  }
  var password_default = {
    type: "password",
    render,
    Edit: "password",
    sort: () => 0,
    // Passwords should not be sortable for security reasons
    enableSorting: false,
    enableGlobalSearch: false,
    defaultOperators: [],
    validOperators: [],
    format: {},
    getValueFormatted: getValueFormatted8,
    validate: {
      required: isValidRequired,
      pattern: isValidPattern,
      minLength: isValidMinLength,
      maxLength: isValidMaxLength,
      elements: isValidElements
    }
  };

  // packages/dataviews/build-module/field-types/telephone.mjs
  var telephone_default = {
    type: "telephone",
    render,
    Edit: "telephone",
    sort: sort_text_default,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE2],
    validOperators: [
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_CONTAINS,
      OPERATOR_NOT_CONTAINS,
      OPERATOR_STARTS_WITH,
      // Multiple selection
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE2,
      OPERATOR_IS_ALL,
      OPERATOR_IS_NOT_ALL
    ],
    format: {},
    getValueFormatted: get_value_formatted_default_default,
    validate: {
      required: isValidRequired,
      pattern: isValidPattern,
      minLength: isValidMinLength,
      maxLength: isValidMaxLength,
      elements: isValidElements
    }
  };

  // packages/dataviews/build-module/field-types/color.mjs
  var import_i18n66 = __toESM(require_i18n(), 1);
  var import_jsx_runtime196 = __toESM(require_jsx_runtime(), 1);
  function render3({ item, field }) {
    if (field.hasElements) {
      return /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(RenderFromElements, { item, field });
    }
    const value = get_value_formatted_default_default({ item, field });
    if (!value || !w(value).isValid()) {
      return value;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime196.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: "8px" }, children: [
      /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
        "div",
        {
          style: {
            width: "16px",
            height: "16px",
            borderRadius: "50%",
            backgroundColor: value,
            border: "1px solid #ddd",
            flexShrink: 0
          }
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime196.jsx)("span", { children: value })
    ] });
  }
  function isValidCustom6(item, field) {
    const value = field.getValue({ item });
    if (![void 0, "", null].includes(value) && !w(value).isValid()) {
      return (0, import_i18n66.__)("Value must be a valid color.");
    }
    return null;
  }
  var sort5 = (a2, b2, direction) => {
    const colorA = w(a2);
    const colorB = w(b2);
    if (!colorA.isValid() && !colorB.isValid()) {
      return 0;
    }
    if (!colorA.isValid()) {
      return direction === "asc" ? 1 : -1;
    }
    if (!colorB.isValid()) {
      return direction === "asc" ? -1 : 1;
    }
    const hslA = colorA.toHsl();
    const hslB = colorB.toHsl();
    if (hslA.h !== hslB.h) {
      return direction === "asc" ? hslA.h - hslB.h : hslB.h - hslA.h;
    }
    if (hslA.s !== hslB.s) {
      return direction === "asc" ? hslA.s - hslB.s : hslB.s - hslA.s;
    }
    return direction === "asc" ? hslA.l - hslB.l : hslB.l - hslA.l;
  };
  var color_default = {
    type: "color",
    render: render3,
    Edit: "color",
    sort: sort5,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE2],
    validOperators: [
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE2
    ],
    format: {},
    getValueFormatted: get_value_formatted_default_default,
    validate: {
      required: isValidRequired,
      elements: isValidElements,
      custom: isValidCustom6
    }
  };

  // packages/dataviews/build-module/field-types/url.mjs
  var url_default = {
    type: "url",
    render,
    Edit: "url",
    sort: sort_text_default,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE2],
    validOperators: [
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_CONTAINS,
      OPERATOR_NOT_CONTAINS,
      OPERATOR_STARTS_WITH,
      // Multiple selection
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE2,
      OPERATOR_IS_ALL,
      OPERATOR_IS_NOT_ALL
    ],
    format: {},
    getValueFormatted: get_value_formatted_default_default,
    validate: {
      required: isValidRequired,
      pattern: isValidPattern,
      minLength: isValidMinLength,
      maxLength: isValidMaxLength,
      elements: isValidElements
    }
  };

  // packages/dataviews/build-module/field-types/no-type.mjs
  var sort6 = (a2, b2, direction) => {
    if (typeof a2 === "number" && typeof b2 === "number") {
      return sort_number_default(a2, b2, direction);
    }
    return sort_text_default(a2, b2, direction);
  };
  var no_type_default = {
    // type: no type for this one
    render,
    Edit: null,
    sort: sort6,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS, OPERATOR_IS_NOT],
    validOperators: getAllOperatorNames(),
    format: {},
    getValueFormatted: get_value_formatted_default_default,
    validate: {
      required: isValidRequired,
      elements: isValidElements
    }
  };

  // packages/dataviews/build-module/field-types/utils/get-is-valid.mjs
  function supportsNumericRangeConstraint(type) {
    return type === "integer" || type === "number";
  }
  function supportsDateRangeConstraint(type) {
    return type === "date" || type === "datetime";
  }
  function normalizeRangeRule(value, fieldType, key) {
    const validator = fieldType.validate[key];
    if (validator && (typeof value === "number" && supportsNumericRangeConstraint(fieldType.type) || typeof value === "string" && supportsDateRangeConstraint(fieldType.type))) {
      return { constraint: value, validate: validator };
    }
    return void 0;
  }
  function getIsValid(field, fieldType) {
    const rules = field.isValid;
    let required;
    if (rules?.required === true && fieldType.validate.required !== void 0) {
      required = {
        constraint: true,
        validate: fieldType.validate.required
      };
    }
    let elements2;
    if ((rules?.elements === true || // elements is enabled unless the field opts-out
    rules?.elements === void 0 && (!!field.elements || !!field.getElements)) && fieldType.validate.elements !== void 0) {
      elements2 = {
        constraint: true,
        validate: fieldType.validate.elements
      };
    }
    const min2 = normalizeRangeRule(rules?.min, fieldType, "min");
    const max2 = normalizeRangeRule(rules?.max, fieldType, "max");
    const minLengthValue = rules?.minLength;
    let minLength;
    if (typeof minLengthValue === "number" && fieldType.validate.minLength !== void 0) {
      minLength = {
        constraint: minLengthValue,
        validate: fieldType.validate.minLength
      };
    }
    const maxLengthValue = rules?.maxLength;
    let maxLength;
    if (typeof maxLengthValue === "number" && fieldType.validate.maxLength !== void 0) {
      maxLength = {
        constraint: maxLengthValue,
        validate: fieldType.validate.maxLength
      };
    }
    const patternValue = rules?.pattern;
    let pattern;
    if (patternValue !== void 0 && fieldType.validate.pattern !== void 0) {
      pattern = {
        constraint: patternValue,
        validate: fieldType.validate.pattern
      };
    }
    const custom = rules?.custom ?? fieldType.validate.custom;
    return {
      required,
      elements: elements2,
      min: min2,
      max: max2,
      minLength,
      maxLength,
      pattern,
      custom
    };
  }

  // packages/dataviews/build-module/field-types/utils/get-filter.mjs
  function getFilter(fieldType) {
    return fieldType.validOperators.reduce((accumulator, operator) => {
      const operatorObj = getOperatorByName(operator);
      if (operatorObj?.filter) {
        accumulator[operator] = operatorObj.filter;
      }
      return accumulator;
    }, {});
  }

  // packages/dataviews/build-module/field-types/utils/get-format.mjs
  function getFormat(field, fieldType) {
    return {
      ...fieldType.format,
      ...field.format
    };
  }
  var get_format_default = getFormat;

  // packages/dataviews/build-module/field-types/index.mjs
  function getFieldTypeByName(type) {
    const found = [
      email_default,
      integer_default,
      number_default,
      text_default,
      datetime_default,
      date_default,
      boolean_default,
      media_default2,
      array_default,
      password_default,
      telephone_default,
      color_default,
      url_default
    ].find((fieldType) => fieldType?.type === type);
    if (!!found) {
      return found;
    }
    return no_type_default;
  }
  function normalizeFields(fields2) {
    return fields2.map((field) => {
      const fieldType = getFieldTypeByName(field.type);
      const getValue = field.getValue || get_value_from_id_default(field.id);
      const sort7 = function(a2, b2, direction) {
        const aValue = getValue({ item: a2 });
        const bValue = getValue({ item: b2 });
        return field.sort ? field.sort(aValue, bValue, direction) : fieldType.sort(aValue, bValue, direction);
      };
      return {
        id: field.id,
        label: field.label || field.id,
        header: field.header || field.label || field.id,
        description: field.description,
        placeholder: field.placeholder,
        getValue,
        setValue: field.setValue || set_value_from_id_default(field.id),
        elements: field.elements,
        getElements: field.getElements,
        hasElements: hasElements(field),
        isVisible: field.isVisible,
        isDisabled: typeof field.isDisabled === "function" ? field.isDisabled : () => !!field.isDisabled,
        enableHiding: field.enableHiding ?? true,
        readOnly: field.readOnly ?? false,
        // The type provides defaults for the following props
        type: fieldType.type,
        render: field.render ?? fieldType.render,
        Edit: getControl(field, fieldType.Edit),
        sort: sort7,
        enableSorting: field.enableSorting ?? fieldType.enableSorting,
        enableGlobalSearch: field.enableGlobalSearch ?? fieldType.enableGlobalSearch,
        isValid: getIsValid(field, fieldType),
        filterBy: get_filter_by_default(
          field,
          fieldType.defaultOperators,
          fieldType.validOperators
        ),
        filter: getFilter(fieldType),
        format: get_format_default(field, fieldType),
        getValueFormatted: field.getValueFormatted ?? fieldType.getValueFormatted
      };
    });
  }

  // packages/dataviews/build-module/hooks/use-data.mjs
  var import_element114 = __toESM(require_element(), 1);
  function useData({
    view,
    data: shownData,
    getItemId: getItemId2,
    isLoading,
    paginationInfo,
    selection
  }) {
    const isInfiniteScrollEnabled = view.infiniteScrollEnabled;
    const [hasInitiallyLoaded, setHasInitiallyLoaded] = (0, import_element114.useState)(
      !isLoading
    );
    (0, import_element114.useEffect)(() => {
      if (!isLoading) {
        setHasInitiallyLoaded(true);
      }
    }, [isLoading]);
    const previousDataRef = (0, import_element114.useRef)(shownData);
    const previousPaginationInfoRef = (0, import_element114.useRef)(paginationInfo);
    (0, import_element114.useEffect)(() => {
      if (!isLoading) {
        previousDataRef.current = shownData;
        previousPaginationInfoRef.current = paginationInfo;
      }
    }, [shownData, isLoading, paginationInfo]);
    const [visibleEntries, setVisibleEntries] = (0, import_element114.useState)([]);
    const positionMapRef = (0, import_element114.useRef)(/* @__PURE__ */ new Map());
    const allLoadedRecordsRef = (0, import_element114.useRef)([]);
    const prevViewParamsRef = (0, import_element114.useRef)({
      search: void 0,
      filters: void 0,
      perPage: void 0
    });
    const scrollDirectionRef = (0, import_element114.useRef)(void 0);
    const prevStartPositionRef = (0, import_element114.useRef)(void 0);
    const hasInitializedRef = (0, import_element114.useRef)(false);
    const allLoadedRecords = (0, import_element114.useMemo)(() => {
      if (view.startPosition !== void 0 && prevStartPositionRef.current !== void 0) {
        if (view.startPosition < prevStartPositionRef.current) {
          scrollDirectionRef.current = "up";
        } else if (view.startPosition > prevStartPositionRef.current) {
          scrollDirectionRef.current = "down";
        }
      }
      prevStartPositionRef.current = view.startPosition;
      const currentFiltersKey = JSON.stringify(view.filters ?? []);
      const prevFiltersKey = prevViewParamsRef.current.filters;
      const shouldReset = !hasInitializedRef.current || !view.infiniteScrollEnabled || view.search !== prevViewParamsRef.current.search || currentFiltersKey !== prevFiltersKey || view.perPage !== prevViewParamsRef.current.perPage;
      hasInitializedRef.current = true;
      prevViewParamsRef.current = {
        search: view.search,
        filters: currentFiltersKey,
        perPage: view.perPage
      };
      if (shouldReset) {
        positionMapRef.current.clear();
        scrollDirectionRef.current = void 0;
        const startPosition = view.search ? 1 : view.startPosition ?? 1;
        const records = shownData.map((record, index2) => {
          const position = startPosition + index2;
          positionMapRef.current.set(getItemId2(record), position);
          return {
            ...record,
            position
          };
        });
        allLoadedRecordsRef.current = records;
        return records;
      }
      const prev = allLoadedRecordsRef.current;
      const shownDataIds = new Set(shownData.map(getItemId2));
      const scrollDirection = scrollDirectionRef.current;
      const basePosition = view.search ? 1 : view.startPosition ?? 1;
      const newRecords = shownData.map((record, index2) => {
        const itemId = getItemId2(record);
        const position = view.infiniteScrollEnabled ? basePosition + index2 : void 0;
        if (position !== void 0) {
          positionMapRef.current.set(itemId, position);
        }
        return {
          ...record,
          position
        };
      });
      if (newRecords.length === 0) {
        return prev;
      }
      const prevWithoutDuplicates = prev.filter(
        (record) => !shownDataIds.has(getItemId2(record))
      );
      const allRecords = scrollDirection === "up" ? [...newRecords, ...prevWithoutDuplicates] : [...prevWithoutDuplicates, ...newRecords];
      allRecords.sort((a2, b2) => {
        const posA = a2.position;
        const posB = b2.position;
        return posA - posB;
      });
      let result = allRecords;
      if (visibleEntries.length > 0) {
        const visibleMin = Math.min(...visibleEntries);
        const visibleMax = Math.max(...visibleEntries);
        const buffer = 20;
        const recordPositions = allRecords.map(
          (r3) => r3.position
        );
        const minRecordPos = Math.min(...recordPositions);
        const maxRecordPos = Math.max(...recordPositions);
        const hasOverlap = !(maxRecordPos < visibleMin - buffer || minRecordPos > visibleMax + buffer);
        if (hasOverlap) {
          result = allRecords.filter((record) => {
            const itemId = getItemId2(record);
            const isSelected2 = selection?.includes(itemId);
            if (isSelected2) {
              return true;
            }
            const itemPosition = record.position;
            if (scrollDirection === "up") {
              return itemPosition <= visibleMax + buffer;
            } else if (scrollDirection === "down") {
              return itemPosition >= visibleMin - buffer;
            }
            return itemPosition >= visibleMin - buffer && itemPosition <= visibleMax + buffer;
          });
        }
      }
      allLoadedRecordsRef.current = result;
      return result;
    }, [
      shownData,
      view.search,
      view.filters,
      view.perPage,
      view.startPosition,
      view.infiniteScrollEnabled,
      visibleEntries,
      selection,
      getItemId2
    ]);
    if (!isInfiniteScrollEnabled) {
      const dataToReturn = isLoading && previousDataRef.current?.length ? previousDataRef.current : shownData;
      return {
        data: dataToReturn.map((item) => ({
          ...item,
          position: void 0
        })),
        paginationInfo: isLoading && previousDataRef.current?.length ? previousPaginationInfoRef.current : paginationInfo,
        hasInitiallyLoaded,
        setVisibleEntries: void 0
      };
    }
    return {
      data: allLoadedRecords,
      paginationInfo,
      hasInitiallyLoaded,
      setVisibleEntries
    };
  }

  // packages/dataviews/build-module/hooks/use-infinite-scroll.mjs
  var import_element115 = __toESM(require_element(), 1);
  var import_compose17 = __toESM(require_compose(), 1);
  function captureAnchorElement(container, anchorElementRef, direction) {
    const containerRect = container.getBoundingClientRect();
    const centerY = containerRect.top + containerRect.height / 2;
    const items = Array.from(container.querySelectorAll("[aria-posinset]"));
    if (items.length === 0) {
      return false;
    }
    const bestAnchor = items.reduce((best, item) => {
      const itemRect = item.getBoundingClientRect();
      const itemCenterY = itemRect.top + itemRect.height / 2;
      const distance = Math.abs(itemCenterY - centerY);
      const bestRect = best.getBoundingClientRect();
      const bestCenterY = bestRect.top + bestRect.height / 2;
      const bestDistance = Math.abs(bestCenterY - centerY);
      return distance < bestDistance ? item : best;
    });
    const posinset = Number(bestAnchor.getAttribute("aria-posinset"));
    const anchorRect = bestAnchor.getBoundingClientRect();
    anchorElementRef.current = {
      posinset,
      viewportOffset: anchorRect.top - containerRect.top,
      scrollTop: container.scrollTop,
      direction
    };
    return true;
  }
  function useInfiniteScroll({
    view,
    onChangeView,
    isLoading,
    paginationInfo,
    containerRef,
    setVisibleEntries
  }) {
    const anchorElementRef = (0, import_element115.useRef)(null);
    const viewRef = (0, import_element115.useRef)(view);
    const isLoadingRef = (0, import_element115.useRef)(isLoading);
    const onChangeViewRef = (0, import_element115.useRef)(onChangeView);
    const totalItemsRef = (0, import_element115.useRef)(paginationInfo.totalItems);
    (0, import_element115.useLayoutEffect)(() => {
      viewRef.current = view;
      isLoadingRef.current = isLoading;
      onChangeViewRef.current = onChangeView;
      totalItemsRef.current = paginationInfo.totalItems;
    }, [view, isLoading, onChangeView, paginationInfo.totalItems]);
    const intersectionObserverCallback = (0, import_element115.useCallback)(
      (entries) => {
        if (!setVisibleEntries) {
          return;
        }
        setVisibleEntries((prev) => {
          const newVisibleEntries = new Set(prev);
          let hasChanged = false;
          entries.forEach((entry) => {
            const posInSet = Number(
              entry.target?.attributes?.getNamedItem(
                "aria-posinset"
              )?.value
            );
            if (isNaN(posInSet)) {
              return;
            }
            if (entry.isIntersecting) {
              if (!newVisibleEntries.has(posInSet)) {
                newVisibleEntries.add(posInSet);
                hasChanged = true;
              }
            } else if (newVisibleEntries.has(posInSet)) {
              newVisibleEntries.delete(posInSet);
              hasChanged = true;
            }
          });
          return hasChanged ? Array.from(newVisibleEntries).sort() : prev;
        });
      },
      [setVisibleEntries]
    );
    (0, import_element115.useLayoutEffect)(() => {
      const container = containerRef.current;
      const anchor = anchorElementRef.current;
      if (!container || !view.infiniteScrollEnabled || !anchor || isLoading) {
        return;
      }
      const anchorElement = container.querySelector(
        `[aria-posinset="${anchor.posinset}"]`
      );
      if (anchorElement) {
        const containerRect = container.getBoundingClientRect();
        const anchorRect = anchorElement.getBoundingClientRect();
        const currentOffset = anchorRect.top - containerRect.top;
        const scrollAdjustment = currentOffset - anchor.viewportOffset + (container.scrollTop - anchor.scrollTop);
        if (Math.abs(scrollAdjustment) > 1) {
          container.scrollTop += scrollAdjustment;
        }
      }
      anchorElementRef.current = null;
    }, [containerRef, isLoading, view.infiniteScrollEnabled]);
    const intersectionObserverRef = (0, import_element115.useRef)(
      null
    );
    (0, import_element115.useEffect)(() => {
      if (!view.infiniteScrollEnabled || !intersectionObserverCallback) {
        if (intersectionObserverRef.current) {
          intersectionObserverRef.current.disconnect();
          intersectionObserverRef.current = null;
        }
        return;
      }
      intersectionObserverRef.current = new IntersectionObserver(
        intersectionObserverCallback,
        { root: null, rootMargin: "0px", threshold: 0.1 }
      );
      return () => {
        if (intersectionObserverRef.current) {
          intersectionObserverRef.current.disconnect();
          intersectionObserverRef.current = null;
        }
      };
    }, [view.infiniteScrollEnabled, intersectionObserverCallback]);
    (0, import_element115.useEffect)(() => {
      if (!view.infiniteScrollEnabled || !containerRef.current) {
        return;
      }
      let lastScrollTop = 0;
      const BOTTOM_THRESHOLD = 600;
      const TOP_THRESHOLD = 800;
      const handleScroll = (0, import_compose17.throttle)((event) => {
        const currentView = viewRef.current;
        const totalItems = totalItemsRef.current;
        const target = event.target;
        const scrollTop = target.scrollTop;
        const scrollHeight = target.scrollHeight;
        const clientHeight = target.clientHeight;
        const scrollDirection = scrollTop > lastScrollTop ? "down" : "up";
        lastScrollTop = scrollTop;
        if (isLoadingRef.current) {
          return;
        }
        const currentStartPosition = currentView.startPosition || 1;
        const batchSize = currentView.perPage || 10;
        const currentEndPosition = Math.min(
          currentStartPosition + batchSize,
          totalItems
        );
        if (scrollDirection === "down" && scrollTop + clientHeight >= scrollHeight - BOTTOM_THRESHOLD) {
          if (currentEndPosition < totalItems) {
            const newStartPosition = currentEndPosition;
            captureAnchorElement(target, anchorElementRef, "down");
            onChangeViewRef.current({
              ...currentView,
              startPosition: newStartPosition
            });
          }
        }
        if (scrollDirection === "up" && scrollTop <= TOP_THRESHOLD) {
          if (currentStartPosition > 1) {
            const calculatedStartPosition = currentStartPosition - batchSize;
            const newStartPosition = calculatedStartPosition < 6 ? 1 : calculatedStartPosition;
            captureAnchorElement(target, anchorElementRef, "up");
            onChangeViewRef.current({
              ...currentView,
              startPosition: newStartPosition
            });
          }
        }
      }, 50);
      const container = containerRef.current;
      container.addEventListener("scroll", handleScroll);
      return () => {
        container.removeEventListener("scroll", handleScroll);
        handleScroll.cancel();
      };
    }, [containerRef, view.infiniteScrollEnabled]);
    return {
      intersectionObserver: intersectionObserverRef.current
    };
  }

  // packages/dataviews/build-module/dataviews/index.mjs
  var import_jsx_runtime197 = __toESM(require_jsx_runtime(), 1);
  var defaultGetItemId = (item) => item.id;
  var defaultIsItemClickable = () => true;
  var EMPTY_ARRAY8 = [];
  var DEFAULT_LAYOUTS = { table: {}, grid: {}, list: {} };
  var dataViewsLayouts = VIEW_LAYOUTS.filter(
    (viewLayout) => !viewLayout.isPicker
  );
  function DefaultUI({
    header,
    search = true,
    searchLabel = void 0
  }) {
    const { view } = (0, import_element116.useContext)(dataviews_context_default);
    const isInfiniteScroll = view.infiniteScrollEnabled;
    return /* @__PURE__ */ (0, import_jsx_runtime197.jsxs)(import_jsx_runtime197.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime197.jsxs)(
        Stack,
        {
          direction: "row",
          align: "top",
          justify: "space-between",
          className: clsx_default("dataviews__view-actions", {
            "dataviews__view-actions--infinite-scroll": isInfiniteScroll
          }),
          gap: "xs",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime197.jsxs)(
              Stack,
              {
                direction: "row",
                justify: "start",
                gap: "sm",
                className: "dataviews__search",
                children: [
                  search && /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(dataviews_search_default, { label: searchLabel }),
                  /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(toggle_default, {})
                ]
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime197.jsxs)(Stack, { direction: "row", gap: "xs", style: { flexShrink: 0 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(dataviews_view_config_default, {}),
              header
            ] })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(filters_toggled_default, { className: "dataviews-filters__container" }),
      /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(DataViewsLayout, {}),
      /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(DataViewsFooter, {})
    ] });
  }
  function DataViews({
    view,
    onChangeView,
    fields: fields2,
    search = true,
    searchLabel = void 0,
    actions = EMPTY_ARRAY8,
    data,
    getItemId: getItemId2 = defaultGetItemId,
    getItemLevel: getItemLevel2,
    isLoading = false,
    paginationInfo,
    defaultLayouts: defaultLayoutsProperty = DEFAULT_LAYOUTS,
    selection: selectionProperty,
    onChangeSelection,
    onClickItem,
    renderItemLink,
    isItemClickable = defaultIsItemClickable,
    header,
    children,
    config: config2 = { perPageSizes: [10, 20, 50, 100] },
    empty,
    onReset
  }) {
    const [selectionState, setSelectionState] = (0, import_element116.useState)([]);
    const isUncontrolled = selectionProperty === void 0 || onChangeSelection === void 0;
    const selection = isUncontrolled ? selectionState : selectionProperty;
    const {
      data: displayData,
      paginationInfo: displayPaginationInfo,
      hasInitiallyLoaded,
      setVisibleEntries
    } = useData({
      view,
      data,
      getItemId: getItemId2,
      isLoading,
      selection,
      paginationInfo
    });
    const containerRef = (0, import_element116.useRef)(null);
    const [containerWidth, setContainerWidth] = (0, import_element116.useState)(0);
    const resizeObserverRef = (0, import_compose18.useResizeObserver)(
      (resizeObserverEntries) => {
        setContainerWidth(
          resizeObserverEntries[0].borderBoxSize[0].inlineSize
        );
      },
      { box: "border-box" }
    );
    const [openedFilter, setOpenedFilter] = (0, import_element116.useState)(null);
    function setSelectionWithChange(value) {
      const newValue = typeof value === "function" ? value(selection) : value;
      if (isUncontrolled) {
        setSelectionState(newValue);
      }
      if (onChangeSelection) {
        onChangeSelection(newValue);
      }
    }
    const _fields = (0, import_element116.useMemo)(() => normalizeFields(fields2), [fields2]);
    const _selection = (0, import_element116.useMemo)(() => {
      if (view.infiniteScrollEnabled) {
        return selection;
      }
      return selection.filter(
        (id) => data.some((item) => getItemId2(item) === id)
      );
    }, [selection, data, getItemId2, view.infiniteScrollEnabled]);
    const filters = use_filters_default(_fields, view);
    const hasPrimaryOrLockedFilters = (0, import_element116.useMemo)(
      () => (filters || []).some(
        (filter) => filter.isPrimary || filter.isLocked
      ),
      [filters]
    );
    const [isShowingFilter, setIsShowingFilter] = (0, import_element116.useState)(
      hasPrimaryOrLockedFilters
    );
    const { intersectionObserver } = useInfiniteScroll({
      view,
      onChangeView,
      isLoading,
      paginationInfo,
      containerRef,
      setVisibleEntries
    });
    (0, import_element116.useEffect)(() => {
      if (hasPrimaryOrLockedFilters && !isShowingFilter) {
        setIsShowingFilter(true);
      }
    }, [hasPrimaryOrLockedFilters, isShowingFilter]);
    const defaultLayouts2 = (0, import_element116.useMemo)(
      () => Object.fromEntries(
        Object.entries(defaultLayoutsProperty).filter(([layoutType]) => {
          return dataViewsLayouts.some(
            (viewLayout) => viewLayout.type === layoutType
          );
        }).map(([key, value]) => [
          key,
          value === true ? {} : value
        ])
      ),
      [defaultLayoutsProperty]
    );
    if (!defaultLayouts2[view.type]) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
      dataviews_context_default.Provider,
      {
        value: {
          view,
          onChangeView,
          fields: _fields,
          actions,
          data: displayData,
          isLoading,
          paginationInfo: displayPaginationInfo,
          selection: _selection,
          onChangeSelection: setSelectionWithChange,
          openedFilter,
          setOpenedFilter,
          getItemId: getItemId2,
          getItemLevel: getItemLevel2,
          isItemClickable,
          onClickItem,
          renderItemLink,
          containerWidth,
          containerRef,
          resizeObserverRef,
          defaultLayouts: defaultLayouts2,
          filters,
          isShowingFilter,
          setIsShowingFilter,
          config: config2,
          empty,
          hasInitiallyLoaded,
          onReset,
          intersectionObserver
        },
        children: /* @__PURE__ */ (0, import_jsx_runtime197.jsx)("div", { className: "dataviews-wrapper", children: children ?? /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
          DefaultUI,
          {
            header,
            search,
            searchLabel
          }
        ) })
      }
    );
  }
  var DataViewsSubComponents = DataViews;
  DataViewsSubComponents.BulkActionToolbar = BulkActionsFooter;
  DataViewsSubComponents.Filters = filters_default;
  DataViewsSubComponents.FiltersToggled = filters_toggled_default;
  DataViewsSubComponents.FiltersToggle = toggle_default;
  DataViewsSubComponents.Layout = DataViewsLayout;
  DataViewsSubComponents.LayoutSwitcher = ViewTypeMenu;
  DataViewsSubComponents.Pagination = DataViewsPagination;
  DataViewsSubComponents.Search = dataviews_search_default;
  DataViewsSubComponents.ViewConfig = DataviewsViewConfigDropdown;
  DataViewsSubComponents.Footer = DataViewsFooter;
  var dataviews_default = DataViewsSubComponents;

  // packages/dataviews/build-module/dataform/index.mjs
  var import_element128 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataform-context/index.mjs
  var import_element117 = __toESM(require_element(), 1);
  var import_jsx_runtime198 = __toESM(require_jsx_runtime(), 1);
  var DataFormContext = (0, import_element117.createContext)({
    fields: []
  });
  DataFormContext.displayName = "DataFormContext";
  function DataFormProvider({
    fields: fields2,
    children
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime198.jsx)(DataFormContext.Provider, { value: { fields: fields2 }, children });
  }
  var dataform_context_default = DataFormContext;

  // packages/dataviews/build-module/components/dataform-layouts/data-form-layout.mjs
  var import_element127 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataform-layouts/regular/index.mjs
  var import_element118 = __toESM(require_element(), 1);
  var import_components66 = __toESM(require_components(), 1);

  // packages/dataviews/build-module/components/dataform-layouts/normalize-form.mjs
  var import_i18n67 = __toESM(require_i18n(), 1);
  var DEFAULT_LAYOUT = {
    type: "regular",
    labelPosition: "top"
  };
  var normalizeCardSummaryField = (sum) => {
    if (typeof sum === "string") {
      return [{ id: sum, visibility: "when-collapsed" }];
    }
    return sum.map((item) => {
      if (typeof item === "string") {
        return { id: item, visibility: "when-collapsed" };
      }
      return { id: item.id, visibility: item.visibility };
    });
  };
  function normalizeLayout(layout) {
    let normalizedLayout = DEFAULT_LAYOUT;
    if (layout?.type === "regular") {
      normalizedLayout = {
        type: "regular",
        labelPosition: layout?.labelPosition ?? "top"
      };
    } else if (layout?.type === "panel") {
      const summary = layout.summary ?? [];
      const normalizedSummary = Array.isArray(summary) ? summary : [summary];
      const openAs = layout?.openAs;
      let normalizedOpenAs;
      if (typeof openAs === "object" && openAs.type === "modal") {
        normalizedOpenAs = {
          type: "modal",
          applyLabel: openAs.applyLabel?.trim() || (0, import_i18n67.__)("Apply"),
          cancelLabel: openAs.cancelLabel?.trim() || (0, import_i18n67.__)("Cancel")
        };
      } else if (openAs === "modal") {
        normalizedOpenAs = {
          type: "modal",
          applyLabel: (0, import_i18n67.__)("Apply"),
          cancelLabel: (0, import_i18n67.__)("Cancel")
        };
      } else {
        normalizedOpenAs = { type: "dropdown" };
      }
      normalizedLayout = {
        type: "panel",
        labelPosition: layout?.labelPosition ?? "side",
        openAs: normalizedOpenAs,
        summary: normalizedSummary,
        editVisibility: layout?.editVisibility ?? "on-hover"
      };
    } else if (layout?.type === "card") {
      if (layout.withHeader === false) {
        normalizedLayout = {
          type: "card",
          withHeader: false,
          isOpened: true,
          summary: [],
          isCollapsible: false
        };
      } else {
        const summary = layout.summary ?? [];
        normalizedLayout = {
          type: "card",
          withHeader: true,
          isOpened: typeof layout.isOpened === "boolean" ? layout.isOpened : true,
          summary: normalizeCardSummaryField(summary),
          isCollapsible: layout.isCollapsible === void 0 ? true : layout.isCollapsible
        };
      }
    } else if (layout?.type === "row") {
      normalizedLayout = {
        type: "row",
        alignment: layout?.alignment ?? "center",
        styles: layout?.styles ?? {}
      };
    } else if (layout?.type === "details") {
      normalizedLayout = {
        type: "details",
        summary: layout?.summary ?? ""
      };
    }
    return normalizedLayout;
  }
  function normalizeForm(form2) {
    const normalizedFormLayout = normalizeLayout(form2?.layout);
    const normalizedFields = (form2.fields ?? []).map(
      (field) => {
        if (typeof field === "string") {
          return {
            id: field,
            layout: normalizedFormLayout
          };
        }
        const fieldLayout = field.layout ? normalizeLayout(field.layout) : normalizedFormLayout;
        return {
          id: field.id,
          layout: fieldLayout,
          ...!!field.label && { label: field.label },
          ...!!field.description && {
            description: field.description
          },
          ..."children" in field && Array.isArray(field.children) && {
            children: normalizeForm({
              fields: field.children,
              layout: DEFAULT_LAYOUT
            }).fields
          }
        };
      }
    );
    return {
      layout: normalizedFormLayout,
      fields: normalizedFields
    };
  }
  var normalize_form_default = normalizeForm;

  // packages/dataviews/build-module/components/dataform-layouts/regular/index.mjs
  var import_jsx_runtime199 = __toESM(require_jsx_runtime(), 1);
  function Header4({ title }) {
    return /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(
      Stack,
      {
        direction: "column",
        className: "dataforms-layouts-regular__header",
        gap: "lg",
        children: /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(Stack, { direction: "row", align: "center", children: /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(import_components66.__experimentalHeading, { level: 2, size: 13, children: title }) })
      }
    );
  }
  function FormRegularField({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { fields: fields2 } = (0, import_element118.useContext)(dataform_context_default);
    const layout = field.layout;
    const form2 = (0, import_element118.useMemo)(
      () => ({
        layout: DEFAULT_LAYOUT,
        fields: !!field.children ? field.children : []
      }),
      [field]
    );
    if (!!field.children) {
      return /* @__PURE__ */ (0, import_jsx_runtime199.jsxs)(import_jsx_runtime199.Fragment, { children: [
        !hideLabelFromVision && field.label && /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(Header4, { title: field.label }),
        /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(
          DataFormLayout,
          {
            data,
            form: form2,
            onChange,
            validity: validity?.children
          }
        )
      ] });
    }
    const labelPosition = layout.labelPosition;
    const fieldDefinition = fields2.find(
      (fieldDef) => fieldDef.id === field.id
    );
    if (!fieldDefinition || !fieldDefinition.Edit) {
      return null;
    }
    if (labelPosition === "side") {
      return /* @__PURE__ */ (0, import_jsx_runtime199.jsxs)(
        Stack,
        {
          direction: "row",
          className: "dataforms-layouts-regular__field",
          gap: "sm",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(
              "div",
              {
                className: clsx_default(
                  "dataforms-layouts-regular__field-label",
                  `dataforms-layouts-regular__field-label--label-position-${labelPosition}`
                ),
                children: /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(import_components66.BaseControl.VisualLabel, { children: fieldDefinition.label })
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime199.jsx)("div", { className: "dataforms-layouts-regular__field-control", children: fieldDefinition.readOnly === true ? /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(
              fieldDefinition.render,
              {
                item: data,
                field: fieldDefinition
              }
            ) : /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(
              fieldDefinition.Edit,
              {
                data,
                field: fieldDefinition,
                onChange,
                hideLabelFromVision: true,
                markWhenOptional,
                validity
              },
              fieldDefinition.id
            ) })
          ]
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime199.jsx)("div", { className: "dataforms-layouts-regular__field", children: fieldDefinition.readOnly === true ? /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(import_jsx_runtime199.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime199.jsxs)(import_jsx_runtime199.Fragment, { children: [
      !hideLabelFromVision && labelPosition !== "none" && /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(import_components66.BaseControl.VisualLabel, { children: fieldDefinition.label }),
      /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(
        fieldDefinition.render,
        {
          item: data,
          field: fieldDefinition
        }
      )
    ] }) }) : /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(
      fieldDefinition.Edit,
      {
        data,
        field: fieldDefinition,
        onChange,
        hideLabelFromVision: labelPosition === "none" ? true : hideLabelFromVision,
        markWhenOptional,
        validity
      }
    ) });
  }

  // packages/dataviews/build-module/components/dataform-layouts/panel/modal.mjs
  var import_deepmerge3 = __toESM(require_cjs(), 1);
  var import_components69 = __toESM(require_components(), 1);
  var import_element123 = __toESM(require_element(), 1);
  var import_compose20 = __toESM(require_compose(), 1);

  // packages/dataviews/build-module/components/dataform-layouts/panel/summary-button.mjs
  var import_components68 = __toESM(require_components(), 1);
  var import_i18n68 = __toESM(require_i18n(), 1);
  var import_compose19 = __toESM(require_compose(), 1);
  var import_element119 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataform-layouts/panel/utils/get-label-classname.mjs
  function getLabelClassName(labelPosition, showError) {
    return clsx_default(
      "dataforms-layouts-panel__field-label",
      `dataforms-layouts-panel__field-label--label-position-${labelPosition}`,
      { "has-error": showError }
    );
  }
  var get_label_classname_default = getLabelClassName;

  // packages/dataviews/build-module/components/dataform-layouts/panel/utils/get-label-content.mjs
  var import_components67 = __toESM(require_components(), 1);
  var import_jsx_runtime200 = __toESM(require_jsx_runtime(), 1);
  function getLabelContent(showError, errorMessage, fieldLabel) {
    return showError ? /* @__PURE__ */ (0, import_jsx_runtime200.jsxs)(tooltip_exports.Root, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime200.jsx)(
        tooltip_exports.Trigger,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime200.jsxs)("span", { className: "dataforms-layouts-panel__field-label-error-content", children: [
            /* @__PURE__ */ (0, import_jsx_runtime200.jsx)(import_components67.Icon, { icon: error_default, size: 16 }),
            /* @__PURE__ */ (0, import_jsx_runtime200.jsxs)(VisuallyHidden, { children: [
              errorMessage,
              ": "
            ] }),
            fieldLabel
          ] })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime200.jsx)(tooltip_exports.Popup, { children: errorMessage })
    ] }) : fieldLabel;
  }
  var get_label_content_default = getLabelContent;

  // packages/dataviews/build-module/components/dataform-layouts/panel/utils/get-first-validation-error.mjs
  function getFirstValidationError(validity) {
    if (!validity) {
      return void 0;
    }
    const validityRules = Object.keys(validity).filter(
      (key) => key !== "children"
    );
    for (const key of validityRules) {
      const rule = validity[key];
      if (rule === void 0) {
        continue;
      }
      if (rule.type === "invalid") {
        if (rule.message) {
          return rule.message;
        }
        if (key === "required") {
          return "A required field is empty";
        }
        return "Unidentified validation error";
      }
    }
    if (validity.children) {
      for (const childValidity of Object.values(validity.children)) {
        const childError = getFirstValidationError(childValidity);
        if (childError) {
          return childError;
        }
      }
    }
    return void 0;
  }
  var get_first_validation_error_default = getFirstValidationError;

  // packages/dataviews/build-module/components/dataform-layouts/panel/summary-button.mjs
  var import_jsx_runtime201 = __toESM(require_jsx_runtime(), 1);
  function SummaryButton({
    data,
    field,
    fieldLabel,
    summaryFields,
    validity,
    touched,
    disabled: disabled2,
    isOpen,
    onClick
  }) {
    const { labelPosition, editVisibility } = field.layout;
    const errorMessage = get_first_validation_error_default(validity);
    const showError = touched && !!errorMessage;
    const labelClassName = get_label_classname_default(labelPosition, showError);
    const labelContent = get_label_content_default(showError, errorMessage, fieldLabel);
    const className = clsx_default(
      "dataforms-layouts-panel__field-trigger",
      `dataforms-layouts-panel__field-trigger--label-${labelPosition}`,
      {
        "is-disabled": disabled2,
        "dataforms-layouts-panel__field-trigger--edit-always": editVisibility === "always"
      }
    );
    const controlId = (0, import_compose19.useInstanceId)(
      SummaryButton,
      "dataforms-layouts-panel__field-control"
    );
    const ariaLabel = showError ? (0, import_i18n68.sprintf)(
      // translators: %s: Field name.
      (0, import_i18n68._x)("Edit %s (has errors)", "field"),
      fieldLabel || ""
    ) : (0, import_i18n68.sprintf)(
      // translators: %s: Field name.
      (0, import_i18n68._x)("Edit %s", "field"),
      fieldLabel || ""
    );
    const rowRef = (0, import_element119.useRef)(null);
    const editButtonRef = (0, import_element119.useRef)(null);
    const handleRowClick = (event) => {
      if (!isOpen && event.detail < 2 && !editButtonRef.current?.contains(event.target) && rowRef.current?.ownerDocument.defaultView?.getSelection()?.toString()) {
        return;
      }
      onClick();
    };
    const handleKeyDown = (event) => {
      if (event.target === event.currentTarget && (event.key === "Enter" || event.key === " ")) {
        event.preventDefault();
        onClick();
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime201.jsxs)(
      "div",
      {
        ref: rowRef,
        className,
        onClick: !disabled2 ? handleRowClick : void 0,
        onKeyDown: !disabled2 ? handleKeyDown : void 0,
        children: [
          labelPosition !== "none" && /* @__PURE__ */ (0, import_jsx_runtime201.jsx)("span", { className: labelClassName, children: labelContent }),
          labelPosition === "none" && showError && /* @__PURE__ */ (0, import_jsx_runtime201.jsxs)(tooltip_exports.Root, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(
              tooltip_exports.Trigger,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(
                  "span",
                  {
                    className: "dataforms-layouts-panel__field-label-error-content",
                    role: "img",
                    "aria-label": errorMessage,
                    children: /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(import_components68.Icon, { icon: error_default, size: 16 })
                  }
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(tooltip_exports.Popup, { children: errorMessage })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(
            "span",
            {
              id: `${controlId}`,
              className: "dataforms-layouts-panel__field-control",
              children: summaryFields.length > 1 ? /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(
                "span",
                {
                  style: {
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "flex-start",
                    width: "100%",
                    gap: "2px"
                  },
                  children: summaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(
                    "span",
                    {
                      style: { width: "100%" },
                      children: /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(
                        summaryField.render,
                        {
                          item: data,
                          field: summaryField
                        }
                      )
                    },
                    summaryField.id
                  ))
                }
              ) : summaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(
                summaryField.render,
                {
                  item: data,
                  field: summaryField
                },
                summaryField.id
              ))
            }
          ),
          !disabled2 && /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(
            import_components68.Button,
            {
              ref: editButtonRef,
              className: "dataforms-layouts-panel__field-trigger-icon",
              label: ariaLabel,
              icon: pencil_default,
              size: "small",
              "aria-expanded": isOpen,
              "aria-haspopup": "dialog",
              "aria-describedby": `${controlId}`
            }
          )
        ]
      }
    );
  }

  // packages/dataviews/build-module/hooks/use-form-validity.mjs
  var import_deepmerge2 = __toESM(require_cjs(), 1);
  var import_es63 = __toESM(require_es6(), 1);
  var import_element120 = __toESM(require_element(), 1);
  var import_i18n69 = __toESM(require_i18n(), 1);
  function isFormValid(formValidity) {
    if (!formValidity) {
      return true;
    }
    return Object.values(formValidity).every((fieldValidation) => {
      return Object.entries(fieldValidation).every(
        ([key, validation]) => {
          if (key === "children" && validation && typeof validation === "object") {
            return isFormValid(validation);
          }
          return validation.type !== "invalid" && validation.type !== "validating";
        }
      );
    });
  }
  function getFormFieldsToValidate(form2, fields2) {
    const normalizedForm = normalize_form_default(form2);
    if (normalizedForm.fields.length === 0) {
      return [];
    }
    const fieldsMap = /* @__PURE__ */ new Map();
    fields2.forEach((field) => {
      fieldsMap.set(field.id, field);
    });
    function processFormField(formField) {
      if ("children" in formField && Array.isArray(formField.children)) {
        const processedChildren = formField.children.map(processFormField).filter((child) => child !== null);
        if (processedChildren.length === 0) {
          return null;
        }
        const fieldDef2 = fieldsMap.get(formField.id);
        if (fieldDef2) {
          const [normalizedField2] = normalizeFields([
            fieldDef2
          ]);
          return {
            id: formField.id,
            children: processedChildren,
            field: normalizedField2
          };
        }
        return {
          id: formField.id,
          children: processedChildren
        };
      }
      const fieldDef = fieldsMap.get(formField.id);
      if (!fieldDef) {
        return null;
      }
      const [normalizedField] = normalizeFields([fieldDef]);
      return {
        id: formField.id,
        children: [],
        field: normalizedField
      };
    }
    const toValidate = normalizedForm.fields.map(processFormField).filter((field) => field !== null);
    return toValidate;
  }
  function setValidityAtPath(formValidity, fieldValidity, path) {
    if (!formValidity) {
      formValidity = {};
    }
    if (path.length === 0) {
      return formValidity;
    }
    const result = { ...formValidity };
    let current = result;
    for (let i2 = 0; i2 < path.length - 1; i2++) {
      const segment = path[i2];
      if (!current[segment]) {
        current[segment] = {};
      }
      current[segment] = { ...current[segment] };
      current = current[segment];
    }
    const finalKey = path[path.length - 1];
    current[finalKey] = {
      ...current[finalKey] || {},
      ...fieldValidity
    };
    return result;
  }
  function removeValidationProperty(formValidity, path, property) {
    if (!formValidity || path.length === 0) {
      return formValidity;
    }
    const result = { ...formValidity };
    let current = result;
    for (let i2 = 0; i2 < path.length - 1; i2++) {
      const segment = path[i2];
      if (!current[segment]) {
        return formValidity;
      }
      current[segment] = { ...current[segment] };
      current = current[segment];
    }
    const finalKey = path[path.length - 1];
    if (!current[finalKey]) {
      return formValidity;
    }
    const fieldValidity = { ...current[finalKey] };
    delete fieldValidity[property];
    if (Object.keys(fieldValidity).length === 0) {
      delete current[finalKey];
    } else {
      current[finalKey] = fieldValidity;
    }
    if (Object.keys(result).length === 0) {
      return void 0;
    }
    return result;
  }
  function handleElementsValidationAsync(promise, formField, promiseHandler) {
    const { elementsCounterRef, setFormValidity, path, item } = promiseHandler;
    const currentToken = (elementsCounterRef.current[formField.id] || 0) + 1;
    elementsCounterRef.current[formField.id] = currentToken;
    promise.then((result) => {
      if (currentToken !== elementsCounterRef.current[formField.id]) {
        return;
      }
      if (!Array.isArray(result)) {
        setFormValidity((prev) => {
          const newFormValidity = setValidityAtPath(
            prev,
            {
              elements: {
                type: "invalid",
                message: (0, import_i18n69.__)("Could not validate elements.")
              }
            },
            [...path, formField.id]
          );
          return newFormValidity;
        });
        return;
      }
      if (formField.field?.isValid.elements && !formField.field.isValid.elements.validate(item, {
        ...formField.field,
        elements: result
      })) {
        setFormValidity((prev) => {
          const newFormValidity = setValidityAtPath(
            prev,
            {
              elements: {
                type: "invalid",
                message: (0, import_i18n69.__)(
                  "Value must be one of the elements."
                )
              }
            },
            [...path, formField.id]
          );
          return newFormValidity;
        });
      } else {
        setFormValidity((prev) => {
          return removeValidationProperty(
            prev,
            [...path, formField.id],
            "elements"
          );
        });
      }
    }).catch((error2) => {
      if (currentToken !== elementsCounterRef.current[formField.id]) {
        return;
      }
      let errorMessage;
      if (error2 instanceof Error) {
        errorMessage = error2.message;
      } else {
        errorMessage = String(error2) || (0, import_i18n69.__)(
          "Unknown error when running elements validation asynchronously."
        );
      }
      setFormValidity((prev) => {
        const newFormValidity = setValidityAtPath(
          prev,
          {
            elements: {
              type: "invalid",
              message: errorMessage
            }
          },
          [...path, formField.id]
        );
        return newFormValidity;
      });
    });
  }
  function handleCustomValidationAsync(promise, formField, promiseHandler) {
    const { customCounterRef, setFormValidity, path } = promiseHandler;
    const currentToken = (customCounterRef.current[formField.id] || 0) + 1;
    customCounterRef.current[formField.id] = currentToken;
    promise.then((result) => {
      if (currentToken !== customCounterRef.current[formField.id]) {
        return;
      }
      if (result === null) {
        setFormValidity((prev) => {
          return removeValidationProperty(
            prev,
            [...path, formField.id],
            "custom"
          );
        });
        return;
      }
      if (typeof result === "string") {
        setFormValidity((prev) => {
          const newFormValidity = setValidityAtPath(
            prev,
            {
              custom: {
                type: "invalid",
                message: result
              }
            },
            [...path, formField.id]
          );
          return newFormValidity;
        });
        return;
      }
      setFormValidity((prev) => {
        const newFormValidity = setValidityAtPath(
          prev,
          {
            custom: {
              type: "invalid",
              message: (0, import_i18n69.__)("Validation could not be processed.")
            }
          },
          [...path, formField.id]
        );
        return newFormValidity;
      });
    }).catch((error2) => {
      if (currentToken !== customCounterRef.current[formField.id]) {
        return;
      }
      let errorMessage;
      if (error2 instanceof Error) {
        errorMessage = error2.message;
      } else {
        errorMessage = String(error2) || (0, import_i18n69.__)(
          "Unknown error when running custom validation asynchronously."
        );
      }
      setFormValidity((prev) => {
        const newFormValidity = setValidityAtPath(
          prev,
          {
            custom: {
              type: "invalid",
              message: errorMessage
            }
          },
          [...path, formField.id]
        );
        return newFormValidity;
      });
    });
  }
  function validateFormField(item, formField, promiseHandler) {
    if (formField.field?.isValid.required && !formField.field.isValid.required.validate(item, formField.field)) {
      return {
        required: { type: "invalid" }
      };
    }
    if (formField.field?.isValid.pattern && !formField.field.isValid.pattern.validate(item, formField.field)) {
      return {
        pattern: {
          type: "invalid",
          message: (0, import_i18n69.__)("Value does not match the required pattern.")
        }
      };
    }
    if (formField.field?.isValid.min && !formField.field.isValid.min.validate(item, formField.field)) {
      return {
        min: {
          type: "invalid",
          message: (0, import_i18n69.__)("Value is below the minimum.")
        }
      };
    }
    if (formField.field?.isValid.max && !formField.field.isValid.max.validate(item, formField.field)) {
      return {
        max: {
          type: "invalid",
          message: (0, import_i18n69.__)("Value is above the maximum.")
        }
      };
    }
    if (formField.field?.isValid.minLength && !formField.field.isValid.minLength.validate(item, formField.field)) {
      return {
        minLength: {
          type: "invalid",
          message: (0, import_i18n69.__)("Value is too short.")
        }
      };
    }
    if (formField.field?.isValid.maxLength && !formField.field.isValid.maxLength.validate(item, formField.field)) {
      return {
        maxLength: {
          type: "invalid",
          message: (0, import_i18n69.__)("Value is too long.")
        }
      };
    }
    if (formField.field?.isValid.elements && formField.field.hasElements && !formField.field.getElements && Array.isArray(formField.field.elements) && !formField.field.isValid.elements.validate(item, formField.field)) {
      return {
        elements: {
          type: "invalid",
          message: (0, import_i18n69.__)("Value must be one of the elements.")
        }
      };
    }
    let customError;
    if (!!formField.field && formField.field.isValid.custom) {
      try {
        const value = formField.field.getValue({ item });
        customError = formField.field.isValid.custom(
          (0, import_deepmerge2.default)(
            item,
            formField.field.setValue({
              item,
              value
            })
          ),
          formField.field
        );
      } catch (error2) {
        let errorMessage;
        if (error2 instanceof Error) {
          errorMessage = error2.message;
        } else {
          errorMessage = String(error2) || (0, import_i18n69.__)("Unknown error when running custom validation.");
        }
        return {
          custom: {
            type: "invalid",
            message: errorMessage
          }
        };
      }
    }
    if (typeof customError === "string") {
      return {
        custom: {
          type: "invalid",
          message: customError
        }
      };
    }
    const fieldValidity = {};
    if (!!formField.field && formField.field.isValid.elements && formField.field.hasElements && typeof formField.field.getElements === "function") {
      handleElementsValidationAsync(
        formField.field.getElements(),
        formField,
        promiseHandler
      );
      fieldValidity.elements = {
        type: "validating",
        message: (0, import_i18n69.__)("Validating\u2026")
      };
    }
    if (customError instanceof Promise) {
      handleCustomValidationAsync(customError, formField, promiseHandler);
      fieldValidity.custom = {
        type: "validating",
        message: (0, import_i18n69.__)("Validating\u2026")
      };
    }
    if (Object.keys(fieldValidity).length > 0) {
      return fieldValidity;
    }
    if (formField.children.length > 0) {
      const result = {};
      formField.children.forEach((child) => {
        result[child.id] = validateFormField(item, child, {
          ...promiseHandler,
          path: [...promiseHandler.path, formField.id, "children"]
        });
      });
      const filteredResult = {};
      Object.entries(result).forEach(([key, value]) => {
        if (value !== void 0) {
          filteredResult[key] = value;
        }
      });
      if (Object.keys(filteredResult).length === 0) {
        return void 0;
      }
      return {
        children: filteredResult
      };
    }
    return void 0;
  }
  function getFormFieldValue(formField, item) {
    const fieldValue = formField?.field?.getValue({ item });
    if (formField.children.length === 0) {
      return fieldValue;
    }
    const childrenValues = formField.children.map(
      (child) => getFormFieldValue(child, item)
    );
    if (!childrenValues) {
      return fieldValue;
    }
    return {
      value: fieldValue,
      children: childrenValues
    };
  }
  function useFormValidity(item, fields2, form2) {
    const [formValidity, setFormValidity] = (0, import_element120.useState)();
    const customCounterRef = (0, import_element120.useRef)({});
    const elementsCounterRef = (0, import_element120.useRef)({});
    const previousValuesRef = (0, import_element120.useRef)({});
    const validate = (0, import_element120.useCallback)(() => {
      const promiseHandler = {
        customCounterRef,
        elementsCounterRef,
        setFormValidity,
        path: [],
        item
      };
      const formFieldsToValidate = getFormFieldsToValidate(form2, fields2);
      if (formFieldsToValidate.length === 0) {
        setFormValidity(void 0);
        return;
      }
      const newFormValidity = {};
      const untouchedFields = [];
      formFieldsToValidate.forEach((formField) => {
        const value = getFormFieldValue(formField, item);
        if (previousValuesRef.current.hasOwnProperty(formField.id) && (0, import_es63.default)(
          previousValuesRef.current[formField.id],
          value
        )) {
          untouchedFields.push(formField.id);
          return;
        }
        previousValuesRef.current[formField.id] = value;
        const fieldValidity = validateFormField(
          item,
          formField,
          promiseHandler
        );
        if (fieldValidity !== void 0) {
          newFormValidity[formField.id] = fieldValidity;
        }
      });
      setFormValidity((existingFormValidity) => {
        let validity = {
          ...existingFormValidity,
          ...newFormValidity
        };
        const fieldsToKeep = [
          ...untouchedFields,
          ...Object.keys(newFormValidity)
        ];
        Object.keys(validity).forEach((key) => {
          if (validity && !fieldsToKeep.includes(key)) {
            delete validity[key];
          }
        });
        if (Object.keys(validity).length === 0) {
          validity = void 0;
        }
        const areEqual = (0, import_es63.default)(existingFormValidity, validity);
        if (areEqual) {
          return existingFormValidity;
        }
        return validity;
      });
    }, [item, fields2, form2]);
    (0, import_element120.useEffect)(() => {
      validate();
    }, [validate]);
    return {
      validity: formValidity,
      isValid: isFormValid(formValidity)
    };
  }
  var use_form_validity_default = useFormValidity;

  // packages/dataviews/build-module/hooks/use-report-validity.mjs
  var import_element121 = __toESM(require_element(), 1);
  function useReportValidity(ref, shouldReport) {
    (0, import_element121.useEffect)(() => {
      if (shouldReport && ref.current) {
        const inputs = ref.current.querySelectorAll(
          "input, textarea, select"
        );
        inputs.forEach((input) => {
          input.reportValidity();
        });
      }
    }, [shouldReport, ref]);
  }

  // packages/dataviews/build-module/components/dataform-layouts/panel/utils/use-field-from-form-field.mjs
  var import_element122 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataform-layouts/get-summary-fields.mjs
  function extractSummaryIds(summary) {
    if (Array.isArray(summary)) {
      return summary.map(
        (item) => typeof item === "string" ? item : item.id
      );
    }
    return [];
  }
  var getSummaryFields = (summaryField, fields2) => {
    if (Array.isArray(summaryField) && summaryField.length > 0) {
      const summaryIds = extractSummaryIds(summaryField);
      return summaryIds.map(
        (summaryId) => fields2.find((_field) => _field.id === summaryId)
      ).filter((_field) => _field !== void 0);
    }
    return [];
  };

  // packages/dataviews/build-module/components/dataform-layouts/panel/utils/use-field-from-form-field.mjs
  var getFieldDefinition = (field, fields2) => {
    const fieldDefinition = fields2.find((_field) => _field.id === field.id);
    if (!fieldDefinition) {
      return fields2.find((_field) => {
        if (!!field.children) {
          const simpleChildren = field.children.filter(
            (child) => !child.children
          );
          if (simpleChildren.length === 0) {
            return false;
          }
          return _field.id === simpleChildren[0].id;
        }
        return _field.id === field.id;
      });
    }
    return fieldDefinition;
  };
  function useFieldFromFormField(field) {
    const { fields: fields2 } = (0, import_element122.useContext)(dataform_context_default);
    const layout = field.layout;
    const summaryFields = getSummaryFields(layout.summary, fields2);
    const fieldDefinition = getFieldDefinition(field, fields2);
    const fieldLabel = !!field.children ? field.label : fieldDefinition?.label;
    if (summaryFields.length === 0) {
      return {
        summaryFields: fieldDefinition ? [fieldDefinition] : [],
        fieldDefinition,
        fieldLabel
      };
    }
    return {
      summaryFields,
      fieldDefinition,
      fieldLabel
    };
  }
  var use_field_from_form_field_default = useFieldFromFormField;

  // packages/dataviews/build-module/components/dataform-layouts/panel/modal.mjs
  var import_jsx_runtime202 = __toESM(require_jsx_runtime(), 1);
  function ModalContent({
    data,
    field,
    onChange,
    fieldLabel,
    onClose,
    touched
  }) {
    const { openAs } = field.layout;
    const { applyLabel, cancelLabel } = openAs;
    const { fields: fields2 } = (0, import_element123.useContext)(dataform_context_default);
    const [changes, setChanges] = (0, import_element123.useState)({});
    const modalData = (0, import_element123.useMemo)(() => {
      return (0, import_deepmerge3.default)(data, changes, {
        arrayMerge: (target, source) => source
      });
    }, [data, changes]);
    const form2 = (0, import_element123.useMemo)(
      () => ({
        layout: DEFAULT_LAYOUT,
        fields: !!field.children ? field.children : (
          // If not explicit children return the field id itself.
          [{ id: field.id, layout: DEFAULT_LAYOUT }]
        )
      }),
      [field]
    );
    const fieldsAsFieldType = fields2.map((f2) => ({
      ...f2,
      Edit: f2.Edit === null ? void 0 : f2.Edit,
      isValid: {
        required: f2.isValid.required?.constraint,
        elements: f2.isValid.elements?.constraint,
        min: f2.isValid.min?.constraint,
        max: f2.isValid.max?.constraint,
        pattern: f2.isValid.pattern?.constraint,
        minLength: f2.isValid.minLength?.constraint,
        maxLength: f2.isValid.maxLength?.constraint
      }
    }));
    const { validity } = use_form_validity_default(modalData, fieldsAsFieldType, form2);
    const onApply = () => {
      onChange(changes);
      onClose();
    };
    const handleOnChange = (newValue) => {
      setChanges(
        (prev) => (0, import_deepmerge3.default)(prev, newValue, {
          arrayMerge: (target, source) => source
        })
      );
    };
    const focusOnMountRef = (0, import_compose20.useFocusOnMount)("firstInputElement");
    const contentRef = (0, import_element123.useRef)(null);
    const mergedRef = (0, import_compose20.useMergeRefs)([focusOnMountRef, contentRef]);
    useReportValidity(contentRef, touched);
    return /* @__PURE__ */ (0, import_jsx_runtime202.jsxs)(
      import_components69.Modal,
      {
        className: "dataforms-layouts-panel__modal",
        onRequestClose: onClose,
        isFullScreen: false,
        title: fieldLabel,
        size: "medium",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime202.jsx)("div", { ref: mergedRef, children: /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(
            DataFormLayout,
            {
              data: modalData,
              form: form2,
              onChange: handleOnChange,
              validity,
              children: (FieldLayout, childField, childFieldValidity, markWhenOptional) => /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(
                FieldLayout,
                {
                  data: modalData,
                  field: childField,
                  onChange: handleOnChange,
                  hideLabelFromVision: form2.fields.length < 2,
                  markWhenOptional,
                  validity: childFieldValidity
                },
                childField.id
              )
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime202.jsxs)(
            Stack,
            {
              direction: "row",
              className: "dataforms-layouts-panel__modal-footer",
              gap: "md",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(import_components69.__experimentalSpacer, { style: { flex: 1 } }),
                /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(
                  import_components69.Button,
                  {
                    variant: "tertiary",
                    onClick: onClose,
                    __next40pxDefaultSize: true,
                    children: cancelLabel
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(
                  import_components69.Button,
                  {
                    variant: "primary",
                    onClick: onApply,
                    __next40pxDefaultSize: true,
                    children: applyLabel
                  }
                )
              ]
            }
          )
        ]
      }
    );
  }
  function PanelModal({
    data,
    field,
    onChange,
    validity
  }) {
    const [touched, setTouched] = (0, import_element123.useState)(false);
    const [isOpen, setIsOpen] = (0, import_element123.useState)(false);
    const { fieldDefinition, fieldLabel, summaryFields } = use_field_from_form_field_default(field);
    if (!fieldDefinition) {
      return null;
    }
    const handleClose = () => {
      setIsOpen(false);
      setTouched(true);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime202.jsxs)(import_jsx_runtime202.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(
        SummaryButton,
        {
          data,
          field,
          fieldLabel,
          summaryFields,
          validity,
          touched,
          disabled: fieldDefinition.readOnly === true,
          onClick: () => setIsOpen(true),
          isOpen
        }
      ),
      isOpen && /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(
        ModalContent,
        {
          data,
          field,
          onChange,
          fieldLabel: fieldLabel ?? "",
          onClose: handleClose,
          touched
        }
      )
    ] });
  }
  var modal_default = PanelModal;

  // packages/dataviews/build-module/components/dataform-layouts/panel/dropdown.mjs
  var import_components70 = __toESM(require_components(), 1);
  var import_i18n70 = __toESM(require_i18n(), 1);
  var import_element124 = __toESM(require_element(), 1);
  var import_compose21 = __toESM(require_compose(), 1);
  var import_jsx_runtime203 = __toESM(require_jsx_runtime(), 1);
  function DropdownHeader({
    title,
    onClose
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
      Stack,
      {
        direction: "column",
        className: "dataforms-layouts-panel__dropdown-header",
        gap: "lg",
        children: /* @__PURE__ */ (0, import_jsx_runtime203.jsxs)(Stack, { direction: "row", gap: "sm", align: "center", children: [
          title && /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(import_components70.__experimentalHeading, { level: 2, size: 13, children: title }),
          /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(import_components70.__experimentalSpacer, { style: { flex: 1 } }),
          onClose && /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
            import_components70.Button,
            {
              label: (0, import_i18n70.__)("Close"),
              icon: close_small_default,
              onClick: onClose,
              size: "small"
            }
          )
        ] })
      }
    );
  }
  function DropdownContentWithValidation({
    touched,
    children
  }) {
    const ref = (0, import_element124.useRef)(null);
    useReportValidity(ref, touched);
    return /* @__PURE__ */ (0, import_jsx_runtime203.jsx)("div", { ref, children });
  }
  function PanelDropdown({
    data,
    field,
    onChange,
    validity
  }) {
    const [touched, setTouched] = (0, import_element124.useState)(false);
    const [popoverAnchor, setPopoverAnchor] = (0, import_element124.useState)(
      null
    );
    const popoverProps = (0, import_element124.useMemo)(
      () => ({
        // Anchor the popover to the middle of the entire row so that it doesn't
        // move around when the label changes.
        anchor: popoverAnchor,
        placement: "left-start",
        offset: 36,
        shift: true
      }),
      [popoverAnchor]
    );
    const [dialogRef, dialogProps] = (0, import_compose21.__experimentalUseDialog)({
      focusOnMount: "firstInputElement"
    });
    const form2 = (0, import_element124.useMemo)(
      () => ({
        layout: DEFAULT_LAYOUT,
        fields: !!field.children ? field.children : (
          // If not explicit children return the field id itself.
          [{ id: field.id, layout: DEFAULT_LAYOUT }]
        )
      }),
      [field]
    );
    const formValidity = (0, import_element124.useMemo)(() => {
      if (validity === void 0) {
        return void 0;
      }
      if (!!field.children) {
        return validity?.children;
      }
      return { [field.id]: validity };
    }, [validity, field]);
    const { fieldDefinition, fieldLabel, summaryFields } = use_field_from_form_field_default(field);
    if (!fieldDefinition) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
      "div",
      {
        ref: setPopoverAnchor,
        className: "dataforms-layouts-panel__field-dropdown-anchor",
        children: /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
          import_components70.Dropdown,
          {
            contentClassName: "dataforms-layouts-panel__field-dropdown",
            popoverProps,
            focusOnMount: false,
            onToggle: (willOpen) => {
              if (!willOpen) {
                setTouched(true);
              }
            },
            renderToggle: ({ isOpen, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
              SummaryButton,
              {
                data,
                field,
                fieldLabel,
                summaryFields,
                validity,
                touched,
                disabled: fieldDefinition.readOnly === true,
                isOpen,
                onClick: onToggle
              }
            ),
            renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(DropdownContentWithValidation, { touched, children: /* @__PURE__ */ (0, import_jsx_runtime203.jsxs)("div", { ref: dialogRef, ...dialogProps, children: [
              /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
                DropdownHeader,
                {
                  title: fieldLabel,
                  onClose
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
                DataFormLayout,
                {
                  data,
                  form: form2,
                  onChange,
                  validity: formValidity,
                  children: (FieldLayout, childField, childFieldValidity, markWhenOptional) => /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(
                    FieldLayout,
                    {
                      data,
                      field: childField,
                      onChange,
                      hideLabelFromVision: (form2?.fields ?? []).length < 2,
                      markWhenOptional,
                      validity: childFieldValidity
                    },
                    childField.id
                  )
                }
              )
            ] }) })
          }
        )
      }
    );
  }
  var dropdown_default = PanelDropdown;

  // packages/dataviews/build-module/components/dataform-layouts/panel/index.mjs
  var import_jsx_runtime204 = __toESM(require_jsx_runtime(), 1);
  function FormPanelField({
    data,
    field,
    onChange,
    validity
  }) {
    const layout = field.layout;
    if (layout.openAs.type === "modal") {
      return /* @__PURE__ */ (0, import_jsx_runtime204.jsx)(
        modal_default,
        {
          data,
          field,
          onChange,
          validity
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime204.jsx)(
      dropdown_default,
      {
        data,
        field,
        onChange,
        validity
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-layouts/card/index.mjs
  var import_element125 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataform-layouts/validation-badge.mjs
  var import_i18n71 = __toESM(require_i18n(), 1);
  var import_jsx_runtime205 = __toESM(require_jsx_runtime(), 1);
  function countInvalidFields(validity) {
    if (!validity) {
      return 0;
    }
    let count = 0;
    const validityRules = Object.keys(validity).filter(
      (key) => key !== "children"
    );
    for (const key of validityRules) {
      const rule = validity[key];
      if (rule?.type === "invalid") {
        count++;
      }
    }
    if (validity.children) {
      for (const childValidity of Object.values(validity.children)) {
        count += countInvalidFields(childValidity);
      }
    }
    return count;
  }
  function ValidationBadge({
    validity
  }) {
    const invalidCount = countInvalidFields(validity);
    if (invalidCount === 0) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime205.jsx)(Badge, { intent: "high", children: (0, import_i18n71.sprintf)(
      /* translators: %d: Number of fields that need attention */
      (0, import_i18n71._n)(
        "%d field needs attention",
        "%d fields need attention",
        invalidCount
      ),
      invalidCount
    ) });
  }

  // packages/dataviews/build-module/components/dataform-layouts/card/index.mjs
  var import_jsx_runtime206 = __toESM(require_jsx_runtime(), 1);
  function isSummaryFieldVisible(summaryField, summaryConfig, isOpen) {
    if (!summaryConfig || Array.isArray(summaryConfig) && summaryConfig.length === 0) {
      return false;
    }
    const summaryConfigArray = Array.isArray(summaryConfig) ? summaryConfig : [summaryConfig];
    const fieldConfig = summaryConfigArray.find((config2) => {
      if (typeof config2 === "string") {
        return config2 === summaryField.id;
      }
      if (typeof config2 === "object" && "id" in config2) {
        return config2.id === summaryField.id;
      }
      return false;
    });
    if (!fieldConfig) {
      return false;
    }
    if (typeof fieldConfig === "string") {
      return true;
    }
    if (typeof fieldConfig === "object" && "visibility" in fieldConfig) {
      return fieldConfig.visibility === "always" || fieldConfig.visibility === "when-collapsed" && !isOpen;
    }
    return true;
  }
  function HeaderContent({
    data,
    fields: fields2,
    label,
    layout,
    isOpen,
    touched,
    validity
  }) {
    const summaryFields = getSummaryFields(layout.summary, fields2);
    const visibleSummaryFields = summaryFields.filter(
      (summaryField) => isSummaryFieldVisible(summaryField, layout.summary, isOpen)
    );
    const hasBadge = touched && layout.isCollapsible;
    const hasSummary = visibleSummaryFields.length > 0 && layout.withHeader;
    return /* @__PURE__ */ (0, import_jsx_runtime206.jsxs)(
      Stack,
      {
        align: "center",
        justify: "space-between",
        className: "dataforms-layouts-card__field-header-content",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(card_exports.Title, { children: label }),
          (hasBadge || hasSummary) && /* @__PURE__ */ (0, import_jsx_runtime206.jsxs)(collapsible_card_exports.HeaderDescription, { className: "dataforms-layouts-card__field-header-content-description", children: [
            hasBadge && /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(ValidationBadge, { validity }),
            hasSummary && /* @__PURE__ */ (0, import_jsx_runtime206.jsx)("div", { className: "dataforms-layouts-card__field-summary", children: visibleSummaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(
              summaryField.render,
              {
                item: data,
                field: summaryField
              },
              summaryField.id
            )) })
          ] })
        ]
      }
    );
  }
  function BodyContent({
    data,
    field,
    form: form2,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity,
    withHeader
  }) {
    if (field.children) {
      return /* @__PURE__ */ (0, import_jsx_runtime206.jsxs)(import_jsx_runtime206.Fragment, { children: [
        field.description && /* @__PURE__ */ (0, import_jsx_runtime206.jsx)("div", { className: "dataforms-layouts-card__field-description", children: field.description }),
        /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(
          DataFormLayout,
          {
            data,
            form: form2,
            onChange,
            validity: validity?.children
          }
        )
      ] });
    }
    const SingleFieldLayout = getFormFieldLayout("regular")?.component;
    if (!SingleFieldLayout) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(
      SingleFieldLayout,
      {
        data,
        field,
        onChange,
        hideLabelFromVision: hideLabelFromVision || withHeader,
        markWhenOptional,
        validity
      }
    );
  }
  function FormCardField({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { fields: fields2 } = (0, import_element125.useContext)(dataform_context_default);
    const layout = field.layout;
    const contentRef = (0, import_element125.useRef)(null);
    const form2 = (0, import_element125.useMemo)(
      () => ({
        layout: DEFAULT_LAYOUT,
        fields: field.children ?? []
      }),
      [field]
    );
    const { isOpened, isCollapsible } = layout;
    const [isOpen, setIsOpen] = (0, import_element125.useState)(isOpened);
    const [touched, setTouched] = (0, import_element125.useState)(false);
    (0, import_element125.useEffect)(() => {
      setIsOpen(isOpened);
    }, [isOpened]);
    const handleOpenChange = (0, import_element125.useCallback)((open) => {
      if (!open) {
        setTouched(true);
      }
      setIsOpen(open);
    }, []);
    const handleBlur = (0, import_element125.useCallback)(() => {
      setTouched(true);
    }, []);
    useReportValidity(
      contentRef,
      (isCollapsible ? isOpen : true) && touched
    );
    let label = field.label;
    let withHeader;
    if (field.children) {
      withHeader = !!label && layout.withHeader;
    } else {
      const fieldDefinition = fields2.find(
        (fieldDef) => fieldDef.id === field.id
      );
      if (!fieldDefinition || !fieldDefinition.Edit) {
        return null;
      }
      label = fieldDefinition.label;
      withHeader = !!label && layout.withHeader;
    }
    const bodyContent = /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(
      BodyContent,
      {
        data,
        field,
        form: form2,
        onChange,
        hideLabelFromVision,
        markWhenOptional,
        validity,
        withHeader
      }
    );
    const headerContent = /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(
      HeaderContent,
      {
        data,
        fields: fields2,
        label,
        layout,
        isOpen: isCollapsible ? !!isOpen : true,
        touched,
        validity
      }
    );
    if (withHeader && isCollapsible) {
      return /* @__PURE__ */ (0, import_jsx_runtime206.jsxs)(
        collapsible_card_exports.Root,
        {
          className: "dataforms-layouts-card__field",
          open: isOpen,
          onOpenChange: handleOpenChange,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(collapsible_card_exports.Header, { children: headerContent }),
            /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(
              collapsible_card_exports.Content,
              {
                ref: contentRef,
                onBlur: handleBlur,
                children: bodyContent
              }
            )
          ]
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime206.jsxs)(card_exports.Root, { className: "dataforms-layouts-card__field", children: [
      withHeader && /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(card_exports.Header, { children: headerContent }),
      /* @__PURE__ */ (0, import_jsx_runtime206.jsx)(card_exports.Content, { ref: contentRef, onBlur: handleBlur, children: bodyContent })
    ] });
  }

  // packages/dataviews/build-module/components/dataform-layouts/row/index.mjs
  var import_components71 = __toESM(require_components(), 1);
  var import_jsx_runtime207 = __toESM(require_jsx_runtime(), 1);
  function Header5({ title }) {
    return /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(
      Stack,
      {
        direction: "column",
        className: "dataforms-layouts-row__header",
        gap: "lg",
        children: /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(Stack, { direction: "row", align: "center", children: /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(import_components71.__experimentalHeading, { level: 2, size: 13, children: title }) })
      }
    );
  }
  var EMPTY_WRAPPER = ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(import_jsx_runtime207.Fragment, { children });
  function FormRowField({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const layout = field.layout;
    if (!!field.children) {
      const form2 = {
        layout: DEFAULT_LAYOUT,
        fields: field.children
      };
      return /* @__PURE__ */ (0, import_jsx_runtime207.jsxs)("div", { className: "dataforms-layouts-row__field", children: [
        !hideLabelFromVision && field.label && /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(Header5, { title: field.label }),
        /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(Stack, { direction: "row", align: layout.alignment, gap: "lg", children: /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(
          DataFormLayout,
          {
            data,
            form: form2,
            onChange,
            validity: validity?.children,
            as: EMPTY_WRAPPER,
            children: (FieldLayout, childField, childFieldValidity) => /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(
              "div",
              {
                className: "dataforms-layouts-row__field-control",
                style: layout.styles[childField.id],
                children: /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(
                  FieldLayout,
                  {
                    data,
                    field: childField,
                    onChange,
                    hideLabelFromVision,
                    markWhenOptional,
                    validity: childFieldValidity
                  }
                )
              },
              childField.id
            )
          }
        ) })
      ] });
    }
    const RegularLayout = getFormFieldLayout("regular")?.component;
    if (!RegularLayout) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(import_jsx_runtime207.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime207.jsx)("div", { className: "dataforms-layouts-row__field-control", children: /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(
      RegularLayout,
      {
        data,
        field,
        onChange,
        markWhenOptional,
        validity
      }
    ) }) });
  }

  // packages/dataviews/build-module/components/dataform-layouts/details/index.mjs
  var import_element126 = __toESM(require_element(), 1);
  var import_i18n72 = __toESM(require_i18n(), 1);
  var import_jsx_runtime208 = __toESM(require_jsx_runtime(), 1);
  function FormDetailsField({
    data,
    field,
    onChange,
    validity
  }) {
    const { fields: fields2 } = (0, import_element126.useContext)(dataform_context_default);
    const detailsRef = (0, import_element126.useRef)(null);
    const contentRef = (0, import_element126.useRef)(null);
    const [touched, setTouched] = (0, import_element126.useState)(false);
    const [isOpen, setIsOpen] = (0, import_element126.useState)(false);
    const form2 = (0, import_element126.useMemo)(
      () => ({
        layout: DEFAULT_LAYOUT,
        fields: field.children ?? []
      }),
      [field]
    );
    (0, import_element126.useEffect)(() => {
      const details = detailsRef.current;
      if (!details) {
        return;
      }
      const handleToggle = () => {
        const nowOpen = details.open;
        if (!nowOpen) {
          setTouched(true);
        }
        setIsOpen(nowOpen);
      };
      details.addEventListener("toggle", handleToggle);
      return () => {
        details.removeEventListener("toggle", handleToggle);
      };
    }, []);
    useReportValidity(contentRef, isOpen && touched);
    const handleBlur = (0, import_element126.useCallback)(() => {
      setTouched(true);
    }, []);
    if (!field.children) {
      return null;
    }
    const summaryFieldId = field.layout.summary ?? "";
    const summaryField = summaryFieldId ? fields2.find((fieldDef) => fieldDef.id === summaryFieldId) : void 0;
    let summaryContent;
    if (summaryField && summaryField.render) {
      summaryContent = /* @__PURE__ */ (0, import_jsx_runtime208.jsx)(summaryField.render, { item: data, field: summaryField });
    } else {
      summaryContent = field.label || (0, import_i18n72.__)("More details");
    }
    return /* @__PURE__ */ (0, import_jsx_runtime208.jsxs)(
      "details",
      {
        ref: detailsRef,
        className: "dataforms-layouts-details__details",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime208.jsx)("summary", { className: "dataforms-layouts-details__summary", children: /* @__PURE__ */ (0, import_jsx_runtime208.jsxs)(
            Stack,
            {
              direction: "row",
              align: "center",
              gap: "md",
              className: "dataforms-layouts-details__summary-content",
              children: [
                summaryContent,
                touched && /* @__PURE__ */ (0, import_jsx_runtime208.jsx)(ValidationBadge, { validity })
              ]
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime208.jsx)(
            "div",
            {
              ref: contentRef,
              className: "dataforms-layouts-details__content",
              onBlur: handleBlur,
              children: /* @__PURE__ */ (0, import_jsx_runtime208.jsx)(
                DataFormLayout,
                {
                  data,
                  form: form2,
                  onChange,
                  validity: validity?.children
                }
              )
            }
          )
        ]
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-layouts/index.mjs
  var import_jsx_runtime209 = __toESM(require_jsx_runtime(), 1);
  var FORM_FIELD_LAYOUTS = [
    {
      type: "regular",
      component: FormRegularField,
      wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
        Stack,
        {
          direction: "column",
          className: "dataforms-layouts__wrapper",
          gap: "lg",
          children
        }
      )
    },
    {
      type: "panel",
      component: FormPanelField,
      wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
        Stack,
        {
          direction: "column",
          className: "dataforms-layouts__wrapper",
          gap: "md",
          children
        }
      )
    },
    {
      type: "card",
      component: FormCardField,
      wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
        Stack,
        {
          direction: "column",
          className: "dataforms-layouts__wrapper",
          gap: "xl",
          children
        }
      )
    },
    {
      type: "row",
      component: FormRowField,
      wrapper: ({
        children,
        layout
      }) => /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
        Stack,
        {
          direction: "column",
          className: "dataforms-layouts__wrapper",
          gap: "lg",
          children: /* @__PURE__ */ (0, import_jsx_runtime209.jsx)("div", { className: "dataforms-layouts-row__field", children: /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
            Stack,
            {
              direction: "row",
              gap: "lg",
              align: layout.alignment,
              children
            }
          ) })
        }
      )
    },
    {
      type: "details",
      component: FormDetailsField
    }
  ];
  function getFormFieldLayout(type) {
    return FORM_FIELD_LAYOUTS.find((layout) => layout.type === type);
  }

  // packages/dataviews/build-module/components/dataform-layouts/data-form-layout.mjs
  var import_jsx_runtime210 = __toESM(require_jsx_runtime(), 1);
  var DEFAULT_WRAPPER = ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime210.jsx)(Stack, { direction: "column", className: "dataforms-layouts__wrapper", gap: "lg", children });
  function DataFormLayout({
    data,
    form: form2,
    onChange,
    validity,
    children,
    as
  }) {
    const { fields: fieldDefinitions } = (0, import_element127.useContext)(dataform_context_default);
    const markWhenOptional = (0, import_element127.useMemo)(() => {
      const requiredCount = fieldDefinitions.filter(
        (f2) => !!f2.isValid?.required
      ).length;
      const optionalCount = fieldDefinitions.length - requiredCount;
      return requiredCount > optionalCount;
    }, [fieldDefinitions]);
    function getFieldDefinition2(field) {
      return fieldDefinitions.find(
        (fieldDefinition) => fieldDefinition.id === field.id
      );
    }
    const Wrapper = as ?? getFormFieldLayout(form2.layout.type)?.wrapper ?? DEFAULT_WRAPPER;
    return /* @__PURE__ */ (0, import_jsx_runtime210.jsx)(Wrapper, { layout: form2.layout, children: form2.fields.map((formField) => {
      const FieldLayout = getFormFieldLayout(formField.layout.type)?.component;
      if (!FieldLayout) {
        return null;
      }
      const fieldDefinition = !formField.children ? getFieldDefinition2(formField) : void 0;
      if (fieldDefinition && fieldDefinition.isVisible && !fieldDefinition.isVisible(data)) {
        return null;
      }
      if (children) {
        return children(
          FieldLayout,
          formField,
          validity?.[formField.id],
          markWhenOptional
        );
      }
      return /* @__PURE__ */ (0, import_jsx_runtime210.jsx)(
        FieldLayout,
        {
          data,
          field: formField,
          onChange,
          markWhenOptional,
          validity: validity?.[formField.id]
        },
        formField.id
      );
    }) });
  }

  // packages/dataviews/build-module/dataform/index.mjs
  var import_jsx_runtime211 = __toESM(require_jsx_runtime(), 1);
  function DataForm({
    data,
    form: form2,
    fields: fields2,
    onChange,
    validity
  }) {
    const normalizedForm = (0, import_element128.useMemo)(() => normalize_form_default(form2), [form2]);
    const normalizedFields = (0, import_element128.useMemo)(
      () => normalizeFields(fields2),
      [fields2]
    );
    if (!form2.fields) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime211.jsx)(DataFormProvider, { fields: normalizedFields, children: /* @__PURE__ */ (0, import_jsx_runtime211.jsx)(
      DataFormLayout,
      {
        data,
        form: normalizedForm,
        onChange,
        validity
      }
    ) });
  }

  // packages/dataviews/build-module/utils/filter-sort-and-paginate.mjs
  var import_remove_accents2 = __toESM(require_remove_accents(), 1);
  var import_deprecated4 = __toESM(require_deprecated(), 1);
  function normalizeSearchInput2(input = "") {
    return (0, import_remove_accents2.default)(input.trim().toLowerCase());
  }
  var EMPTY_ARRAY9 = [];
  function filterSortAndPaginate(data, view, fields2) {
    if (!data) {
      return {
        data: EMPTY_ARRAY9,
        paginationInfo: { totalItems: 0, totalPages: 0 }
      };
    }
    const _fields = normalizeFields(fields2);
    let filteredData = [...data];
    if (view.search) {
      const normalizedSearch = normalizeSearchInput2(view.search);
      filteredData = filteredData.filter((item) => {
        return _fields.filter((field) => field.enableGlobalSearch).some((field) => {
          const fieldValue = field.getValue({ item });
          const values = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
          return values.some(
            (value) => normalizeSearchInput2(String(value)).includes(
              normalizedSearch
            )
          );
        });
      });
    }
    if (view.filters && view.filters?.length > 0) {
      view.filters.forEach((filter) => {
        const field = _fields.find(
          (_field) => _field.id === filter.field
        );
        if (field) {
          if (filter.operator === OPERATOR_IS_NOT_ALL) {
            (0, import_deprecated4.default)("The 'isNotAll' filter operator", {
              since: "7.0",
              alternative: "'isNone'"
            });
          }
          const handler = field.filter[filter.operator];
          if (handler) {
            filteredData = filteredData.filter(
              (item) => handler(item, field, filter.value)
            );
          }
        }
      });
    }
    const sortByField = view.sort?.field ? _fields.find((field) => {
      return field.enableSorting !== false && field.id === view.sort?.field;
    }) : null;
    const groupByField = view.groupBy?.field ? _fields.find((field) => {
      return field.enableSorting !== false && field.id === view.groupBy?.field;
    }) : null;
    if (sortByField || groupByField) {
      filteredData.sort((a2, b2) => {
        if (groupByField) {
          const groupCompare = groupByField.sort(
            a2,
            b2,
            view.groupBy?.direction ?? "asc"
          );
          if (groupCompare !== 0) {
            return groupCompare;
          }
        }
        if (sortByField) {
          return sortByField.sort(a2, b2, view.sort?.direction ?? "desc");
        }
        return 0;
      });
    }
    let totalItems = filteredData.length;
    let totalPages = 1;
    if (view.infiniteScrollEnabled && view.startPosition !== void 0 && view.perPage !== void 0) {
      const start2 = view.startPosition - 1;
      const end = Math.min(start2 + view.perPage, totalItems);
      filteredData = filteredData?.slice(start2, end);
    } else if (view.page !== void 0 && view.perPage !== void 0) {
      const start2 = (view.page - 1) * view.perPage;
      totalItems = filteredData?.length || 0;
      totalPages = Math.ceil(totalItems / view.perPage);
      filteredData = filteredData?.slice(start2, start2 + view.perPage);
    }
    return {
      data: filteredData,
      paginationInfo: {
        totalItems,
        totalPages
      }
    };
  }

  // packages/fields/build-module/lock-unlock.mjs
  var import_private_apis6 = __toESM(require_private_apis(), 1);
  var { lock: lock5, unlock: unlock5 } = (0, import_private_apis6.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
    "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
    "@wordpress/fields"
  );

  // packages/fields/build-module/components/media-edit/index.mjs
  var import_components72 = __toESM(require_components(), 1);
  var import_blob2 = __toESM(require_blob(), 1);
  var import_core_data23 = __toESM(require_core_data(), 1);
  var import_data40 = __toESM(require_data(), 1);
  var import_element130 = __toESM(require_element(), 1);
  var import_i18n73 = __toESM(require_i18n(), 1);
  var import_a11y3 = __toESM(require_a11y(), 1);
  var import_media_utils = __toESM(require_media_utils(), 1);
  var import_notices4 = __toESM(require_notices(), 1);

  // packages/fields/build-module/components/media-edit/use-moving-animation.mjs
  var import_element129 = __toESM(require_element(), 1);
  function getAbsolutePosition2(element) {
    return {
      top: element.offsetTop,
      left: element.offsetLeft
    };
  }
  function useMovingAnimation2(triggerAnimationOnChange) {
    const ref = (0, import_element129.useRef)(null);
    const previousRef = (0, import_element129.useRef)(void 0);
    if (ref.current) {
      previousRef.current = getAbsolutePosition2(ref.current);
    }
    (0, import_element129.useLayoutEffect)(() => {
      const previous = previousRef.current;
      if (!previous || !ref.current) {
        return;
      }
      if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
        return;
      }
      const controller = new Controller({
        x: 0,
        y: 0,
        config: { mass: 5, tension: 2e3, friction: 200 },
        onChange({ value }) {
          if (!ref.current) {
            return;
          }
          let { x: x22, y: y22 } = value;
          x22 = Math.round(x22);
          y22 = Math.round(y22);
          const finishedMoving = x22 === 0 && y22 === 0;
          ref.current.style.transform = finishedMoving ? "" : `translate3d(${x22}px,${y22}px,0)`;
        }
      });
      ref.current.style.transform = "";
      const destination = getAbsolutePosition2(ref.current);
      const x2 = Math.round(previous.left - destination.left);
      const y2 = Math.round(previous.top - destination.top);
      controller.start({ x: 0, y: 0, from: { x: x2, y: y2 } });
      return () => {
        controller.stop();
        controller.set({ x: 0, y: 0 });
      };
    }, [triggerAnimationOnChange]);
    return ref;
  }

  // packages/fields/build-module/components/media-edit/index.mjs
  var import_jsx_runtime212 = __toESM(require_jsx_runtime(), 1);
  var { MediaUploadModal } = unlock5(import_media_utils.privateApis);
  function AnimatedMediaItem({
    children,
    index: index2,
    className
  }) {
    const ref = useMovingAnimation2(index2);
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)("div", { ref, className, children });
  }
  function normalizeValue2(value) {
    if (Array.isArray(value)) {
      return value;
    }
    return value ? [value] : [];
  }
  function ConditionalMediaUpload({ render: render4, multiple, ...props }) {
    const [isModalOpen, setIsModalOpen] = (0, import_element130.useState)(false);
    if (window.__experimentalDataViewsMediaModal) {
      return /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(import_jsx_runtime212.Fragment, { children: [
        render4 && render4({ open: () => setIsModalOpen(true) }),
        isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
          MediaUploadModal,
          {
            ...props,
            multiple,
            isOpen: isModalOpen,
            onClose: () => {
              setIsModalOpen(false);
              props.onClose?.();
            },
            onSelect: (media) => {
              setIsModalOpen(false);
              props.onSelect?.(media);
            }
          }
        )
      ] });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
      import_media_utils.MediaUpload,
      {
        ...props,
        render: render4,
        multiple: multiple ? "add" : void 0
      }
    );
  }
  function MediaPickerButton({
    open,
    children,
    label,
    showTooltip = false,
    onFilesDrop,
    attachment,
    isUploading = false
  }) {
    const isBlob = attachment && (0, import_blob2.isBlobURL)(attachment.source_url);
    const mediaPickerButton = /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(
      "div",
      {
        className: clsx_default("fields__media-edit-picker-button", {
          "has-attachment": attachment
        }),
        role: "button",
        tabIndex: 0,
        onClick: () => {
          if (!isUploading) {
            open();
          }
        },
        onKeyDown: (event) => {
          if (isUploading) {
            return;
          }
          if (event.key === "Enter" || event.key === " ") {
            event.preventDefault();
            open();
          }
        },
        "aria-label": label,
        "aria-disabled": isUploading,
        children: [
          children,
          isBlob && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)("span", { className: "fields__media-edit-picker-button-spinner", children: /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(import_components72.Spinner, {}) }),
          !isUploading && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
            import_components72.DropZone,
            {
              onFilesDrop: (files) => onFilesDrop(files, attachment?.id)
            }
          )
        ]
      }
    );
    if (!showTooltip) {
      return mediaPickerButton;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(tooltip_exports.Root, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(tooltip_exports.Trigger, { render: mediaPickerButton }),
      /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(tooltip_exports.Popup, { children: label })
    ] });
  }
  var archiveMimeTypes = [
    "application/zip",
    "application/x-zip-compressed",
    "application/x-rar-compressed",
    "application/x-7z-compressed",
    "application/x-tar",
    "application/x-gzip"
  ];
  function MediaTitle({ attachment }) {
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(import_components72.__experimentalTruncate, { className: "fields__media-edit-filename", children: attachment.title.rendered });
  }
  function MediaEditPlaceholder(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(MediaPickerButton, { ...props, children: /* @__PURE__ */ (0, import_jsx_runtime212.jsx)("span", { className: "fields__media-edit-placeholder", children: props.label }) });
  }
  function MoveButtons({
    itemId,
    index: index2,
    totalItems,
    isUploading,
    moveItem,
    orientation = "vertical"
  }) {
    const isHorizontal = orientation === "horizontal";
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(import_jsx_runtime212.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
        import_components72.Button,
        {
          __next40pxDefaultSize: true,
          icon: isHorizontal ? chevron_left_default : chevron_up_default,
          label: isHorizontal ? (0, import_i18n73.__)("Move left") : (0, import_i18n73.__)("Move up"),
          size: "small",
          disabled: isUploading || index2 === 0,
          accessibleWhenDisabled: true,
          tooltipPosition: "top",
          onClick: (event) => {
            event.stopPropagation();
            moveItem(itemId, "up");
          }
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
        import_components72.Button,
        {
          __next40pxDefaultSize: true,
          icon: isHorizontal ? chevron_right_default : chevron_down_default,
          label: isHorizontal ? (0, import_i18n73.__)("Move right") : (0, import_i18n73.__)("Move down"),
          size: "small",
          disabled: isUploading || index2 === totalItems - 1,
          accessibleWhenDisabled: true,
          tooltipPosition: "top",
          onClick: (event) => {
            event.stopPropagation();
            moveItem(itemId, "down");
          }
        }
      )
    ] });
  }
  function MediaPreview({ attachment }) {
    const url = attachment.source_url;
    const mimeType = attachment.mime_type || "";
    if (mimeType.startsWith("image")) {
      return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
        "img",
        {
          className: "fields__media-edit-thumbnail",
          alt: attachment.alt_text || "",
          src: url
        }
      );
    } else if (mimeType.startsWith("audio")) {
      return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(import_components72.Icon, { icon: audio_default });
    } else if (mimeType.startsWith("video")) {
      return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(import_components72.Icon, { icon: video_default });
    } else if (archiveMimeTypes.includes(mimeType)) {
      return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(import_components72.Icon, { icon: archive_default });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(import_components72.Icon, { icon: file_default });
  }
  function ExpandedMediaEditAttachments({
    allItems,
    addButtonLabel,
    multiple,
    removeItem,
    moveItem,
    open,
    onFilesDrop,
    isUploading,
    setTargetItemId
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(
      "div",
      {
        className: clsx_default("fields__media-edit-expanded", {
          "is-multiple": multiple,
          "is-single": !multiple,
          "is-empty": !allItems?.length
        }),
        children: [
          allItems?.map((attachment, index2) => {
            const hasPreviewImage = attachment.mime_type?.startsWith("image");
            const isBlob = (0, import_blob2.isBlobURL)(attachment.source_url);
            const attachmentNumericId = attachment.id;
            return /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(
              AnimatedMediaItem,
              {
                index: index2,
                className: clsx_default("fields__media-edit-expanded-item", {
                  "has-preview-image": hasPreviewImage
                }),
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                    MediaPickerButton,
                    {
                      open: () => {
                        setTargetItemId(attachmentNumericId);
                        open();
                      },
                      label: !isBlob ? (0, import_i18n73.sprintf)(
                        /* translators: %s: The title of the media item. */
                        (0, import_i18n73.__)("Replace %s"),
                        attachment.title.rendered
                      ) : (0, import_i18n73.__)("Replace"),
                      showTooltip: true,
                      onFilesDrop,
                      attachment,
                      isUploading,
                      children: /* @__PURE__ */ (0, import_jsx_runtime212.jsx)("div", { className: "fields__media-edit-expanded-preview", children: /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                        import_components72.__experimentalVStack,
                        {
                          spacing: 0,
                          alignment: "center",
                          justify: "center",
                          className: "fields__media-edit-expanded-preview-stack",
                          children: (!isBlob || hasPreviewImage) && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                            MediaPreview,
                            {
                              attachment
                            }
                          )
                        }
                      ) })
                    }
                  ),
                  !isBlob && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)("div", { className: "fields__media-edit-expanded-overlay", children: /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(
                    import_components72.__experimentalHStack,
                    {
                      className: "fields__media-edit-expanded-actions",
                      spacing: 0,
                      alignment: "flex-end",
                      expanded: false,
                      children: [
                        multiple && allItems.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                          MoveButtons,
                          {
                            itemId: attachmentNumericId,
                            index: index2,
                            totalItems: allItems.length,
                            isUploading,
                            moveItem,
                            orientation: "horizontal"
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                          import_components72.Button,
                          {
                            __next40pxDefaultSize: true,
                            icon: close_small_default,
                            label: (0, import_i18n73.__)("Remove"),
                            size: "small",
                            disabled: isUploading,
                            accessibleWhenDisabled: true,
                            tooltipPosition: "top",
                            onClick: (event) => {
                              event.stopPropagation();
                              removeItem(attachmentNumericId);
                            }
                          }
                        )
                      ]
                    }
                  ) })
                ]
              },
              attachment.id
            );
          }),
          (multiple || !allItems?.length) && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
            MediaEditPlaceholder,
            {
              open: () => {
                setTargetItemId(void 0);
                open();
              },
              label: addButtonLabel,
              onFilesDrop,
              isUploading
            }
          )
        ]
      }
    );
  }
  function CompactMediaEditAttachments({
    allItems,
    addButtonLabel,
    multiple,
    removeItem,
    moveItem,
    open,
    onFilesDrop,
    isUploading,
    setTargetItemId
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(import_jsx_runtime212.Fragment, { children: [
      !!allItems?.length && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
        "div",
        {
          className: clsx_default("fields__media-edit-compact-group", {
            "is-single": allItems.length === 1
          }),
          children: /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(import_components72.__experimentalVStack, { spacing: 0, children: allItems.map((attachment, index2) => {
            const isBlob = (0, import_blob2.isBlobURL)(attachment.source_url);
            const showMoveButtons = multiple && allItems.length > 1;
            const attachmentNumericId = attachment.id;
            return /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(
              AnimatedMediaItem,
              {
                index: index2,
                className: "fields__media-edit-compact",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                    MediaPickerButton,
                    {
                      open: () => {
                        setTargetItemId(
                          attachmentNumericId
                        );
                        open();
                      },
                      label: (0, import_i18n73.__)("Replace"),
                      showTooltip: true,
                      onFilesDrop,
                      attachment,
                      isUploading,
                      children: /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(import_jsx_runtime212.Fragment, { children: [
                        /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                          MediaPreview,
                          {
                            attachment
                          }
                        ),
                        !isBlob && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                          MediaTitle,
                          {
                            attachment
                          }
                        )
                      ] })
                    }
                  ),
                  !isBlob && /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(
                    import_components72.__experimentalHStack,
                    {
                      className: "fields__media-edit-compact-movers",
                      spacing: 0,
                      alignment: "flex-end",
                      expanded: false,
                      children: [
                        showMoveButtons && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                          MoveButtons,
                          {
                            itemId: attachmentNumericId,
                            index: index2,
                            totalItems: allItems.length,
                            isUploading,
                            moveItem,
                            orientation: "vertical"
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                          import_components72.Button,
                          {
                            __next40pxDefaultSize: true,
                            icon: close_small_default,
                            label: (0, import_i18n73.__)("Remove"),
                            size: "small",
                            disabled: isUploading,
                            accessibleWhenDisabled: true,
                            tooltipPosition: "top",
                            onClick: (event) => {
                              event.stopPropagation();
                              removeItem(
                                attachmentNumericId
                              );
                            }
                          }
                        )
                      ]
                    }
                  )
                ]
              },
              attachment.id
            );
          }) })
        }
      ),
      (multiple || !allItems?.length) && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
        MediaEditPlaceholder,
        {
          open: () => {
            setTargetItemId(void 0);
            open();
          },
          label: addButtonLabel,
          onFilesDrop,
          isUploading
        }
      )
    ] });
  }
  function MediaEdit({
    data,
    field,
    onChange,
    hideLabelFromVision,
    allowedTypes = ["image"],
    multiple,
    isExpanded,
    validity
  }) {
    const value = field.getValue({ item: data });
    const [isTouched, setIsTouched] = (0, import_element130.useState)(false);
    const validityTargetRef = (0, import_element130.useRef)(null);
    const [customValidity, setCustomValidity] = (0, import_element130.useState)(void 0);
    (0, import_element130.useEffect)(() => {
      const validityTarget = validityTargetRef.current;
      const handler = () => {
        setIsTouched(true);
      };
      validityTarget?.addEventListener("invalid", handler);
      return () => validityTarget?.removeEventListener("invalid", handler);
    }, []);
    const attachments = (0, import_data40.useSelect)(
      (select4) => {
        if (!value) {
          return null;
        }
        const normalizedValue = normalizeValue2(value);
        const sortedIds = normalizedValue.toSorted((a2, b2) => a2 - b2);
        const { getEntityRecords } = select4(import_core_data23.store);
        return getEntityRecords("postType", "attachment", {
          include: sortedIds
        });
      },
      [value]
    );
    const stableAttachmentsRef = (0, import_element130.useRef)(
      null
    );
    if (attachments !== null) {
      stableAttachmentsRef.current = attachments;
    }
    let stableAttachments = attachments;
    if (attachments === null && stableAttachmentsRef.current && value) {
      const stableIds = new Set(
        stableAttachmentsRef.current.map((a2) => a2.id)
      );
      if (normalizeValue2(value).every((id) => stableIds.has(id))) {
        stableAttachments = stableAttachmentsRef.current;
      }
    }
    const orderedAttachments = (0, import_element130.useMemo)(() => {
      if (!stableAttachments) {
        return null;
      }
      const normalizedValue = normalizeValue2(value);
      const attachmentMap = new Map(
        stableAttachments.map((a2) => [a2.id, a2])
      );
      return normalizedValue.map((id) => attachmentMap.get(id)).filter((a2) => a2 !== void 0);
    }, [stableAttachments, value]);
    const { createErrorNotice } = (0, import_data40.useDispatch)(import_notices4.store);
    const { receiveEntityRecords } = (0, import_data40.useDispatch)(import_core_data23.store);
    const [targetItemId, setTargetItemId] = (0, import_element130.useState)();
    const openModalRef = (0, import_element130.useRef)(void 0);
    const [pendingOpen, setPendingOpen] = (0, import_element130.useState)(false);
    const [blobs, setBlobs] = (0, import_element130.useState)([]);
    (0, import_element130.useEffect)(() => {
      if (pendingOpen) {
        setPendingOpen(false);
        openModalRef.current?.();
      }
    }, [pendingOpen]);
    const onChangeControl = (0, import_element130.useCallback)(
      (newValue) => onChange(field.setValue({ item: data, value: newValue })),
      [data, field, onChange]
    );
    const removeItem = (0, import_element130.useCallback)(
      (itemId) => {
        const currentIds = normalizeValue2(value);
        const newIds = currentIds.filter((id) => id !== itemId);
        setIsTouched(true);
        onChangeControl(newIds.length ? newIds : void 0);
      },
      [value, onChangeControl]
    );
    const moveItem = (0, import_element130.useCallback)(
      (itemId, direction) => {
        if (!orderedAttachments) {
          return;
        }
        const currentIds = orderedAttachments.map((a2) => a2.id);
        const index2 = currentIds.indexOf(itemId);
        const newIndex = direction === "up" ? index2 - 1 : index2 + 1;
        [currentIds[index2], currentIds[newIndex]] = [
          currentIds[newIndex],
          currentIds[index2]
        ];
        onChangeControl(currentIds);
      },
      [orderedAttachments, onChangeControl]
    );
    const onFilesDrop = (0, import_element130.useCallback)(
      (files, _targetItemId) => {
        setTargetItemId(_targetItemId);
        (0, import_media_utils.uploadMedia)({
          allowedTypes: allowedTypes?.length ? allowedTypes : void 0,
          filesList: files,
          onFileChange(uploadedMedia) {
            const blobUrls = uploadedMedia.filter((item) => (0, import_blob2.isBlobURL)(item.url)).map((item) => item.url);
            setBlobs(blobUrls);
            if (!!blobUrls.length) {
              return;
            }
            receiveEntityRecords(
              "postType",
              "attachment",
              [],
              void 0,
              true
            );
            const uploadedIds = uploadedMedia.map(
              (item) => item.id
            );
            if (!multiple) {
              onChangeControl(uploadedIds[0]);
              setTargetItemId(void 0);
              return;
            }
            const currentValue = normalizeValue2(value);
            if (_targetItemId === void 0) {
              onChangeControl([...currentValue, ...uploadedIds]);
            } else {
              const newValue = [...currentValue];
              newValue.splice(
                currentValue.indexOf(_targetItemId),
                1,
                ...uploadedIds
              );
              onChangeControl(newValue);
            }
            setTargetItemId(void 0);
          },
          onError(error2) {
            setTargetItemId(void 0);
            setBlobs([]);
            createErrorNotice(error2.message, { type: "snackbar" });
          },
          multiple: !!multiple
        });
      },
      [
        allowedTypes,
        value,
        multiple,
        createErrorNotice,
        onChangeControl,
        receiveEntityRecords
      ]
    );
    const addButtonLabel = field.placeholder || (multiple ? (0, import_i18n73.__)("Choose files") : (0, import_i18n73.__)("Choose file"));
    const allItems = (0, import_element130.useMemo)(() => {
      if (!blobs.length) {
        return orderedAttachments;
      }
      const items = [
        ...orderedAttachments || []
      ];
      const blobItems = blobs.map((url) => ({
        id: url,
        source_url: url,
        mime_type: (0, import_blob2.getBlobTypeByURL)(url)
      }));
      if (targetItemId !== void 0) {
        const targetIndex = items.findIndex(
          (a2) => a2.id === targetItemId
        );
        items.splice(targetIndex, 1, ...blobItems);
      } else {
        items.push(...blobItems);
      }
      return items;
    }, [orderedAttachments, targetItemId, blobs]);
    (0, import_element130.useEffect)(() => {
      if (!isTouched) {
        return;
      }
      const input = validityTargetRef.current;
      if (!input) {
        return;
      }
      if (validity) {
        const customValidityResult = validity?.custom;
        setCustomValidity(customValidityResult);
        if (customValidityResult?.type === "invalid") {
          input.setCustomValidity(
            customValidityResult.message || (0, import_i18n73.__)("Invalid")
          );
        } else {
          input.setCustomValidity("");
        }
      } else {
        input.setCustomValidity("");
        setCustomValidity(void 0);
      }
    }, [isTouched, field.isValid, validity]);
    (0, import_element130.useEffect)(() => {
      if (isTouched && customValidity?.message) {
        (0, import_a11y3.speak)(customValidity.message);
      }
    }, [isTouched, customValidity?.message]);
    const onBlur = (0, import_element130.useCallback)(
      (event) => {
        if (isTouched) {
          return;
        }
        if (!event.relatedTarget || !event.currentTarget.contains(event.relatedTarget)) {
          setIsTouched(true);
        }
      },
      [isTouched]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)("div", { onBlur, children: [
      /* @__PURE__ */ (0, import_jsx_runtime212.jsx)("fieldset", { className: "fields__media-edit", "data-field-id": field.id, children: /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
        ConditionalMediaUpload,
        {
          onSelect: (selectedMedia) => {
            if (!multiple) {
              onChangeControl(selectedMedia.id);
              setTargetItemId(void 0);
              return;
            }
            const newIds = Array.isArray(selectedMedia) ? selectedMedia.map((m2) => m2.id) : [selectedMedia.id];
            const currentValue = normalizeValue2(value);
            if (!currentValue.length) {
              onChangeControl(newIds);
            } else if (targetItemId === void 0) {
              const existingItems = currentValue.filter(
                (id) => newIds.includes(id)
              );
              const newItems = newIds.filter(
                (id) => !currentValue.includes(id)
              );
              onChangeControl([
                ...existingItems,
                ...newItems
              ]);
            } else if (selectedMedia.id !== targetItemId) {
              const filtered = currentValue.filter(
                (id) => id !== selectedMedia.id
              );
              onChangeControl(
                filtered.map(
                  (id) => id === targetItemId ? selectedMedia.id : id
                )
              );
            }
            setTargetItemId(void 0);
          },
          onClose: () => setTargetItemId(void 0),
          allowedTypes,
          value: targetItemId !== void 0 ? targetItemId : value,
          multiple: multiple && targetItemId === void 0,
          title: field.label,
          render: ({ open }) => {
            openModalRef.current = open;
            const AttachmentsComponent = isExpanded ? ExpandedMediaEditAttachments : CompactMediaEditAttachments;
            return /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(import_components72.__experimentalVStack, { spacing: 2, children: [
              field.label && (hideLabelFromVision ? /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime212.jsx)("legend", {}), children: field.label }) : /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                import_components72.BaseControl.VisualLabel,
                {
                  as: "legend",
                  style: { marginBottom: 0 },
                  children: field.label
                }
              )),
              /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                AttachmentsComponent,
                {
                  allItems,
                  addButtonLabel,
                  multiple,
                  removeItem,
                  moveItem,
                  open: () => setPendingOpen(true),
                  onFilesDrop,
                  isUploading: !!blobs.length,
                  setTargetItemId
                }
              ),
              field.description && /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                import_components72.__experimentalText,
                {
                  variant: "muted",
                  className: "fields__media-edit-description",
                  children: field.description
                }
              )
            ] });
          }
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(VisuallyHidden, { children: /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
        "input",
        {
          type: "text",
          ref: validityTargetRef,
          value: value ?? "",
          tabIndex: -1,
          "aria-hidden": "true",
          onChange: () => {
          }
        }
      ) }),
      customValidity && /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(
        "p",
        {
          className: clsx_default(
            "components-validated-control__indicator",
            {
              "is-invalid": customValidity.type === "invalid",
              "is-valid": customValidity.type === "valid"
            }
          ),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
              import_components72.Icon,
              {
                className: "components-validated-control__indicator-icon",
                icon: error_default,
                size: 16,
                fill: "currentColor"
              }
            ),
            customValidity.message
          ]
        }
      )
    ] });
  }

  // node_modules/tslib/tslib.es6.mjs
  var __assign = function() {
    __assign = Object.assign || function __assign2(t3) {
      for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
        s2 = arguments[i2];
        for (var p3 in s2) if (Object.prototype.hasOwnProperty.call(s2, p3)) t3[p3] = s2[p3];
      }
      return t3;
    };
    return __assign.apply(this, arguments);
  };

  // node_modules/lower-case/dist.es2015/index.js
  function lowerCase(str) {
    return str.toLowerCase();
  }

  // node_modules/no-case/dist.es2015/index.js
  var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
  var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
  function noCase(input, options) {
    if (options === void 0) {
      options = {};
    }
    var _a = options.splitRegexp, splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d;
    var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
    var start2 = 0;
    var end = result.length;
    while (result.charAt(start2) === "\0")
      start2++;
    while (result.charAt(end - 1) === "\0")
      end--;
    return result.slice(start2, end).split("\0").map(transform).join(delimiter);
  }
  function replace(input, re, value) {
    if (re instanceof RegExp)
      return input.replace(re, value);
    return re.reduce(function(input2, re2) {
      return input2.replace(re2, value);
    }, input);
  }

  // node_modules/dot-case/dist.es2015/index.js
  function dotCase(input, options) {
    if (options === void 0) {
      options = {};
    }
    return noCase(input, __assign({ delimiter: "." }, options));
  }

  // node_modules/param-case/dist.es2015/index.js
  function paramCase(input, options) {
    if (options === void 0) {
      options = {};
    }
    return dotCase(input, __assign({ delimiter: "-" }, options));
  }

  // packages/edit-site/build-module/components/sidebar-identity/index.mjs
  var import_jsx_runtime213 = __toESM(require_jsx_runtime(), 1);
  var fields = [
    {
      id: "title",
      type: "text",
      label: (0, import_i18n74.__)("Site Title"),
      description: (0, import_i18n74.__)(
        "Displays in your site's layout via the Site Title block."
      )
    },
    {
      id: "description",
      type: "text",
      label: (0, import_i18n74.__)("Site Tagline"),
      description: (0, import_i18n74.__)(
        "In a few words, explain what this site is about. Displays in your site's layout via the Site Tagline block."
      )
    },
    {
      id: "site_logo",
      type: "media",
      label: (0, import_i18n74.__)("Site Logo"),
      description: (0, import_i18n74.__)(
        "Displays in your site's layout via the Site Logo block."
      ),
      placeholder: (0, import_i18n74.__)("Choose logo"),
      Edit: MediaEdit,
      setValue: ({ value }) => ({
        site_logo: value ?? 0
      })
    },
    {
      id: "site_icon",
      type: "media",
      label: (0, import_i18n74.__)("Site Icon"),
      description: (0, import_i18n74.__)(
        "Shown in browser tabs, bookmarks, and mobile apps. It should be square and at least 512 by 512 pixels."
      ),
      placeholder: (0, import_i18n74.__)("Choose icon"),
      Edit: MediaEdit,
      setValue: ({ value }) => ({
        site_icon: value ?? 0
      })
    }
  ];
  var form = {
    layout: {
      type: "regular",
      labelPosition: "top"
    },
    fields: ["title", "description", "site_logo", "site_icon"]
  };
  function SidebarIdentity() {
    const data = (0, import_data41.useSelect)(
      (select4) => select4(import_core_data24.store).getEditedEntityRecord("root", "site"),
      []
    );
    const { editEntityRecord } = (0, import_data41.useDispatch)(import_core_data24.store);
    const onChange = (edits) => {
      editEntityRecord("root", "site", void 0, edits);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime213.jsx)(
      page_default2,
      {
        title: (0, import_i18n74._x)("Identity", "site identity"),
        headingLevel: 2,
        hasPadding: true,
        children: /* @__PURE__ */ (0, import_jsx_runtime213.jsx)(
          DataForm,
          {
            data,
            fields,
            form,
            onChange
          }
        )
      }
    );
  }

  // packages/edit-site/build-module/components/site-editor-routes/identity.mjs
  var import_jsx_runtime214 = __toESM(require_jsx_runtime(), 1);
  var identityRoute = {
    name: "identity",
    path: "/identity",
    areas: {
      sidebar: /* @__PURE__ */ (0, import_jsx_runtime214.jsx)(SidebarNavigationScreenIdentity, {}),
      content: /* @__PURE__ */ (0, import_jsx_runtime214.jsx)(SidebarIdentity, {}),
      preview: /* @__PURE__ */ (0, import_jsx_runtime214.jsx)(EditSiteEditor, {}),
      mobileContent: /* @__PURE__ */ (0, import_jsx_runtime214.jsx)(SidebarIdentity, {})
    },
    widths: {
      content: 380
    }
  };

  // packages/edit-site/build-module/components/site-editor-routes/styles.mjs
  var import_router20 = __toESM(require_router(), 1);
  var import_editor24 = __toESM(require_editor(), 1);
  var import_url14 = __toESM(require_url(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-global-styles/index.mjs
  var import_i18n122 = __toESM(require_i18n(), 1);
  var import_data54 = __toESM(require_data(), 1);
  var import_element163 = __toESM(require_element(), 1);
  var import_preferences10 = __toESM(require_preferences(), 1);
  var import_editor22 = __toESM(require_editor(), 1);
  var import_router18 = __toESM(require_router(), 1);
  var import_url12 = __toESM(require_url(), 1);

  // packages/global-styles-ui/build-module/global-styles-ui.mjs
  var import_components130 = __toESM(require_components(), 1);
  var import_blocks8 = __toESM(require_blocks(), 1);
  var import_data53 = __toESM(require_data(), 1);
  var import_block_editor19 = __toESM(require_block_editor(), 1);
  var import_element162 = __toESM(require_element(), 1);
  var import_compose27 = __toESM(require_compose(), 1);

  // packages/global-styles-ui/build-module/provider.mjs
  var import_element132 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/context.mjs
  var import_element131 = __toESM(require_element(), 1);
  var GlobalStylesContext = (0, import_element131.createContext)({
    user: { styles: {}, settings: {} },
    base: { styles: {}, settings: {} },
    merged: { styles: {}, settings: {} },
    onChange: () => {
    },
    fontLibraryEnabled: false
  });

  // packages/global-styles-ui/build-module/provider.mjs
  var import_jsx_runtime215 = __toESM(require_jsx_runtime(), 1);
  function GlobalStylesProvider({
    children,
    value,
    baseValue,
    onChange,
    fontLibraryEnabled
  }) {
    const merged = (0, import_element132.useMemo)(() => {
      return mergeGlobalStyles(baseValue, value);
    }, [baseValue, value]);
    const contextValue = (0, import_element132.useMemo)(
      () => ({
        user: value,
        base: baseValue,
        merged,
        onChange,
        fontLibraryEnabled
      }),
      [value, baseValue, merged, onChange, fontLibraryEnabled]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(GlobalStylesContext.Provider, { value: contextValue, children });
  }

  // packages/global-styles-ui/build-module/screen-root.mjs
  var import_components79 = __toESM(require_components(), 1);
  var import_i18n79 = __toESM(require_i18n(), 1);
  var import_data43 = __toESM(require_data(), 1);
  var import_core_data26 = __toESM(require_core_data(), 1);

  // packages/global-styles-ui/build-module/icon-with-current-color.mjs
  var import_jsx_runtime216 = __toESM(require_jsx_runtime(), 1);
  function IconWithCurrentColor({
    className,
    ...props
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime216.jsx)(
      icon_default,
      {
        className: clsx_default(
          className,
          "global-styles-ui-icon-with-current-color"
        ),
        ...props
      }
    );
  }

  // packages/global-styles-ui/build-module/navigation-button.mjs
  var import_components73 = __toESM(require_components(), 1);
  var import_jsx_runtime217 = __toESM(require_jsx_runtime(), 1);
  function GenericNavigationButton({
    icon,
    children,
    ...props
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime217.jsxs)(import_components73.__experimentalItem, { ...props, children: [
      icon && /* @__PURE__ */ (0, import_jsx_runtime217.jsxs)(import_components73.__experimentalHStack, { justify: "flex-start", children: [
        /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(IconWithCurrentColor, { icon, size: 24 }),
        /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(import_components73.FlexItem, { children })
      ] }),
      !icon && children
    ] });
  }
  function NavigationButtonAsItem(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(import_components73.Navigator.Button, { as: GenericNavigationButton, ...props });
  }

  // packages/global-styles-ui/build-module/root-menu.mjs
  var import_components74 = __toESM(require_components(), 1);
  var import_i18n77 = __toESM(require_i18n(), 1);
  var import_block_editor6 = __toESM(require_block_editor(), 1);

  // node_modules/colord/plugins/a11y.mjs
  var o2 = function(o3) {
    var t3 = o3 / 255;
    return t3 < 0.04045 ? t3 / 12.92 : Math.pow((t3 + 0.055) / 1.055, 2.4);
  };
  var t2 = function(t3) {
    return 0.2126 * o2(t3.r) + 0.7152 * o2(t3.g) + 0.0722 * o2(t3.b);
  };
  function a11y_default(o3) {
    o3.prototype.luminance = function() {
      return o4 = t2(this.rgba), void 0 === (r3 = 2) && (r3 = 0), void 0 === n2 && (n2 = Math.pow(10, r3)), Math.round(n2 * o4) / n2 + 0;
      var o4, r3, n2;
    }, o3.prototype.contrast = function(r3) {
      void 0 === r3 && (r3 = "#FFF");
      var n2, a2, i2, e2, v2, u2, d2, c6 = r3 instanceof o3 ? r3 : new o3(r3);
      return e2 = this.rgba, v2 = c6.toRgb(), u2 = t2(e2), d2 = t2(v2), n2 = u2 > d2 ? (u2 + 0.05) / (d2 + 0.05) : (d2 + 0.05) / (u2 + 0.05), void 0 === (a2 = 2) && (a2 = 0), void 0 === i2 && (i2 = Math.pow(10, a2)), Math.floor(i2 * n2) / i2 + 0;
    }, o3.prototype.isReadable = function(o4, t3) {
      return void 0 === o4 && (o4 = "#FFF"), void 0 === t3 && (t3 = {}), this.contrast(o4) >= (e2 = void 0 === (i2 = (r3 = t3).size) ? "normal" : i2, "AAA" === (a2 = void 0 === (n2 = r3.level) ? "AA" : n2) && "normal" === e2 ? 7 : "AA" === a2 && "large" === e2 ? 3 : 4.5);
      var r3, n2, a2, i2, e2;
    };
  }

  // packages/global-styles-ui/build-module/hooks.mjs
  var import_element133 = __toESM(require_element(), 1);
  var import_data42 = __toESM(require_data(), 1);
  var import_core_data25 = __toESM(require_core_data(), 1);
  var import_i18n76 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/utils.mjs
  var import_i18n75 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/lock-unlock.mjs
  var import_private_apis7 = __toESM(require_private_apis(), 1);
  var { lock: lock6, unlock: unlock6 } = (0, import_private_apis7.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
    "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
    "@wordpress/global-styles-ui"
  );

  // packages/global-styles-ui/build-module/utils.mjs
  var { getViewportBreakpoints: getViewportBreakpoints2 } = unlock6(privateApis2);
  var VALID_ELEMENT_STATES = {
    link: [
      { value: ":link", label: (0, import_i18n75.__)("Link") },
      { value: ":any-link", label: (0, import_i18n75.__)("Any Link") },
      { value: ":visited", label: (0, import_i18n75.__)("Visited") },
      { value: ":hover", label: (0, import_i18n75.__)("Hover") },
      { value: ":focus", label: (0, import_i18n75.__)("Focus") },
      { value: ":focus-visible", label: (0, import_i18n75.__)("Focus-visible") },
      { value: ":active", label: (0, import_i18n75.__)("Active") }
    ],
    button: [
      { value: ":link", label: (0, import_i18n75.__)("Link") },
      { value: ":any-link", label: (0, import_i18n75.__)("Any Link") },
      { value: ":visited", label: (0, import_i18n75.__)("Visited") },
      { value: ":hover", label: (0, import_i18n75.__)("Hover") },
      { value: ":focus", label: (0, import_i18n75.__)("Focus") },
      { value: ":focus-visible", label: (0, import_i18n75.__)("Focus-visible") },
      { value: ":active", label: (0, import_i18n75.__)("Active") }
    ]
  };
  var VALID_BLOCK_STATES = {
    "core/button": [
      { value: ":hover", label: (0, import_i18n75.__)("Hover") },
      { value: ":focus", label: (0, import_i18n75.__)("Focus") },
      { value: ":focus-visible", label: (0, import_i18n75.__)("Focus-visible") },
      { value: ":active", label: (0, import_i18n75.__)("Active") }
    ]
  };
  var RESPONSIVE_STATES = [
    { value: "@tablet", label: (0, import_i18n75.__)("Tablet") },
    { value: "@mobile", label: (0, import_i18n75.__)("Mobile") }
  ];
  function removePropertiesFromObject(object, properties) {
    if (!properties?.length) {
      return object;
    }
    if (typeof object !== "object" || !object || !Object.keys(object).length) {
      return object;
    }
    for (const key in object) {
      if (properties.includes(key)) {
        delete object[key];
      } else if (typeof object[key] === "object") {
        removePropertiesFromObject(object[key], properties);
      }
    }
    return object;
  }
  var filterObjectByProperties = (object, properties) => {
    if (!object || !properties?.length) {
      return {};
    }
    const newObject = {};
    Object.keys(object).forEach((key) => {
      if (properties.includes(key)) {
        newObject[key] = object[key];
      } else if (typeof object[key] === "object") {
        const newFilter = filterObjectByProperties(
          object[key],
          properties
        );
        if (Object.keys(newFilter).length) {
          newObject[key] = newFilter;
        }
      }
    });
    return newObject;
  };
  function isVariationWithProperties(variation, properties) {
    const variationWithProperties = filterObjectByProperties(
      structuredClone(variation),
      properties
    );
    return areGlobalStylesEqual(variationWithProperties, variation);
  }
  function getFontFamilyFromSetting(fontFamilies, setting) {
    if (!Array.isArray(fontFamilies) || !setting) {
      return null;
    }
    const fontFamilyVariable = setting.replace("var(", "").replace(")", "");
    const fontFamilySlug = fontFamilyVariable?.split("--").slice(-1)[0];
    return fontFamilies.find(
      (fontFamily) => fontFamily.slug === fontFamilySlug
    );
  }
  function getFontFamilies(themeJson) {
    const themeFontFamilies = themeJson?.settings?.typography?.fontFamilies?.theme;
    const customFontFamilies = themeJson?.settings?.typography?.fontFamilies?.custom;
    let fontFamilies = [];
    if (themeFontFamilies && customFontFamilies) {
      fontFamilies = [...themeFontFamilies, ...customFontFamilies];
    } else if (themeFontFamilies) {
      fontFamilies = themeFontFamilies;
    } else if (customFontFamilies) {
      fontFamilies = customFontFamilies;
    }
    const bodyFontFamilySetting = themeJson?.styles?.typography?.fontFamily;
    const bodyFontFamily = getFontFamilyFromSetting(
      fontFamilies,
      bodyFontFamilySetting
    );
    const headingFontFamilySetting = themeJson?.styles?.elements?.heading?.typography?.fontFamily;
    let headingFontFamily;
    if (!headingFontFamilySetting) {
      headingFontFamily = bodyFontFamily;
    } else {
      headingFontFamily = getFontFamilyFromSetting(
        fontFamilies,
        themeJson?.styles?.elements?.heading?.typography?.fontFamily
      );
    }
    return [bodyFontFamily, headingFontFamily];
  }

  // packages/global-styles-ui/build-module/hooks.mjs
  k([a11y_default]);
  function useStyle3(path, blockName, readFrom = "merged", shouldDecodeEncode = true, state) {
    const { user, base, merged, onChange } = (0, import_element133.useContext)(GlobalStylesContext);
    const statePathParts = state?.split(".").filter(Boolean) ?? [];
    const pseudoSelectorState = statePathParts.find(
      (value) => value.startsWith(":")
    );
    const statePathWithoutPseudo = statePathParts.filter((value) => !value.startsWith(":")).join(".");
    const stylePath = [path, statePathWithoutPseudo].filter(Boolean).join(".");
    let sourceValue = merged;
    if (readFrom === "base") {
      sourceValue = base;
    } else if (readFrom === "user") {
      sourceValue = user;
    }
    const styleValue = (0, import_element133.useMemo)(() => {
      const rawValue = getStyle(
        sourceValue,
        stylePath,
        blockName,
        shouldDecodeEncode
      );
      if (pseudoSelectorState) {
        return rawValue?.[pseudoSelectorState] ?? {};
      }
      return rawValue;
    }, [
      sourceValue,
      stylePath,
      blockName,
      shouldDecodeEncode,
      pseudoSelectorState
    ]);
    const setStyleValue = (0, import_element133.useCallback)(
      (newValue) => {
        let valueToSet = newValue;
        if (pseudoSelectorState) {
          const fullCurrentValue = getStyle(
            user,
            stylePath,
            blockName,
            false
          );
          valueToSet = {
            ...fullCurrentValue,
            [pseudoSelectorState]: newValue
          };
        }
        const newGlobalStyles = setStyle(
          user,
          stylePath,
          valueToSet,
          blockName
        );
        onChange(newGlobalStyles);
      },
      [user, onChange, stylePath, blockName, pseudoSelectorState]
    );
    return [styleValue, setStyleValue];
  }
  function useSetting(path, blockName, readFrom = "merged") {
    const { user, base, merged, onChange } = (0, import_element133.useContext)(GlobalStylesContext);
    let sourceValue = merged;
    if (readFrom === "base") {
      sourceValue = base;
    } else if (readFrom === "user") {
      sourceValue = user;
    }
    const settingValue = (0, import_element133.useMemo)(
      () => getSetting(sourceValue, path, blockName),
      [sourceValue, path, blockName]
    );
    const setSettingValue = (0, import_element133.useCallback)(
      (newValue) => {
        const newGlobalStyles = setSetting(
          user,
          path,
          newValue,
          blockName
        );
        onChange(newGlobalStyles);
      },
      [user, onChange, path, blockName]
    );
    return [settingValue, setSettingValue];
  }
  var EMPTY_ARRAY10 = [];
  function hasThemeVariation({
    title,
    settings: settings2,
    styles
  }) {
    return title === (0, import_i18n76.__)("Default") || Object.keys(settings2 || {}).length > 0 || Object.keys(styles || {}).length > 0;
  }
  function useCurrentMergeThemeStyleVariationsWithUserConfig(properties = []) {
    const { variationsFromTheme } = (0, import_data42.useSelect)((select4) => {
      const _variationsFromTheme = select4(
        import_core_data25.store
      ).__experimentalGetCurrentThemeGlobalStylesVariations?.();
      return {
        variationsFromTheme: _variationsFromTheme || EMPTY_ARRAY10
      };
    }, []);
    const { user: userVariation } = (0, import_element133.useContext)(GlobalStylesContext);
    return (0, import_element133.useMemo)(() => {
      const clonedUserVariation = structuredClone(userVariation);
      const userVariationWithoutProperties = removePropertiesFromObject(
        clonedUserVariation,
        properties
      );
      userVariationWithoutProperties.title = (0, import_i18n76.__)("Default");
      const variationsWithPropertiesAndBase = variationsFromTheme.filter((variation) => {
        return isVariationWithProperties(variation, properties);
      }).map((variation) => {
        return mergeGlobalStyles(
          userVariationWithoutProperties,
          variation
        );
      });
      const variationsByProperties = [
        userVariationWithoutProperties,
        ...variationsWithPropertiesAndBase
      ];
      return variationsByProperties?.length ? variationsByProperties.filter(hasThemeVariation) : [];
    }, [properties, userVariation, variationsFromTheme]);
  }

  // packages/global-styles-ui/build-module/root-menu.mjs
  var import_jsx_runtime218 = __toESM(require_jsx_runtime(), 1);
  var {
    useHasDimensionsPanel,
    useHasTypographyPanel,
    useHasColorPanel,
    useSettingsForBlockElement,
    useHasBackgroundPanel
  } = unlock6(import_block_editor6.privateApis);

  // packages/global-styles-ui/build-module/preview-styles.mjs
  var import_components78 = __toESM(require_components(), 1);

  // packages/global-styles-ui/build-module/preview-hooks.mjs
  function useStylesPreviewColors() {
    const [textColor = "black"] = useStyle3("color.text");
    const [backgroundColor = "white"] = useStyle3("color.background");
    const [headingColor = textColor] = useStyle3(
      "elements.h1.color.text"
    );
    const [linkColor = headingColor] = useStyle3(
      "elements.link.color.text"
    );
    const [buttonBackgroundColor = linkColor] = useStyle3(
      "elements.button.color.background"
    );
    const [coreColors] = useSetting("color.palette.core") || [];
    const [themeColors] = useSetting("color.palette.theme") || [];
    const [customColors] = useSetting("color.palette.custom") || [];
    const paletteColors = (themeColors ?? []).concat(customColors ?? []).concat(coreColors ?? []);
    const textColorObject = paletteColors.filter(
      ({ color }) => color === textColor
    );
    const buttonBackgroundColorObject = paletteColors.filter(
      ({ color }) => color === buttonBackgroundColor
    );
    const highlightedColors = textColorObject.concat(buttonBackgroundColorObject).concat(paletteColors).filter(
      // we exclude these background color because it is already visible in the preview.
      ({ color }) => color !== backgroundColor
    ).slice(0, 2);
    return {
      paletteColors,
      highlightedColors
    };
  }

  // packages/global-styles-ui/build-module/typography-example.mjs
  var import_element134 = __toESM(require_element(), 1);
  var import_components75 = __toESM(require_components(), 1);
  var import_i18n78 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/font-library/utils/preview-styles.mjs
  function findNearest(input, numbers) {
    if (numbers.length === 0) {
      return null;
    }
    numbers.sort((a2, b2) => Math.abs(input - a2) - Math.abs(input - b2));
    return numbers[0];
  }
  function extractFontWeights(fontFaces) {
    const result = [];
    fontFaces.forEach((face) => {
      const weights = String(face.fontWeight).split(" ");
      if (weights.length === 2) {
        const start2 = parseInt(weights[0]);
        const end = parseInt(weights[1]);
        for (let i2 = start2; i2 <= end; i2 += 100) {
          result.push(i2);
        }
      } else if (weights.length === 1) {
        result.push(parseInt(weights[0]));
      }
    });
    return result;
  }
  function formatFontFamily(input) {
    const regex = /^(?!generic\([ a-zA-Z\-]+\)$)(?!^[a-zA-Z\-]+$).+/;
    const output = input.trim();
    const formatItem = (item) => {
      item = item.trim();
      if (item.match(regex)) {
        item = item.replace(/^["']|["']$/g, "");
        return `"${item}"`;
      }
      return item;
    };
    if (output.includes(",")) {
      return output.split(",").map(formatItem).filter((item) => item !== "").join(", ");
    }
    return formatItem(output);
  }
  function getFamilyPreviewStyle(family) {
    const style = {
      fontFamily: formatFontFamily(family.fontFamily)
    };
    if (!("fontFace" in family) || !Array.isArray(family.fontFace)) {
      style.fontWeight = "400";
      style.fontStyle = "normal";
      return style;
    }
    if (family.fontFace) {
      const normalFaces = family.fontFace.filter(
        (face) => face?.fontStyle && face.fontStyle.toLowerCase() === "normal"
      );
      if (normalFaces.length > 0) {
        style.fontStyle = "normal";
        const normalWeights = extractFontWeights(normalFaces);
        const nearestWeight = findNearest(400, normalWeights);
        style.fontWeight = String(nearestWeight) || "400";
      } else {
        style.fontStyle = family.fontFace.length && family.fontFace[0].fontStyle || "normal";
        style.fontWeight = family.fontFace.length && String(family.fontFace[0].fontWeight) || "400";
      }
    }
    return style;
  }

  // packages/global-styles-ui/build-module/typography-example.mjs
  var import_jsx_runtime219 = __toESM(require_jsx_runtime(), 1);
  function PreviewTypography({
    fontSize,
    variation
  }) {
    const { base } = (0, import_element134.useContext)(GlobalStylesContext);
    let config2 = base;
    if (variation) {
      config2 = { ...base, ...variation };
    }
    const [textColor] = useStyle3("color.text");
    const [bodyFontFamilies, headingFontFamilies] = getFontFamilies(config2);
    const bodyPreviewStyle = bodyFontFamilies ? getFamilyPreviewStyle(bodyFontFamilies) : {};
    const headingPreviewStyle = headingFontFamilies ? getFamilyPreviewStyle(headingFontFamilies) : {};
    if (textColor) {
      bodyPreviewStyle.color = textColor;
      headingPreviewStyle.color = textColor;
    }
    if (fontSize) {
      bodyPreviewStyle.fontSize = fontSize;
      headingPreviewStyle.fontSize = fontSize;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime219.jsxs)(
      import_components75.__unstableMotion.div,
      {
        animate: {
          scale: 1,
          opacity: 1
        },
        initial: {
          scale: 0.1,
          opacity: 0
        },
        transition: {
          delay: 0.3,
          type: "tween"
        },
        style: {
          textAlign: "center",
          lineHeight: 1
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime219.jsx)("span", { style: headingPreviewStyle, children: (0, import_i18n78._x)("A", "Uppercase letter A") }),
          /* @__PURE__ */ (0, import_jsx_runtime219.jsx)("span", { style: bodyPreviewStyle, children: (0, import_i18n78._x)("a", "Lowercase letter A") })
        ]
      }
    );
  }

  // packages/global-styles-ui/build-module/highlighted-colors.mjs
  var import_components76 = __toESM(require_components(), 1);
  var import_jsx_runtime220 = __toESM(require_jsx_runtime(), 1);
  function HighlightedColors({
    normalizedColorSwatchSize,
    ratio
  }) {
    const { highlightedColors } = useStylesPreviewColors();
    const scaledSwatchSize = normalizedColorSwatchSize * ratio;
    return highlightedColors.map(({ slug, color }, index2) => /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
      import_components76.__unstableMotion.div,
      {
        style: {
          height: scaledSwatchSize,
          width: scaledSwatchSize,
          background: color,
          borderRadius: scaledSwatchSize / 2
        },
        animate: {
          scale: 1,
          opacity: 1
        },
        initial: {
          scale: 0.1,
          opacity: 0
        },
        transition: {
          delay: index2 === 1 ? 0.2 : 0.1
        }
      },
      `${slug}-${index2}`
    ));
  }

  // packages/global-styles-ui/build-module/preview-wrapper.mjs
  var import_components77 = __toESM(require_components(), 1);
  var import_compose22 = __toESM(require_compose(), 1);
  var import_element135 = __toESM(require_element(), 1);
  var import_jsx_runtime221 = __toESM(require_jsx_runtime(), 1);
  var normalizedWidth = 248;
  var normalizedHeight = 152;
  var THROTTLE_OPTIONS = {
    leading: true,
    trailing: true
  };
  function PreviewWrapper({
    children,
    label,
    isFocused,
    withHoverView
  }) {
    const [backgroundColor = "white"] = useStyle3("color.background");
    const [gradientValue] = useStyle3("color.gradient");
    const disableMotion = (0, import_compose22.useReducedMotion)();
    const [isHovered, setIsHovered] = (0, import_element135.useState)(false);
    const [containerResizeListener, { width }] = (0, import_compose22.useResizeObserver)();
    const [throttledWidth, setThrottledWidthState] = (0, import_element135.useState)(width);
    const [ratioState, setRatioState] = (0, import_element135.useState)();
    const setThrottledWidth = (0, import_compose22.useThrottle)(
      setThrottledWidthState,
      250,
      THROTTLE_OPTIONS
    );
    (0, import_element135.useLayoutEffect)(() => {
      if (width) {
        setThrottledWidth(width);
      }
    }, [width, setThrottledWidth]);
    (0, import_element135.useLayoutEffect)(() => {
      const newRatio = throttledWidth ? throttledWidth / normalizedWidth : 1;
      const ratioDiff = newRatio - (ratioState || 0);
      const isRatioDiffBigEnough = Math.abs(ratioDiff) > 0.1;
      if (isRatioDiffBigEnough || !ratioState) {
        setRatioState(newRatio);
      }
    }, [throttledWidth, ratioState]);
    const fallbackRatio = width ? width / normalizedWidth : 1;
    const ratio = ratioState ? ratioState : fallbackRatio;
    const isReady = !!width;
    return /* @__PURE__ */ (0, import_jsx_runtime221.jsxs)(import_jsx_runtime221.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime221.jsx)("div", { style: { position: "relative" }, children: containerResizeListener }),
      !isReady && // Match the preview aspect ratio so layout doesn't jump once width is measured.
      /* @__PURE__ */ (0, import_jsx_runtime221.jsx)(
        Skeleton,
        {
          className: "global-styles-ui-preview__wrapper",
          style: {
            aspectRatio: normalizedWidth / normalizedHeight
          }
        }
      ),
      isReady && /* @__PURE__ */ (0, import_jsx_runtime221.jsx)(
        "div",
        {
          className: clsx_default("global-styles-ui-preview__wrapper", {
            "is-hoverable": withHoverView
          }),
          style: {
            height: normalizedHeight * ratio
          },
          onMouseEnter: () => setIsHovered(true),
          onMouseLeave: () => setIsHovered(false),
          tabIndex: -1,
          children: /* @__PURE__ */ (0, import_jsx_runtime221.jsx)(
            import_components77.__unstableMotion.div,
            {
              style: {
                height: normalizedHeight * ratio,
                width: "100%",
                background: gradientValue ?? backgroundColor
              },
              initial: "start",
              animate: (isHovered || isFocused) && !disableMotion && label ? "hover" : "start",
              children: [].concat(children).map(
                (child, key) => child({ ratio, key })
              )
            }
          )
        }
      )
    ] });
  }
  var preview_wrapper_default = PreviewWrapper;

  // packages/global-styles-ui/build-module/preview-styles.mjs
  var import_jsx_runtime222 = __toESM(require_jsx_runtime(), 1);
  var firstFrameVariants = {
    start: {
      scale: 1,
      opacity: 1
    },
    hover: {
      scale: 0,
      opacity: 0
    }
  };
  var midFrameVariants = {
    hover: {
      opacity: 1
    },
    start: {
      opacity: 0.5
    }
  };
  var secondFrameVariants = {
    hover: {
      scale: 1,
      opacity: 1
    },
    start: {
      scale: 0,
      opacity: 0
    }
  };
  function PreviewStyles({
    label,
    isFocused,
    withHoverView,
    variation
  }) {
    const [fontWeight] = useStyle3("typography.fontWeight");
    const [fontFamily = "serif"] = useStyle3(
      "typography.fontFamily"
    );
    const [headingFontFamily = fontFamily] = useStyle3(
      "elements.h1.typography.fontFamily"
    );
    const [headingFontWeight = fontWeight] = useStyle3(
      "elements.h1.typography.fontWeight"
    );
    const [textColor = "black"] = useStyle3("color.text");
    const [headingColor = textColor] = useStyle3(
      "elements.h1.color.text"
    );
    const { paletteColors } = useStylesPreviewColors();
    return /* @__PURE__ */ (0, import_jsx_runtime222.jsxs)(
      preview_wrapper_default,
      {
        label,
        isFocused,
        withHoverView,
        children: [
          ({ ratio, key }) => /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
            import_components78.__unstableMotion.div,
            {
              variants: firstFrameVariants,
              style: {
                height: "100%",
                overflow: "hidden"
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime222.jsxs)(
                import_components78.__experimentalHStack,
                {
                  spacing: 10 * ratio,
                  justify: "center",
                  style: {
                    height: "100%",
                    overflow: "hidden"
                  },
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
                      PreviewTypography,
                      {
                        fontSize: 65 * ratio,
                        variation
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(import_components78.__experimentalVStack, { spacing: 4 * ratio, children: /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
                      HighlightedColors,
                      {
                        normalizedColorSwatchSize: 32,
                        ratio
                      }
                    ) })
                  ]
                }
              )
            },
            key
          ),
          ({ key }) => /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
            import_components78.__unstableMotion.div,
            {
              variants: withHoverView ? midFrameVariants : void 0,
              style: {
                height: "100%",
                width: "100%",
                position: "absolute",
                top: 0,
                overflow: "hidden",
                filter: "blur(60px)",
                opacity: 0.1
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
                import_components78.__experimentalHStack,
                {
                  spacing: 0,
                  justify: "flex-start",
                  style: {
                    height: "100%",
                    overflow: "hidden"
                  },
                  children: paletteColors.slice(0, 4).map(({ color }, index2) => /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
                    "div",
                    {
                      style: {
                        height: "100%",
                        background: color,
                        flexGrow: 1
                      }
                    },
                    index2
                  ))
                }
              )
            },
            key
          ),
          ({ ratio, key }) => /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
            import_components78.__unstableMotion.div,
            {
              variants: secondFrameVariants,
              style: {
                height: "100%",
                width: "100%",
                overflow: "hidden",
                position: "absolute",
                top: 0
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
                import_components78.__experimentalVStack,
                {
                  spacing: 3 * ratio,
                  justify: "center",
                  style: {
                    height: "100%",
                    overflow: "hidden",
                    padding: 10 * ratio,
                    boxSizing: "border-box"
                  },
                  children: label && /* @__PURE__ */ (0, import_jsx_runtime222.jsx)(
                    "div",
                    {
                      style: {
                        fontSize: 40 * ratio,
                        fontFamily: headingFontFamily,
                        color: headingColor,
                        fontWeight: headingFontWeight,
                        lineHeight: "1em",
                        textAlign: "center"
                      },
                      children: label
                    }
                  )
                }
              )
            },
            key
          )
        ]
      }
    );
  }
  var preview_styles_default = PreviewStyles;

  // packages/global-styles-ui/build-module/screen-root.mjs
  var import_jsx_runtime223 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-block-list.mjs
  var import_blocks5 = __toESM(require_blocks(), 1);
  var import_i18n81 = __toESM(require_i18n(), 1);
  var import_components82 = __toESM(require_components(), 1);
  var import_data45 = __toESM(require_data(), 1);
  var import_element136 = __toESM(require_element(), 1);
  var import_block_editor8 = __toESM(require_block_editor(), 1);
  var import_compose23 = __toESM(require_compose(), 1);
  var import_a11y5 = __toESM(require_a11y(), 1);

  // packages/global-styles-ui/build-module/variations/variations-panel.mjs
  var import_blocks4 = __toESM(require_blocks(), 1);
  var import_data44 = __toESM(require_data(), 1);
  var import_components80 = __toESM(require_components(), 1);
  var import_jsx_runtime224 = __toESM(require_jsx_runtime(), 1);
  function getFilteredBlockStyles(blockStyles, variations) {
    return blockStyles?.filter(
      (style) => style.source === "block" || variations.includes(style.name)
    ) || [];
  }
  function useBlockVariations(name2) {
    const blockStyles = (0, import_data44.useSelect)(
      (select4) => {
        const { getBlockStyles } = select4(import_blocks4.store);
        return getBlockStyles(name2);
      },
      [name2]
    );
    const [variations] = useStyle3("variations", name2);
    const variationNames = Object.keys(variations ?? {});
    return getFilteredBlockStyles(blockStyles, variationNames);
  }

  // packages/global-styles-ui/build-module/screen-header.mjs
  var import_components81 = __toESM(require_components(), 1);
  var import_i18n80 = __toESM(require_i18n(), 1);
  var import_block_editor7 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime225 = __toESM(require_jsx_runtime(), 1);
  var { StateControl, StateControlBadges } = unlock6(import_block_editor7.privateApis);

  // packages/global-styles-ui/build-module/screen-block-list.mjs
  var import_jsx_runtime226 = __toESM(require_jsx_runtime(), 1);
  var {
    useHasDimensionsPanel: useHasDimensionsPanel2,
    useHasTypographyPanel: useHasTypographyPanel2,
    useHasBorderPanel,
    useSettingsForBlockElement: useSettingsForBlockElement2,
    useHasColorPanel: useHasColorPanel2,
    useHasBackgroundPanel: useHasBackgroundPanel2
  } = unlock6(import_block_editor8.privateApis);
  function useSortedBlockTypes() {
    const blockItems = (0, import_data45.useSelect)(
      (select4) => select4(import_blocks5.store).getBlockTypes(),
      []
    );
    const groupByType = (blocks, block) => {
      const { core, noncore } = blocks;
      const type = block.name.startsWith("core/") ? core : noncore;
      type.push(block);
      return blocks;
    };
    const { core: coreItems, noncore: nonCoreItems } = blockItems.reduce(
      groupByType,
      { core: [], noncore: [] }
    );
    return [...coreItems, ...nonCoreItems];
  }
  function useBlockHasGlobalStyles(blockName) {
    const [rawSettings] = useSetting("", blockName);
    const settings2 = useSettingsForBlockElement2(rawSettings, blockName);
    const hasTypographyPanel = useHasTypographyPanel2(settings2);
    const hasColorPanel = useHasColorPanel2(settings2);
    const hasBackgroundPanel = useHasBackgroundPanel2(settings2);
    const hasBorderPanel = useHasBorderPanel(settings2);
    const hasDimensionsPanel = useHasDimensionsPanel2(settings2);
    const hasLayoutPanel = hasBorderPanel || hasDimensionsPanel;
    const hasVariationsPanel = !!useBlockVariations(blockName)?.length;
    const hasGlobalStyles = hasTypographyPanel || hasColorPanel || hasBackgroundPanel || hasLayoutPanel || hasVariationsPanel;
    return hasGlobalStyles;
  }
  function BlockMenuItem({ block }) {
    const hasBlockMenuItem = useBlockHasGlobalStyles(block.name);
    if (!hasBlockMenuItem) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime226.jsx)(
      NavigationButtonAsItem,
      {
        path: "/blocks/" + encodeURIComponent(block.name),
        children: /* @__PURE__ */ (0, import_jsx_runtime226.jsxs)(import_components82.__experimentalHStack, { justify: "flex-start", children: [
          /* @__PURE__ */ (0, import_jsx_runtime226.jsx)(import_block_editor8.BlockIcon, { icon: block.icon }),
          /* @__PURE__ */ (0, import_jsx_runtime226.jsx)(import_components82.FlexItem, { children: block.title })
        ] })
      }
    );
  }
  function BlockList({ filterValue }) {
    const sortedBlockTypes = useSortedBlockTypes();
    const debouncedSpeak = (0, import_compose23.useDebounce)(import_a11y5.speak, 500);
    const { isMatchingSearchTerm } = (0, import_data45.useSelect)(import_blocks5.store);
    const filteredBlockTypes = !filterValue ? sortedBlockTypes : sortedBlockTypes.filter(
      (blockType) => isMatchingSearchTerm(blockType, filterValue)
    );
    const blockTypesListRef = (0, import_element136.useRef)(null);
    (0, import_element136.useEffect)(() => {
      if (!filterValue) {
        return;
      }
      const count = blockTypesListRef.current?.childElementCount || 0;
      const resultsFoundMessage = (0, import_i18n81.sprintf)(
        /* translators: %d: number of results. */
        (0, import_i18n81._n)("%d result found.", "%d results found.", count),
        count
      );
      debouncedSpeak(resultsFoundMessage, "polite");
    }, [filterValue, debouncedSpeak]);
    return /* @__PURE__ */ (0, import_jsx_runtime226.jsx)(
      "div",
      {
        ref: blockTypesListRef,
        className: "global-styles-ui-block-types-item-list",
        role: "list",
        children: filteredBlockTypes.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime226.jsx)(import_components82.__experimentalText, { align: "center", as: "p", children: (0, import_i18n81.__)("No blocks found.") }) : filteredBlockTypes.map((block) => /* @__PURE__ */ (0, import_jsx_runtime226.jsx)(
          BlockMenuItem,
          {
            block
          },
          "menu-itemblock-" + block.name
        ))
      }
    );
  }
  var MemoizedBlockList = (0, import_element136.memo)(BlockList);

  // packages/global-styles-ui/build-module/screen-block.mjs
  var import_blocks7 = __toESM(require_blocks(), 1);
  var import_block_editor10 = __toESM(require_block_editor(), 1);
  var import_element138 = __toESM(require_element(), 1);
  var import_data46 = __toESM(require_data(), 1);
  var import_core_data27 = __toESM(require_core_data(), 1);
  var import_components85 = __toESM(require_components(), 1);
  var import_i18n82 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/block-preview-panel.mjs
  var import_block_editor9 = __toESM(require_block_editor(), 1);
  var import_blocks6 = __toESM(require_blocks(), 1);
  var import_components83 = __toESM(require_components(), 1);
  var import_element137 = __toESM(require_element(), 1);
  var import_jsx_runtime227 = __toESM(require_jsx_runtime(), 1);
  var { getViewportBreakpoints: getViewportBreakpoints3, getViewportBreakpointValueInPixels: getViewportBreakpointValueInPixels2 } = unlock6(
    privateApis2
  );

  // packages/global-styles-ui/build-module/subtitle.mjs
  var import_components84 = __toESM(require_components(), 1);
  var import_jsx_runtime228 = __toESM(require_jsx_runtime(), 1);
  function Subtitle({ children, level = 2 }) {
    return /* @__PURE__ */ (0, import_jsx_runtime228.jsx)(import_components84.__experimentalHeading, { className: "global-styles-ui-subtitle", level, children });
  }

  // packages/global-styles-ui/build-module/screen-block.mjs
  var import_jsx_runtime229 = __toESM(require_jsx_runtime(), 1);
  var {
    useHasDimensionsPanel: useHasDimensionsPanel3,
    useHasTypographyPanel: useHasTypographyPanel3,
    useHasBorderPanel: useHasBorderPanel2,
    useSettingsForBlockElement: useSettingsForBlockElement3,
    useHasColorPanel: useHasColorPanel3,
    useHasFiltersPanel,
    useHasImageSettingsPanel,
    useHasBackgroundPanel: useHasBackgroundPanel3,
    BackgroundPanel: StylesBackgroundPanel,
    BorderPanel: StylesBorderPanel,
    ColorPanel: StylesColorPanel,
    TypographyPanel: StylesTypographyPanel,
    DimensionsPanel: StylesDimensionsPanel,
    FiltersPanel: StylesFiltersPanel,
    ImageSettingsPanel,
    AdvancedPanel: StylesAdvancedPanel
  } = unlock6(import_block_editor10.privateApis);

  // packages/global-styles-ui/build-module/screen-typography.mjs
  var import_i18n96 = __toESM(require_i18n(), 1);
  var import_components104 = __toESM(require_components(), 1);
  var import_element150 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/screen-body.mjs
  var import_components86 = __toESM(require_components(), 1);
  var import_jsx_runtime230 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/typography-elements.mjs
  var import_i18n83 = __toESM(require_i18n(), 1);
  var import_components87 = __toESM(require_components(), 1);
  var import_jsx_runtime231 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/variations/variations-typography.mjs
  var import_components89 = __toESM(require_components(), 1);

  // packages/global-styles-ui/build-module/preview-typography.mjs
  var import_components88 = __toESM(require_components(), 1);
  var import_jsx_runtime232 = __toESM(require_jsx_runtime(), 1);
  var StylesPreviewTypography = ({
    variation,
    isFocused,
    withHoverView
  }) => {
    return /* @__PURE__ */ (0, import_jsx_runtime232.jsx)(
      preview_wrapper_default,
      {
        label: variation.title,
        isFocused,
        withHoverView,
        children: ({ ratio, key }) => /* @__PURE__ */ (0, import_jsx_runtime232.jsx)(
          import_components88.__experimentalHStack,
          {
            spacing: 10 * ratio,
            justify: "center",
            style: {
              height: "100%",
              overflow: "hidden"
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime232.jsx)(
              PreviewTypography,
              {
                variation,
                fontSize: 85 * ratio
              }
            )
          },
          key
        )
      }
    );
  };
  var preview_typography_default = StylesPreviewTypography;

  // packages/global-styles-ui/build-module/variations/variation.mjs
  var import_element139 = __toESM(require_element(), 1);
  var import_keycodes5 = __toESM(require_keycodes(), 1);
  var import_i18n84 = __toESM(require_i18n(), 1);
  var import_jsx_runtime233 = __toESM(require_jsx_runtime(), 1);
  function Variation({
    variation,
    children,
    isPill = false,
    properties,
    showTooltip = false
  }) {
    const [isFocused, setIsFocused] = (0, import_element139.useState)(false);
    const {
      base,
      user,
      onChange: setUserConfig
    } = (0, import_element139.useContext)(GlobalStylesContext);
    const context = (0, import_element139.useMemo)(() => {
      let merged = mergeGlobalStyles(base, variation);
      if (properties) {
        merged = filterObjectByProperties(merged, properties);
      }
      return {
        user: variation,
        base,
        merged,
        onChange: () => {
        }
      };
    }, [variation, base, properties]);
    const selectVariation = () => setUserConfig(variation);
    const selectOnEnter = (event) => {
      if (event.keyCode === import_keycodes5.ENTER) {
        event.preventDefault();
        selectVariation();
      }
    };
    const isActive = (0, import_element139.useMemo)(
      () => areGlobalStylesEqual(user, variation),
      [user, variation]
    );
    let label = variation?.title;
    if (variation?.description) {
      label = (0, import_i18n84.sprintf)(
        /* translators: 1: variation title. 2: variation description. */
        (0, import_i18n84._x)("%1$s (%2$s)", "variation label"),
        variation?.title,
        variation?.description
      );
    }
    const content = /* @__PURE__ */ (0, import_jsx_runtime233.jsx)(
      "div",
      {
        className: clsx_default("global-styles-ui-variations_item", {
          "is-active": isActive
        }),
        role: "button",
        onClick: selectVariation,
        onKeyDown: selectOnEnter,
        tabIndex: 0,
        "aria-label": label,
        "aria-current": isActive,
        onFocus: () => setIsFocused(true),
        onBlur: () => setIsFocused(false),
        children: /* @__PURE__ */ (0, import_jsx_runtime233.jsx)(
          "div",
          {
            className: clsx_default("global-styles-ui-variations_item-preview", {
              "is-pill": isPill
            }),
            children: children(isFocused)
          }
        )
      }
    );
    return /* @__PURE__ */ (0, import_jsx_runtime233.jsx)(GlobalStylesContext.Provider, { value: context, children: showTooltip ? /* @__PURE__ */ (0, import_jsx_runtime233.jsxs)(tooltip_exports.Root, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime233.jsx)(tooltip_exports.Trigger, { render: content }),
      /* @__PURE__ */ (0, import_jsx_runtime233.jsx)(tooltip_exports.Popup, { children: variation?.title })
    ] }) : content });
  }

  // packages/global-styles-ui/build-module/variations/variations-typography.mjs
  var import_jsx_runtime234 = __toESM(require_jsx_runtime(), 1);
  var propertiesToFilter = ["typography"];
  function TypographyVariations({
    title,
    gap = 2
  }) {
    const typographyVariations = useCurrentMergeThemeStyleVariationsWithUserConfig(propertiesToFilter);
    if (typographyVariations?.length <= 1) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime234.jsxs)(import_components89.__experimentalVStack, { spacing: 3, children: [
      title && /* @__PURE__ */ (0, import_jsx_runtime234.jsx)(Subtitle, { level: 3, children: title }),
      /* @__PURE__ */ (0, import_jsx_runtime234.jsx)(
        import_components89.__experimentalGrid,
        {
          columns: 3,
          gap,
          className: "global-styles-ui-style-variations-container",
          children: typographyVariations.map(
            (variation, index2) => {
              return /* @__PURE__ */ (0, import_jsx_runtime234.jsx)(
                Variation,
                {
                  variation,
                  properties: propertiesToFilter,
                  showTooltip: true,
                  children: () => /* @__PURE__ */ (0, import_jsx_runtime234.jsx)(
                    preview_typography_default,
                    {
                      variation
                    }
                  )
                },
                index2
              );
            }
          )
        }
      )
    ] });
  }

  // packages/global-styles-ui/build-module/font-families.mjs
  var import_i18n94 = __toESM(require_i18n(), 1);
  var import_components102 = __toESM(require_components(), 1);
  var import_element149 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/font-library/context.mjs
  var import_element140 = __toESM(require_element(), 1);
  var import_data47 = __toESM(require_data(), 1);
  var import_core_data29 = __toESM(require_core_data(), 1);
  var import_i18n86 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/font-library/api.mjs
  var import_api_fetch3 = __toESM(require_api_fetch(), 1);
  var import_core_data28 = __toESM(require_core_data(), 1);

  // packages/global-styles-ui/build-module/font-library/utils/index.mjs
  var import_components90 = __toESM(require_components(), 1);

  // packages/global-styles-ui/build-module/font-library/utils/constants.mjs
  var import_i18n85 = __toESM(require_i18n(), 1);
  var FONT_WEIGHTS = {
    100: (0, import_i18n85._x)("Thin", "font weight"),
    200: (0, import_i18n85._x)("Extra-light", "font weight"),
    300: (0, import_i18n85._x)("Light", "font weight"),
    400: (0, import_i18n85._x)("Normal", "font weight"),
    500: (0, import_i18n85._x)("Medium", "font weight"),
    600: (0, import_i18n85._x)("Semi-bold", "font weight"),
    700: (0, import_i18n85._x)("Bold", "font weight"),
    800: (0, import_i18n85._x)("Extra-bold", "font weight"),
    900: (0, import_i18n85._x)("Black", "font weight")
  };
  var FONT_STYLES = {
    normal: (0, import_i18n85._x)("Normal", "font style"),
    italic: (0, import_i18n85._x)("Italic", "font style")
  };

  // packages/global-styles-ui/build-module/font-library/utils/index.mjs
  var { File } = window;
  var { kebabCase: kebabCase3 } = unlock6(import_components90.privateApis);

  // packages/global-styles-ui/build-module/font-library/context.mjs
  var import_jsx_runtime235 = __toESM(require_jsx_runtime(), 1);
  var FontLibraryContext = (0, import_element140.createContext)(
    {}
  );
  FontLibraryContext.displayName = "FontLibraryContext";

  // packages/global-styles-ui/build-module/font-library/modal.mjs
  var import_i18n92 = __toESM(require_i18n(), 1);
  var import_components100 = __toESM(require_components(), 1);
  var import_core_data32 = __toESM(require_core_data(), 1);
  var import_data49 = __toESM(require_data(), 1);

  // packages/global-styles-ui/build-module/font-library/installed-fonts.mjs
  var import_components94 = __toESM(require_components(), 1);
  var import_core_data30 = __toESM(require_core_data(), 1);
  var import_data48 = __toESM(require_data(), 1);
  var import_element144 = __toESM(require_element(), 1);
  var import_i18n88 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/font-library/font-card.mjs
  var import_i18n87 = __toESM(require_i18n(), 1);
  var import_element142 = __toESM(require_element(), 1);
  var import_components92 = __toESM(require_components(), 1);

  // packages/global-styles-ui/build-module/font-library/font-demo.mjs
  var import_components91 = __toESM(require_components(), 1);
  var import_element141 = __toESM(require_element(), 1);
  var import_jsx_runtime236 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-library/font-card.mjs
  var import_jsx_runtime237 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-library/library-font-variant.mjs
  var import_element143 = __toESM(require_element(), 1);
  var import_components93 = __toESM(require_components(), 1);
  var import_jsx_runtime238 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-library/installed-fonts.mjs
  var import_jsx_runtime239 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-library/font-collection.mjs
  var import_element146 = __toESM(require_element(), 1);
  var import_components97 = __toESM(require_components(), 1);
  var import_compose24 = __toESM(require_compose(), 1);
  var import_i18n90 = __toESM(require_i18n(), 1);
  var import_core_data31 = __toESM(require_core_data(), 1);

  // packages/global-styles-ui/build-module/font-library/google-fonts-confirm-dialog.mjs
  var import_i18n89 = __toESM(require_i18n(), 1);
  var import_components95 = __toESM(require_components(), 1);
  var import_jsx_runtime240 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-library/collection-font-variant.mjs
  var import_element145 = __toESM(require_element(), 1);
  var import_components96 = __toESM(require_components(), 1);
  var import_jsx_runtime241 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-library/font-collection.mjs
  var import_jsx_runtime242 = __toESM(require_jsx_runtime(), 1);
  var DEFAULT_CATEGORY = {
    slug: "all",
    name: (0, import_i18n90._x)("All", "font categories")
  };

  // packages/global-styles-ui/build-module/font-library/upload-fonts.mjs
  var import_i18n91 = __toESM(require_i18n(), 1);
  var import_components99 = __toESM(require_components(), 1);
  var import_element147 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/font-library/lib/unbrotli.mjs
  var __require2 = /* @__PURE__ */ ((x2) => typeof __require !== "undefined" ? __require : typeof Proxy !== "undefined" ? new Proxy(x2, {
    get: (a2, b2) => (typeof __require !== "undefined" ? __require : a2)[b2]
  }) : x2)(function(x2) {
    if (typeof __require !== "undefined") return __require.apply(this, arguments);
    throw Error('Dynamic require of "' + x2 + '" is not supported');
  });
  var unbrotli_default = (function() {
    var define, module, exports;
    return (/* @__PURE__ */ (function() {
      function r3(e2, n2, t3) {
        function o3(i22, f2) {
          if (!n2[i22]) {
            if (!e2[i22]) {
              var c6 = "function" == typeof __require2 && __require2;
              if (!f2 && c6) return c6(i22, true);
              if (u2) return u2(i22, true);
              var a2 = new Error("Cannot find module '" + i22 + "'");
              throw a2.code = "MODULE_NOT_FOUND", a2;
            }
            var p3 = n2[i22] = { exports: {} };
            e2[i22][0].call(
              p3.exports,
              function(r22) {
                var n22 = e2[i22][1][r22];
                return o3(n22 || r22);
              },
              p3,
              p3.exports,
              r3,
              e2,
              n2,
              t3
            );
          }
          return n2[i22].exports;
        }
        for (var u2 = "function" == typeof __require2 && __require2, i2 = 0; i2 < t3.length; i2++)
          o3(t3[i2]);
        return o3;
      }
      return r3;
    })())(
      {
        1: [
          function(require2, module2, exports2) {
            var BROTLI_READ_SIZE = 4096;
            var BROTLI_IBUF_SIZE = 2 * BROTLI_READ_SIZE + 32;
            var BROTLI_IBUF_MASK = 2 * BROTLI_READ_SIZE - 1;
            var kBitMask = new Uint32Array([
              0,
              1,
              3,
              7,
              15,
              31,
              63,
              127,
              255,
              511,
              1023,
              2047,
              4095,
              8191,
              16383,
              32767,
              65535,
              131071,
              262143,
              524287,
              1048575,
              2097151,
              4194303,
              8388607,
              16777215
            ]);
            function BrotliBitReader(input) {
              this.buf_ = new Uint8Array(BROTLI_IBUF_SIZE);
              this.input_ = input;
              this.reset();
            }
            BrotliBitReader.READ_SIZE = BROTLI_READ_SIZE;
            BrotliBitReader.IBUF_MASK = BROTLI_IBUF_MASK;
            BrotliBitReader.prototype.reset = function() {
              this.buf_ptr_ = 0;
              this.val_ = 0;
              this.pos_ = 0;
              this.bit_pos_ = 0;
              this.bit_end_pos_ = 0;
              this.eos_ = 0;
              this.readMoreInput();
              for (var i2 = 0; i2 < 4; i2++) {
                this.val_ |= this.buf_[this.pos_] << 8 * i2;
                ++this.pos_;
              }
              return this.bit_end_pos_ > 0;
            };
            BrotliBitReader.prototype.readMoreInput = function() {
              if (this.bit_end_pos_ > 256) {
                return;
              } else if (this.eos_) {
                if (this.bit_pos_ > this.bit_end_pos_)
                  throw new Error(
                    "Unexpected end of input " + this.bit_pos_ + " " + this.bit_end_pos_
                  );
              } else {
                var dst = this.buf_ptr_;
                var bytes_read = this.input_.read(
                  this.buf_,
                  dst,
                  BROTLI_READ_SIZE
                );
                if (bytes_read < 0) {
                  throw new Error("Unexpected end of input");
                }
                if (bytes_read < BROTLI_READ_SIZE) {
                  this.eos_ = 1;
                  for (var p3 = 0; p3 < 32; p3++)
                    this.buf_[dst + bytes_read + p3] = 0;
                }
                if (dst === 0) {
                  for (var p3 = 0; p3 < 32; p3++)
                    this.buf_[(BROTLI_READ_SIZE << 1) + p3] = this.buf_[p3];
                  this.buf_ptr_ = BROTLI_READ_SIZE;
                } else {
                  this.buf_ptr_ = 0;
                }
                this.bit_end_pos_ += bytes_read << 3;
              }
            };
            BrotliBitReader.prototype.fillBitWindow = function() {
              while (this.bit_pos_ >= 8) {
                this.val_ >>>= 8;
                this.val_ |= this.buf_[this.pos_ & BROTLI_IBUF_MASK] << 24;
                ++this.pos_;
                this.bit_pos_ = this.bit_pos_ - 8 >>> 0;
                this.bit_end_pos_ = this.bit_end_pos_ - 8 >>> 0;
              }
            };
            BrotliBitReader.prototype.readBits = function(n_bits) {
              if (32 - this.bit_pos_ < n_bits) {
                this.fillBitWindow();
              }
              var val = this.val_ >>> this.bit_pos_ & kBitMask[n_bits];
              this.bit_pos_ += n_bits;
              return val;
            };
            module2.exports = BrotliBitReader;
          },
          {}
        ],
        2: [
          function(require2, module2, exports2) {
            var CONTEXT_LSB6 = 0;
            var CONTEXT_MSB6 = 1;
            var CONTEXT_UTF8 = 2;
            var CONTEXT_SIGNED = 3;
            exports2.lookup = new Uint8Array([
              /* CONTEXT_UTF8, last byte. */
              /* ASCII range. */
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              4,
              4,
              0,
              0,
              4,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              8,
              12,
              16,
              12,
              12,
              20,
              12,
              16,
              24,
              28,
              12,
              12,
              32,
              12,
              36,
              12,
              44,
              44,
              44,
              44,
              44,
              44,
              44,
              44,
              44,
              44,
              32,
              32,
              24,
              40,
              28,
              12,
              12,
              48,
              52,
              52,
              52,
              48,
              52,
              52,
              52,
              48,
              52,
              52,
              52,
              52,
              52,
              48,
              52,
              52,
              52,
              52,
              52,
              48,
              52,
              52,
              52,
              52,
              52,
              24,
              12,
              28,
              12,
              12,
              12,
              56,
              60,
              60,
              60,
              56,
              60,
              60,
              60,
              56,
              60,
              60,
              60,
              60,
              60,
              56,
              60,
              60,
              60,
              60,
              60,
              56,
              60,
              60,
              60,
              60,
              60,
              24,
              12,
              28,
              12,
              0,
              /* UTF8 continuation byte range. */
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              0,
              1,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              2,
              3,
              /* ASCII range. */
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              1,
              1,
              1,
              1,
              1,
              1,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              1,
              1,
              1,
              1,
              0,
              /* UTF8 continuation byte range. */
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              0,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              1,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              2,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              3,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              4,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              5,
              6,
              6,
              6,
              6,
              6,
              6,
              6,
              6,
              6,
              6,
              6,
              6,
              6,
              6,
              6,
              7,
              /* CONTEXT_SIGNED, last byte, same as the above values shifted by 3 bits. */
              0,
              8,
              8,
              8,
              8,
              8,
              8,
              8,
              8,
              8,
              8,
              8,
              8,
              8,
              8,
              8,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              24,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              32,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              40,
              48,
              48,
              48,
              48,
              48,
              48,
              48,
              48,
              48,
              48,
              48,
              48,
              48,
              48,
              48,
              56,
              /* CONTEXT_LSB6, last byte. */
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7,
              8,
              9,
              10,
              11,
              12,
              13,
              14,
              15,
              16,
              17,
              18,
              19,
              20,
              21,
              22,
              23,
              24,
              25,
              26,
              27,
              28,
              29,
              30,
              31,
              32,
              33,
              34,
              35,
              36,
              37,
              38,
              39,
              40,
              41,
              42,
              43,
              44,
              45,
              46,
              47,
              48,
              49,
              50,
              51,
              52,
              53,
              54,
              55,
              56,
              57,
              58,
              59,
              60,
              61,
              62,
              63,
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7,
              8,
              9,
              10,
              11,
              12,
              13,
              14,
              15,
              16,
              17,
              18,
              19,
              20,
              21,
              22,
              23,
              24,
              25,
              26,
              27,
              28,
              29,
              30,
              31,
              32,
              33,
              34,
              35,
              36,
              37,
              38,
              39,
              40,
              41,
              42,
              43,
              44,
              45,
              46,
              47,
              48,
              49,
              50,
              51,
              52,
              53,
              54,
              55,
              56,
              57,
              58,
              59,
              60,
              61,
              62,
              63,
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7,
              8,
              9,
              10,
              11,
              12,
              13,
              14,
              15,
              16,
              17,
              18,
              19,
              20,
              21,
              22,
              23,
              24,
              25,
              26,
              27,
              28,
              29,
              30,
              31,
              32,
              33,
              34,
              35,
              36,
              37,
              38,
              39,
              40,
              41,
              42,
              43,
              44,
              45,
              46,
              47,
              48,
              49,
              50,
              51,
              52,
              53,
              54,
              55,
              56,
              57,
              58,
              59,
              60,
              61,
              62,
              63,
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7,
              8,
              9,
              10,
              11,
              12,
              13,
              14,
              15,
              16,
              17,
              18,
              19,
              20,
              21,
              22,
              23,
              24,
              25,
              26,
              27,
              28,
              29,
              30,
              31,
              32,
              33,
              34,
              35,
              36,
              37,
              38,
              39,
              40,
              41,
              42,
              43,
              44,
              45,
              46,
              47,
              48,
              49,
              50,
              51,
              52,
              53,
              54,
              55,
              56,
              57,
              58,
              59,
              60,
              61,
              62,
              63,
              /* CONTEXT_MSB6, last byte. */
              0,
              0,
              0,
              0,
              1,
              1,
              1,
              1,
              2,
              2,
              2,
              2,
              3,
              3,
              3,
              3,
              4,
              4,
              4,
              4,
              5,
              5,
              5,
              5,
              6,
              6,
              6,
              6,
              7,
              7,
              7,
              7,
              8,
              8,
              8,
              8,
              9,
              9,
              9,
              9,
              10,
              10,
              10,
              10,
              11,
              11,
              11,
              11,
              12,
              12,
              12,
              12,
              13,
              13,
              13,
              13,
              14,
              14,
              14,
              14,
              15,
              15,
              15,
              15,
              16,
              16,
              16,
              16,
              17,
              17,
              17,
              17,
              18,
              18,
              18,
              18,
              19,
              19,
              19,
              19,
              20,
              20,
              20,
              20,
              21,
              21,
              21,
              21,
              22,
              22,
              22,
              22,
              23,
              23,
              23,
              23,
              24,
              24,
              24,
              24,
              25,
              25,
              25,
              25,
              26,
              26,
              26,
              26,
              27,
              27,
              27,
              27,
              28,
              28,
              28,
              28,
              29,
              29,
              29,
              29,
              30,
              30,
              30,
              30,
              31,
              31,
              31,
              31,
              32,
              32,
              32,
              32,
              33,
              33,
              33,
              33,
              34,
              34,
              34,
              34,
              35,
              35,
              35,
              35,
              36,
              36,
              36,
              36,
              37,
              37,
              37,
              37,
              38,
              38,
              38,
              38,
              39,
              39,
              39,
              39,
              40,
              40,
              40,
              40,
              41,
              41,
              41,
              41,
              42,
              42,
              42,
              42,
              43,
              43,
              43,
              43,
              44,
              44,
              44,
              44,
              45,
              45,
              45,
              45,
              46,
              46,
              46,
              46,
              47,
              47,
              47,
              47,
              48,
              48,
              48,
              48,
              49,
              49,
              49,
              49,
              50,
              50,
              50,
              50,
              51,
              51,
              51,
              51,
              52,
              52,
              52,
              52,
              53,
              53,
              53,
              53,
              54,
              54,
              54,
              54,
              55,
              55,
              55,
              55,
              56,
              56,
              56,
              56,
              57,
              57,
              57,
              57,
              58,
              58,
              58,
              58,
              59,
              59,
              59,
              59,
              60,
              60,
              60,
              60,
              61,
              61,
              61,
              61,
              62,
              62,
              62,
              62,
              63,
              63,
              63,
              63,
              /* CONTEXT_{M,L}SB6, second last byte, */
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0,
              0
            ]);
            exports2.lookupOffsets = new Uint16Array([
              /* CONTEXT_LSB6 */
              1024,
              1536,
              1280,
              1536,
              0,
              256,
              768,
              512
            ]);
          },
          {}
        ],
        3: [
          function(require2, module2, exports2) {
            var BrotliInput = require2("./streams").BrotliInput;
            var BrotliOutput = require2("./streams").BrotliOutput;
            var BrotliBitReader = require2("./bit_reader");
            var BrotliDictionary = require2("./dictionary");
            var HuffmanCode = require2("./huffman").HuffmanCode;
            var BrotliBuildHuffmanTable = require2("./huffman").BrotliBuildHuffmanTable;
            var Context = require2("./context");
            var Prefix = require2("./prefix");
            var Transform = require2("./transform");
            var kDefaultCodeLength = 8;
            var kCodeLengthRepeatCode = 16;
            var kNumLiteralCodes = 256;
            var kNumInsertAndCopyCodes = 704;
            var kNumBlockLengthCodes = 26;
            var kLiteralContextBits = 6;
            var kDistanceContextBits = 2;
            var HUFFMAN_TABLE_BITS = 8;
            var HUFFMAN_TABLE_MASK = 255;
            var HUFFMAN_MAX_TABLE_SIZE = 1080;
            var CODE_LENGTH_CODES = 18;
            var kCodeLengthCodeOrder = new Uint8Array([
              1,
              2,
              3,
              4,
              0,
              5,
              17,
              6,
              16,
              7,
              8,
              9,
              10,
              11,
              12,
              13,
              14,
              15
            ]);
            var NUM_DISTANCE_SHORT_CODES = 16;
            var kDistanceShortCodeIndexOffset = new Uint8Array([
              3,
              2,
              1,
              0,
              3,
              3,
              3,
              3,
              3,
              3,
              2,
              2,
              2,
              2,
              2,
              2
            ]);
            var kDistanceShortCodeValueOffset = new Int8Array([
              0,
              0,
              0,
              0,
              -1,
              1,
              -2,
              2,
              -3,
              3,
              -1,
              1,
              -2,
              2,
              -3,
              3
            ]);
            var kMaxHuffmanTableSize = new Uint16Array([
              256,
              402,
              436,
              468,
              500,
              534,
              566,
              598,
              630,
              662,
              694,
              726,
              758,
              790,
              822,
              854,
              886,
              920,
              952,
              984,
              1016,
              1048,
              1080
            ]);
            function DecodeWindowBits(br) {
              var n2;
              if (br.readBits(1) === 0) {
                return 16;
              }
              n2 = br.readBits(3);
              if (n2 > 0) {
                return 17 + n2;
              }
              n2 = br.readBits(3);
              if (n2 > 0) {
                return 8 + n2;
              }
              return 17;
            }
            function DecodeVarLenUint8(br) {
              if (br.readBits(1)) {
                var nbits = br.readBits(3);
                if (nbits === 0) {
                  return 1;
                } else {
                  return br.readBits(nbits) + (1 << nbits);
                }
              }
              return 0;
            }
            function MetaBlockLength() {
              this.meta_block_length = 0;
              this.input_end = 0;
              this.is_uncompressed = 0;
              this.is_metadata = false;
            }
            function DecodeMetaBlockLength(br) {
              var out = new MetaBlockLength();
              var size_nibbles;
              var size_bytes;
              var i2;
              out.input_end = br.readBits(1);
              if (out.input_end && br.readBits(1)) {
                return out;
              }
              size_nibbles = br.readBits(2) + 4;
              if (size_nibbles === 7) {
                out.is_metadata = true;
                if (br.readBits(1) !== 0)
                  throw new Error("Invalid reserved bit");
                size_bytes = br.readBits(2);
                if (size_bytes === 0) return out;
                for (i2 = 0; i2 < size_bytes; i2++) {
                  var next_byte = br.readBits(8);
                  if (i2 + 1 === size_bytes && size_bytes > 1 && next_byte === 0)
                    throw new Error("Invalid size byte");
                  out.meta_block_length |= next_byte << i2 * 8;
                }
              } else {
                for (i2 = 0; i2 < size_nibbles; ++i2) {
                  var next_nibble = br.readBits(4);
                  if (i2 + 1 === size_nibbles && size_nibbles > 4 && next_nibble === 0)
                    throw new Error("Invalid size nibble");
                  out.meta_block_length |= next_nibble << i2 * 4;
                }
              }
              ++out.meta_block_length;
              if (!out.input_end && !out.is_metadata) {
                out.is_uncompressed = br.readBits(1);
              }
              return out;
            }
            function ReadSymbol(table, index2, br) {
              var start_index = index2;
              var nbits;
              br.fillBitWindow();
              index2 += br.val_ >>> br.bit_pos_ & HUFFMAN_TABLE_MASK;
              nbits = table[index2].bits - HUFFMAN_TABLE_BITS;
              if (nbits > 0) {
                br.bit_pos_ += HUFFMAN_TABLE_BITS;
                index2 += table[index2].value;
                index2 += br.val_ >>> br.bit_pos_ & (1 << nbits) - 1;
              }
              br.bit_pos_ += table[index2].bits;
              return table[index2].value;
            }
            function ReadHuffmanCodeLengths(code_length_code_lengths, num_symbols, code_lengths, br) {
              var symbol3 = 0;
              var prev_code_len = kDefaultCodeLength;
              var repeat = 0;
              var repeat_code_len = 0;
              var space = 32768;
              var table = [];
              for (var i2 = 0; i2 < 32; i2++)
                table.push(new HuffmanCode(0, 0));
              BrotliBuildHuffmanTable(
                table,
                0,
                5,
                code_length_code_lengths,
                CODE_LENGTH_CODES
              );
              while (symbol3 < num_symbols && space > 0) {
                var p3 = 0;
                var code_len;
                br.readMoreInput();
                br.fillBitWindow();
                p3 += br.val_ >>> br.bit_pos_ & 31;
                br.bit_pos_ += table[p3].bits;
                code_len = table[p3].value & 255;
                if (code_len < kCodeLengthRepeatCode) {
                  repeat = 0;
                  code_lengths[symbol3++] = code_len;
                  if (code_len !== 0) {
                    prev_code_len = code_len;
                    space -= 32768 >> code_len;
                  }
                } else {
                  var extra_bits = code_len - 14;
                  var old_repeat;
                  var repeat_delta;
                  var new_len = 0;
                  if (code_len === kCodeLengthRepeatCode) {
                    new_len = prev_code_len;
                  }
                  if (repeat_code_len !== new_len) {
                    repeat = 0;
                    repeat_code_len = new_len;
                  }
                  old_repeat = repeat;
                  if (repeat > 0) {
                    repeat -= 2;
                    repeat <<= extra_bits;
                  }
                  repeat += br.readBits(extra_bits) + 3;
                  repeat_delta = repeat - old_repeat;
                  if (symbol3 + repeat_delta > num_symbols) {
                    throw new Error(
                      "[ReadHuffmanCodeLengths] symbol + repeat_delta > num_symbols"
                    );
                  }
                  for (var x2 = 0; x2 < repeat_delta; x2++)
                    code_lengths[symbol3 + x2] = repeat_code_len;
                  symbol3 += repeat_delta;
                  if (repeat_code_len !== 0) {
                    space -= repeat_delta << 15 - repeat_code_len;
                  }
                }
              }
              if (space !== 0) {
                throw new Error(
                  "[ReadHuffmanCodeLengths] space = " + space
                );
              }
              for (; symbol3 < num_symbols; symbol3++)
                code_lengths[symbol3] = 0;
            }
            function ReadHuffmanCode(alphabet_size, tables, table, br) {
              var table_size = 0;
              var simple_code_or_skip;
              var code_lengths = new Uint8Array(alphabet_size);
              br.readMoreInput();
              simple_code_or_skip = br.readBits(2);
              if (simple_code_or_skip === 1) {
                var i2;
                var max_bits_counter = alphabet_size - 1;
                var max_bits = 0;
                var symbols = new Int32Array(4);
                var num_symbols = br.readBits(2) + 1;
                while (max_bits_counter) {
                  max_bits_counter >>= 1;
                  ++max_bits;
                }
                for (i2 = 0; i2 < num_symbols; ++i2) {
                  symbols[i2] = br.readBits(max_bits) % alphabet_size;
                  code_lengths[symbols[i2]] = 2;
                }
                code_lengths[symbols[0]] = 1;
                switch (num_symbols) {
                  case 1:
                    break;
                  case 3:
                    if (symbols[0] === symbols[1] || symbols[0] === symbols[2] || symbols[1] === symbols[2]) {
                      throw new Error(
                        "[ReadHuffmanCode] invalid symbols"
                      );
                    }
                    break;
                  case 2:
                    if (symbols[0] === symbols[1]) {
                      throw new Error(
                        "[ReadHuffmanCode] invalid symbols"
                      );
                    }
                    code_lengths[symbols[1]] = 1;
                    break;
                  case 4:
                    if (symbols[0] === symbols[1] || symbols[0] === symbols[2] || symbols[0] === symbols[3] || symbols[1] === symbols[2] || symbols[1] === symbols[3] || symbols[2] === symbols[3]) {
                      throw new Error(
                        "[ReadHuffmanCode] invalid symbols"
                      );
                    }
                    if (br.readBits(1)) {
                      code_lengths[symbols[2]] = 3;
                      code_lengths[symbols[3]] = 3;
                    } else {
                      code_lengths[symbols[0]] = 2;
                    }
                    break;
                }
              } else {
                var i2;
                var code_length_code_lengths = new Uint8Array(
                  CODE_LENGTH_CODES
                );
                var space = 32;
                var num_codes = 0;
                var huff = [
                  new HuffmanCode(2, 0),
                  new HuffmanCode(2, 4),
                  new HuffmanCode(2, 3),
                  new HuffmanCode(3, 2),
                  new HuffmanCode(2, 0),
                  new HuffmanCode(2, 4),
                  new HuffmanCode(2, 3),
                  new HuffmanCode(4, 1),
                  new HuffmanCode(2, 0),
                  new HuffmanCode(2, 4),
                  new HuffmanCode(2, 3),
                  new HuffmanCode(3, 2),
                  new HuffmanCode(2, 0),
                  new HuffmanCode(2, 4),
                  new HuffmanCode(2, 3),
                  new HuffmanCode(4, 5)
                ];
                for (i2 = simple_code_or_skip; i2 < CODE_LENGTH_CODES && space > 0; ++i2) {
                  var code_len_idx = kCodeLengthCodeOrder[i2];
                  var p3 = 0;
                  var v2;
                  br.fillBitWindow();
                  p3 += br.val_ >>> br.bit_pos_ & 15;
                  br.bit_pos_ += huff[p3].bits;
                  v2 = huff[p3].value;
                  code_length_code_lengths[code_len_idx] = v2;
                  if (v2 !== 0) {
                    space -= 32 >> v2;
                    ++num_codes;
                  }
                }
                if (!(num_codes === 1 || space === 0))
                  throw new Error(
                    "[ReadHuffmanCode] invalid num_codes or space"
                  );
                ReadHuffmanCodeLengths(
                  code_length_code_lengths,
                  alphabet_size,
                  code_lengths,
                  br
                );
              }
              table_size = BrotliBuildHuffmanTable(
                tables,
                table,
                HUFFMAN_TABLE_BITS,
                code_lengths,
                alphabet_size
              );
              if (table_size === 0) {
                throw new Error(
                  "[ReadHuffmanCode] BuildHuffmanTable failed: "
                );
              }
              return table_size;
            }
            function ReadBlockLength(table, index2, br) {
              var code;
              var nbits;
              code = ReadSymbol(table, index2, br);
              nbits = Prefix.kBlockLengthPrefixCode[code].nbits;
              return Prefix.kBlockLengthPrefixCode[code].offset + br.readBits(nbits);
            }
            function TranslateShortCodes(code, ringbuffer, index2) {
              var val;
              if (code < NUM_DISTANCE_SHORT_CODES) {
                index2 += kDistanceShortCodeIndexOffset[code];
                index2 &= 3;
                val = ringbuffer[index2] + kDistanceShortCodeValueOffset[code];
              } else {
                val = code - NUM_DISTANCE_SHORT_CODES + 1;
              }
              return val;
            }
            function MoveToFront(v2, index2) {
              var value = v2[index2];
              var i2 = index2;
              for (; i2; --i2) v2[i2] = v2[i2 - 1];
              v2[0] = value;
            }
            function InverseMoveToFrontTransform(v2, v_len) {
              var mtf = new Uint8Array(256);
              var i2;
              for (i2 = 0; i2 < 256; ++i2) {
                mtf[i2] = i2;
              }
              for (i2 = 0; i2 < v_len; ++i2) {
                var index2 = v2[i2];
                v2[i2] = mtf[index2];
                if (index2) MoveToFront(mtf, index2);
              }
            }
            function HuffmanTreeGroup(alphabet_size, num_htrees) {
              this.alphabet_size = alphabet_size;
              this.num_htrees = num_htrees;
              this.codes = new Array(
                num_htrees + num_htrees * kMaxHuffmanTableSize[alphabet_size + 31 >>> 5]
              );
              this.htrees = new Uint32Array(num_htrees);
            }
            HuffmanTreeGroup.prototype.decode = function(br) {
              var i2;
              var table_size;
              var next = 0;
              for (i2 = 0; i2 < this.num_htrees; ++i2) {
                this.htrees[i2] = next;
                table_size = ReadHuffmanCode(
                  this.alphabet_size,
                  this.codes,
                  next,
                  br
                );
                next += table_size;
              }
            };
            function DecodeContextMap(context_map_size, br) {
              var out = { num_htrees: null, context_map: null };
              var use_rle_for_zeros;
              var max_run_length_prefix = 0;
              var table;
              var i2;
              br.readMoreInput();
              var num_htrees = out.num_htrees = DecodeVarLenUint8(br) + 1;
              var context_map = out.context_map = new Uint8Array(
                context_map_size
              );
              if (num_htrees <= 1) {
                return out;
              }
              use_rle_for_zeros = br.readBits(1);
              if (use_rle_for_zeros) {
                max_run_length_prefix = br.readBits(4) + 1;
              }
              table = [];
              for (i2 = 0; i2 < HUFFMAN_MAX_TABLE_SIZE; i2++) {
                table[i2] = new HuffmanCode(0, 0);
              }
              ReadHuffmanCode(
                num_htrees + max_run_length_prefix,
                table,
                0,
                br
              );
              for (i2 = 0; i2 < context_map_size; ) {
                var code;
                br.readMoreInput();
                code = ReadSymbol(table, 0, br);
                if (code === 0) {
                  context_map[i2] = 0;
                  ++i2;
                } else if (code <= max_run_length_prefix) {
                  var reps = 1 + (1 << code) + br.readBits(code);
                  while (--reps) {
                    if (i2 >= context_map_size) {
                      throw new Error(
                        "[DecodeContextMap] i >= context_map_size"
                      );
                    }
                    context_map[i2] = 0;
                    ++i2;
                  }
                } else {
                  context_map[i2] = code - max_run_length_prefix;
                  ++i2;
                }
              }
              if (br.readBits(1)) {
                InverseMoveToFrontTransform(
                  context_map,
                  context_map_size
                );
              }
              return out;
            }
            function DecodeBlockType(max_block_type, trees, tree_type, block_types, ringbuffers, indexes, br) {
              var ringbuffer = tree_type * 2;
              var index2 = tree_type;
              var type_code = ReadSymbol(
                trees,
                tree_type * HUFFMAN_MAX_TABLE_SIZE,
                br
              );
              var block_type;
              if (type_code === 0) {
                block_type = ringbuffers[ringbuffer + (indexes[index2] & 1)];
              } else if (type_code === 1) {
                block_type = ringbuffers[ringbuffer + (indexes[index2] - 1 & 1)] + 1;
              } else {
                block_type = type_code - 2;
              }
              if (block_type >= max_block_type) {
                block_type -= max_block_type;
              }
              block_types[tree_type] = block_type;
              ringbuffers[ringbuffer + (indexes[index2] & 1)] = block_type;
              ++indexes[index2];
            }
            function CopyUncompressedBlockToOutput(output, len, pos, ringbuffer, ringbuffer_mask, br) {
              var rb_size = ringbuffer_mask + 1;
              var rb_pos = pos & ringbuffer_mask;
              var br_pos = br.pos_ & BrotliBitReader.IBUF_MASK;
              var nbytes;
              if (len < 8 || br.bit_pos_ + (len << 3) < br.bit_end_pos_) {
                while (len-- > 0) {
                  br.readMoreInput();
                  ringbuffer[rb_pos++] = br.readBits(8);
                  if (rb_pos === rb_size) {
                    output.write(ringbuffer, rb_size);
                    rb_pos = 0;
                  }
                }
                return;
              }
              if (br.bit_end_pos_ < 32) {
                throw new Error(
                  "[CopyUncompressedBlockToOutput] br.bit_end_pos_ < 32"
                );
              }
              while (br.bit_pos_ < 32) {
                ringbuffer[rb_pos] = br.val_ >>> br.bit_pos_;
                br.bit_pos_ += 8;
                ++rb_pos;
                --len;
              }
              nbytes = br.bit_end_pos_ - br.bit_pos_ >> 3;
              if (br_pos + nbytes > BrotliBitReader.IBUF_MASK) {
                var tail = BrotliBitReader.IBUF_MASK + 1 - br_pos;
                for (var x2 = 0; x2 < tail; x2++)
                  ringbuffer[rb_pos + x2] = br.buf_[br_pos + x2];
                nbytes -= tail;
                rb_pos += tail;
                len -= tail;
                br_pos = 0;
              }
              for (var x2 = 0; x2 < nbytes; x2++)
                ringbuffer[rb_pos + x2] = br.buf_[br_pos + x2];
              rb_pos += nbytes;
              len -= nbytes;
              if (rb_pos >= rb_size) {
                output.write(ringbuffer, rb_size);
                rb_pos -= rb_size;
                for (var x2 = 0; x2 < rb_pos; x2++)
                  ringbuffer[x2] = ringbuffer[rb_size + x2];
              }
              while (rb_pos + len >= rb_size) {
                nbytes = rb_size - rb_pos;
                if (br.input_.read(ringbuffer, rb_pos, nbytes) < nbytes) {
                  throw new Error(
                    "[CopyUncompressedBlockToOutput] not enough bytes"
                  );
                }
                output.write(ringbuffer, rb_size);
                len -= nbytes;
                rb_pos = 0;
              }
              if (br.input_.read(ringbuffer, rb_pos, len) < len) {
                throw new Error(
                  "[CopyUncompressedBlockToOutput] not enough bytes"
                );
              }
              br.reset();
            }
            function JumpToByteBoundary(br) {
              var new_bit_pos = br.bit_pos_ + 7 & ~7;
              var pad_bits = br.readBits(new_bit_pos - br.bit_pos_);
              return pad_bits == 0;
            }
            function BrotliDecompressedSize(buffer) {
              var input = new BrotliInput(buffer);
              var br = new BrotliBitReader(input);
              DecodeWindowBits(br);
              var out = DecodeMetaBlockLength(br);
              return out.meta_block_length;
            }
            exports2.BrotliDecompressedSize = BrotliDecompressedSize;
            function BrotliDecompressBuffer(buffer, output_size) {
              var input = new BrotliInput(buffer);
              if (output_size == null) {
                output_size = BrotliDecompressedSize(buffer);
              }
              var output_buffer = new Uint8Array(output_size);
              var output = new BrotliOutput(output_buffer);
              BrotliDecompress(input, output);
              if (output.pos < output.buffer.length) {
                output.buffer = output.buffer.subarray(
                  0,
                  output.pos
                );
              }
              return output.buffer;
            }
            exports2.BrotliDecompressBuffer = BrotliDecompressBuffer;
            function BrotliDecompress(input, output) {
              var i2;
              var pos = 0;
              var input_end = 0;
              var window_bits = 0;
              var max_backward_distance;
              var max_distance = 0;
              var ringbuffer_size;
              var ringbuffer_mask;
              var ringbuffer;
              var ringbuffer_end;
              var dist_rb = [16, 15, 11, 4];
              var dist_rb_idx = 0;
              var prev_byte1 = 0;
              var prev_byte2 = 0;
              var hgroup = [
                new HuffmanTreeGroup(0, 0),
                new HuffmanTreeGroup(0, 0),
                new HuffmanTreeGroup(0, 0)
              ];
              var block_type_trees;
              var block_len_trees;
              var br;
              var kRingBufferWriteAheadSlack = 128 + BrotliBitReader.READ_SIZE;
              br = new BrotliBitReader(input);
              window_bits = DecodeWindowBits(br);
              max_backward_distance = (1 << window_bits) - 16;
              ringbuffer_size = 1 << window_bits;
              ringbuffer_mask = ringbuffer_size - 1;
              ringbuffer = new Uint8Array(
                ringbuffer_size + kRingBufferWriteAheadSlack + BrotliDictionary.maxDictionaryWordLength
              );
              ringbuffer_end = ringbuffer_size;
              block_type_trees = [];
              block_len_trees = [];
              for (var x2 = 0; x2 < 3 * HUFFMAN_MAX_TABLE_SIZE; x2++) {
                block_type_trees[x2] = new HuffmanCode(0, 0);
                block_len_trees[x2] = new HuffmanCode(0, 0);
              }
              while (!input_end) {
                var meta_block_remaining_len = 0;
                var is_uncompressed;
                var block_length = [1 << 28, 1 << 28, 1 << 28];
                var block_type = [0];
                var num_block_types = [1, 1, 1];
                var block_type_rb = [0, 1, 0, 1, 0, 1];
                var block_type_rb_index = [0];
                var distance_postfix_bits;
                var num_direct_distance_codes;
                var distance_postfix_mask;
                var num_distance_codes;
                var context_map = null;
                var context_modes = null;
                var num_literal_htrees;
                var dist_context_map = null;
                var num_dist_htrees;
                var context_offset = 0;
                var context_map_slice = null;
                var literal_htree_index = 0;
                var dist_context_offset = 0;
                var dist_context_map_slice = null;
                var dist_htree_index = 0;
                var context_lookup_offset1 = 0;
                var context_lookup_offset2 = 0;
                var context_mode;
                var htree_command;
                for (i2 = 0; i2 < 3; ++i2) {
                  hgroup[i2].codes = null;
                  hgroup[i2].htrees = null;
                }
                br.readMoreInput();
                var _out = DecodeMetaBlockLength(br);
                meta_block_remaining_len = _out.meta_block_length;
                if (pos + meta_block_remaining_len > output.buffer.length) {
                  var tmp = new Uint8Array(
                    pos + meta_block_remaining_len
                  );
                  tmp.set(output.buffer);
                  output.buffer = tmp;
                }
                input_end = _out.input_end;
                is_uncompressed = _out.is_uncompressed;
                if (_out.is_metadata) {
                  JumpToByteBoundary(br);
                  for (; meta_block_remaining_len > 0; --meta_block_remaining_len) {
                    br.readMoreInput();
                    br.readBits(8);
                  }
                  continue;
                }
                if (meta_block_remaining_len === 0) {
                  continue;
                }
                if (is_uncompressed) {
                  br.bit_pos_ = br.bit_pos_ + 7 & ~7;
                  CopyUncompressedBlockToOutput(
                    output,
                    meta_block_remaining_len,
                    pos,
                    ringbuffer,
                    ringbuffer_mask,
                    br
                  );
                  pos += meta_block_remaining_len;
                  continue;
                }
                for (i2 = 0; i2 < 3; ++i2) {
                  num_block_types[i2] = DecodeVarLenUint8(br) + 1;
                  if (num_block_types[i2] >= 2) {
                    ReadHuffmanCode(
                      num_block_types[i2] + 2,
                      block_type_trees,
                      i2 * HUFFMAN_MAX_TABLE_SIZE,
                      br
                    );
                    ReadHuffmanCode(
                      kNumBlockLengthCodes,
                      block_len_trees,
                      i2 * HUFFMAN_MAX_TABLE_SIZE,
                      br
                    );
                    block_length[i2] = ReadBlockLength(
                      block_len_trees,
                      i2 * HUFFMAN_MAX_TABLE_SIZE,
                      br
                    );
                    block_type_rb_index[i2] = 1;
                  }
                }
                br.readMoreInput();
                distance_postfix_bits = br.readBits(2);
                num_direct_distance_codes = NUM_DISTANCE_SHORT_CODES + (br.readBits(4) << distance_postfix_bits);
                distance_postfix_mask = (1 << distance_postfix_bits) - 1;
                num_distance_codes = num_direct_distance_codes + (48 << distance_postfix_bits);
                context_modes = new Uint8Array(
                  num_block_types[0]
                );
                for (i2 = 0; i2 < num_block_types[0]; ++i2) {
                  br.readMoreInput();
                  context_modes[i2] = br.readBits(2) << 1;
                }
                var _o1 = DecodeContextMap(
                  num_block_types[0] << kLiteralContextBits,
                  br
                );
                num_literal_htrees = _o1.num_htrees;
                context_map = _o1.context_map;
                var _o2 = DecodeContextMap(
                  num_block_types[2] << kDistanceContextBits,
                  br
                );
                num_dist_htrees = _o2.num_htrees;
                dist_context_map = _o2.context_map;
                hgroup[0] = new HuffmanTreeGroup(
                  kNumLiteralCodes,
                  num_literal_htrees
                );
                hgroup[1] = new HuffmanTreeGroup(
                  kNumInsertAndCopyCodes,
                  num_block_types[1]
                );
                hgroup[2] = new HuffmanTreeGroup(
                  num_distance_codes,
                  num_dist_htrees
                );
                for (i2 = 0; i2 < 3; ++i2) {
                  hgroup[i2].decode(br);
                }
                context_map_slice = 0;
                dist_context_map_slice = 0;
                context_mode = context_modes[block_type[0]];
                context_lookup_offset1 = Context.lookupOffsets[context_mode];
                context_lookup_offset2 = Context.lookupOffsets[context_mode + 1];
                htree_command = hgroup[1].htrees[0];
                while (meta_block_remaining_len > 0) {
                  var cmd_code;
                  var range_idx;
                  var insert_code;
                  var copy_code;
                  var insert_length;
                  var copy_length;
                  var distance_code;
                  var distance;
                  var context;
                  var j2;
                  var copy_dst;
                  br.readMoreInput();
                  if (block_length[1] === 0) {
                    DecodeBlockType(
                      num_block_types[1],
                      block_type_trees,
                      1,
                      block_type,
                      block_type_rb,
                      block_type_rb_index,
                      br
                    );
                    block_length[1] = ReadBlockLength(
                      block_len_trees,
                      HUFFMAN_MAX_TABLE_SIZE,
                      br
                    );
                    htree_command = hgroup[1].htrees[block_type[1]];
                  }
                  --block_length[1];
                  cmd_code = ReadSymbol(
                    hgroup[1].codes,
                    htree_command,
                    br
                  );
                  range_idx = cmd_code >> 6;
                  if (range_idx >= 2) {
                    range_idx -= 2;
                    distance_code = -1;
                  } else {
                    distance_code = 0;
                  }
                  insert_code = Prefix.kInsertRangeLut[range_idx] + (cmd_code >> 3 & 7);
                  copy_code = Prefix.kCopyRangeLut[range_idx] + (cmd_code & 7);
                  insert_length = Prefix.kInsertLengthPrefixCode[insert_code].offset + br.readBits(
                    Prefix.kInsertLengthPrefixCode[insert_code].nbits
                  );
                  copy_length = Prefix.kCopyLengthPrefixCode[copy_code].offset + br.readBits(
                    Prefix.kCopyLengthPrefixCode[copy_code].nbits
                  );
                  prev_byte1 = ringbuffer[pos - 1 & ringbuffer_mask];
                  prev_byte2 = ringbuffer[pos - 2 & ringbuffer_mask];
                  for (j2 = 0; j2 < insert_length; ++j2) {
                    br.readMoreInput();
                    if (block_length[0] === 0) {
                      DecodeBlockType(
                        num_block_types[0],
                        block_type_trees,
                        0,
                        block_type,
                        block_type_rb,
                        block_type_rb_index,
                        br
                      );
                      block_length[0] = ReadBlockLength(
                        block_len_trees,
                        0,
                        br
                      );
                      context_offset = block_type[0] << kLiteralContextBits;
                      context_map_slice = context_offset;
                      context_mode = context_modes[block_type[0]];
                      context_lookup_offset1 = Context.lookupOffsets[context_mode];
                      context_lookup_offset2 = Context.lookupOffsets[context_mode + 1];
                    }
                    context = Context.lookup[context_lookup_offset1 + prev_byte1] | Context.lookup[context_lookup_offset2 + prev_byte2];
                    literal_htree_index = context_map[context_map_slice + context];
                    --block_length[0];
                    prev_byte2 = prev_byte1;
                    prev_byte1 = ReadSymbol(
                      hgroup[0].codes,
                      hgroup[0].htrees[literal_htree_index],
                      br
                    );
                    ringbuffer[pos & ringbuffer_mask] = prev_byte1;
                    if ((pos & ringbuffer_mask) === ringbuffer_mask) {
                      output.write(
                        ringbuffer,
                        ringbuffer_size
                      );
                    }
                    ++pos;
                  }
                  meta_block_remaining_len -= insert_length;
                  if (meta_block_remaining_len <= 0) break;
                  if (distance_code < 0) {
                    var context;
                    br.readMoreInput();
                    if (block_length[2] === 0) {
                      DecodeBlockType(
                        num_block_types[2],
                        block_type_trees,
                        2,
                        block_type,
                        block_type_rb,
                        block_type_rb_index,
                        br
                      );
                      block_length[2] = ReadBlockLength(
                        block_len_trees,
                        2 * HUFFMAN_MAX_TABLE_SIZE,
                        br
                      );
                      dist_context_offset = block_type[2] << kDistanceContextBits;
                      dist_context_map_slice = dist_context_offset;
                    }
                    --block_length[2];
                    context = (copy_length > 4 ? 3 : copy_length - 2) & 255;
                    dist_htree_index = dist_context_map[dist_context_map_slice + context];
                    distance_code = ReadSymbol(
                      hgroup[2].codes,
                      hgroup[2].htrees[dist_htree_index],
                      br
                    );
                    if (distance_code >= num_direct_distance_codes) {
                      var nbits;
                      var postfix;
                      var offset4;
                      distance_code -= num_direct_distance_codes;
                      postfix = distance_code & distance_postfix_mask;
                      distance_code >>= distance_postfix_bits;
                      nbits = (distance_code >> 1) + 1;
                      offset4 = (2 + (distance_code & 1) << nbits) - 4;
                      distance_code = num_direct_distance_codes + (offset4 + br.readBits(nbits) << distance_postfix_bits) + postfix;
                    }
                  }
                  distance = TranslateShortCodes(
                    distance_code,
                    dist_rb,
                    dist_rb_idx
                  );
                  if (distance < 0) {
                    throw new Error(
                      "[BrotliDecompress] invalid distance"
                    );
                  }
                  if (pos < max_backward_distance && max_distance !== max_backward_distance) {
                    max_distance = pos;
                  } else {
                    max_distance = max_backward_distance;
                  }
                  copy_dst = pos & ringbuffer_mask;
                  if (distance > max_distance) {
                    if (copy_length >= BrotliDictionary.minDictionaryWordLength && copy_length <= BrotliDictionary.maxDictionaryWordLength) {
                      var offset4 = BrotliDictionary.offsetsByLength[copy_length];
                      var word_id = distance - max_distance - 1;
                      var shift4 = BrotliDictionary.sizeBitsByLength[copy_length];
                      var mask = (1 << shift4) - 1;
                      var word_idx = word_id & mask;
                      var transform_idx = word_id >> shift4;
                      offset4 += word_idx * copy_length;
                      if (transform_idx < Transform.kNumTransforms) {
                        var len = Transform.transformDictionaryWord(
                          ringbuffer,
                          copy_dst,
                          offset4,
                          copy_length,
                          transform_idx
                        );
                        copy_dst += len;
                        pos += len;
                        meta_block_remaining_len -= len;
                        if (copy_dst >= ringbuffer_end) {
                          output.write(
                            ringbuffer,
                            ringbuffer_size
                          );
                          for (var _x25 = 0; _x25 < copy_dst - ringbuffer_end; _x25++)
                            ringbuffer[_x25] = ringbuffer[ringbuffer_end + _x25];
                        }
                      } else {
                        throw new Error(
                          "Invalid backward reference. pos: " + pos + " distance: " + distance + " len: " + copy_length + " bytes left: " + meta_block_remaining_len
                        );
                      }
                    } else {
                      throw new Error(
                        "Invalid backward reference. pos: " + pos + " distance: " + distance + " len: " + copy_length + " bytes left: " + meta_block_remaining_len
                      );
                    }
                  } else {
                    if (distance_code > 0) {
                      dist_rb[dist_rb_idx & 3] = distance;
                      ++dist_rb_idx;
                    }
                    if (copy_length > meta_block_remaining_len) {
                      throw new Error(
                        "Invalid backward reference. pos: " + pos + " distance: " + distance + " len: " + copy_length + " bytes left: " + meta_block_remaining_len
                      );
                    }
                    for (j2 = 0; j2 < copy_length; ++j2) {
                      ringbuffer[pos & ringbuffer_mask] = ringbuffer[pos - distance & ringbuffer_mask];
                      if ((pos & ringbuffer_mask) === ringbuffer_mask) {
                        output.write(
                          ringbuffer,
                          ringbuffer_size
                        );
                      }
                      ++pos;
                      --meta_block_remaining_len;
                    }
                  }
                  prev_byte1 = ringbuffer[pos - 1 & ringbuffer_mask];
                  prev_byte2 = ringbuffer[pos - 2 & ringbuffer_mask];
                }
                pos &= 1073741823;
              }
              output.write(ringbuffer, pos & ringbuffer_mask);
            }
            exports2.BrotliDecompress = BrotliDecompress;
            BrotliDictionary.init();
          },
          {
            "./bit_reader": 1,
            "./context": 2,
            "./dictionary": 6,
            "./huffman": 7,
            "./prefix": 9,
            "./streams": 10,
            "./transform": 11
          }
        ],
        4: [
          function(require2, module2, exports2) {
            var base64 = require2("base64-js");
            exports2.init = function() {
              var BrotliDecompressBuffer = require2("./decode").BrotliDecompressBuffer;
              var compressed = base64.toByteArray(
                require2("./dictionary.bin.js")
              );
              return BrotliDecompressBuffer(compressed);
            };
          },
          { "./decode": 3, "./dictionary.bin.js": 5, "base64-js": 8 }
        ],
        5: [
          function(require2, module2, exports2) {
            module2.exports = " ";
          },
          {}
        ],
        6: [
          function(require2, module2, exports2) {
            var data = require2("./dictionary-browser");
            exports2.init = function() {
              exports2.dictionary = data.init();
            };
            exports2.offsetsByLength = new Uint32Array([
              0,
              0,
              0,
              0,
              0,
              4096,
              9216,
              21504,
              35840,
              44032,
              53248,
              63488,
              74752,
              87040,
              93696,
              100864,
              104704,
              106752,
              108928,
              113536,
              115968,
              118528,
              119872,
              121280,
              122016
            ]);
            exports2.sizeBitsByLength = new Uint8Array([
              0,
              0,
              0,
              0,
              10,
              10,
              11,
              11,
              10,
              10,
              10,
              10,
              10,
              9,
              9,
              8,
              7,
              7,
              8,
              7,
              7,
              6,
              6,
              5,
              5
            ]);
            exports2.minDictionaryWordLength = 4;
            exports2.maxDictionaryWordLength = 24;
          },
          { "./dictionary-browser": 4 }
        ],
        7: [
          function(require2, module2, exports2) {
            function HuffmanCode(bits, value) {
              this.bits = bits;
              this.value = value;
            }
            exports2.HuffmanCode = HuffmanCode;
            var MAX_LENGTH = 15;
            function GetNextKey(key, len) {
              var step = 1 << len - 1;
              while (key & step) {
                step >>= 1;
              }
              return (key & step - 1) + step;
            }
            function ReplicateValue(table, i2, step, end, code) {
              do {
                end -= step;
                table[i2 + end] = new HuffmanCode(
                  code.bits,
                  code.value
                );
              } while (end > 0);
            }
            function NextTableBitSize(count, len, root_bits) {
              var left = 1 << len - root_bits;
              while (len < MAX_LENGTH) {
                left -= count[len];
                if (left <= 0) break;
                ++len;
                left <<= 1;
              }
              return len - root_bits;
            }
            exports2.BrotliBuildHuffmanTable = function(root_table, table, root_bits, code_lengths, code_lengths_size) {
              var start_table = table;
              var code;
              var len;
              var symbol3;
              var key;
              var step;
              var low;
              var mask;
              var table_bits;
              var table_size;
              var total_size;
              var sorted;
              var count = new Int32Array(
                MAX_LENGTH + 1
              );
              var offset4 = new Int32Array(
                MAX_LENGTH + 1
              );
              sorted = new Int32Array(code_lengths_size);
              for (symbol3 = 0; symbol3 < code_lengths_size; symbol3++) {
                count[code_lengths[symbol3]]++;
              }
              offset4[1] = 0;
              for (len = 1; len < MAX_LENGTH; len++) {
                offset4[len + 1] = offset4[len] + count[len];
              }
              for (symbol3 = 0; symbol3 < code_lengths_size; symbol3++) {
                if (code_lengths[symbol3] !== 0) {
                  sorted[offset4[code_lengths[symbol3]]++] = symbol3;
                }
              }
              table_bits = root_bits;
              table_size = 1 << table_bits;
              total_size = table_size;
              if (offset4[MAX_LENGTH] === 1) {
                for (key = 0; key < total_size; ++key) {
                  root_table[table + key] = new HuffmanCode(
                    0,
                    sorted[0] & 65535
                  );
                }
                return total_size;
              }
              key = 0;
              symbol3 = 0;
              for (len = 1, step = 2; len <= root_bits; ++len, step <<= 1) {
                for (; count[len] > 0; --count[len]) {
                  code = new HuffmanCode(
                    len & 255,
                    sorted[symbol3++] & 65535
                  );
                  ReplicateValue(
                    root_table,
                    table + key,
                    step,
                    table_size,
                    code
                  );
                  key = GetNextKey(key, len);
                }
              }
              mask = total_size - 1;
              low = -1;
              for (len = root_bits + 1, step = 2; len <= MAX_LENGTH; ++len, step <<= 1) {
                for (; count[len] > 0; --count[len]) {
                  if ((key & mask) !== low) {
                    table += table_size;
                    table_bits = NextTableBitSize(
                      count,
                      len,
                      root_bits
                    );
                    table_size = 1 << table_bits;
                    total_size += table_size;
                    low = key & mask;
                    root_table[start_table + low] = new HuffmanCode(
                      table_bits + root_bits & 255,
                      table - start_table - low & 65535
                    );
                  }
                  code = new HuffmanCode(
                    len - root_bits & 255,
                    sorted[symbol3++] & 65535
                  );
                  ReplicateValue(
                    root_table,
                    table + (key >> root_bits),
                    step,
                    table_size,
                    code
                  );
                  key = GetNextKey(key, len);
                }
              }
              return total_size;
            };
          },
          {}
        ],
        8: [
          function(require2, module2, exports2) {
            "use strict";
            exports2.byteLength = byteLength;
            exports2.toByteArray = toByteArray;
            exports2.fromByteArray = fromByteArray;
            var lookup = [];
            var revLookup = [];
            var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
            var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            for (var i2 = 0, len = code.length; i2 < len; ++i2) {
              lookup[i2] = code[i2];
              revLookup[code.charCodeAt(i2)] = i2;
            }
            revLookup["-".charCodeAt(0)] = 62;
            revLookup["_".charCodeAt(0)] = 63;
            function getLens(b64) {
              var len2 = b64.length;
              if (len2 % 4 > 0) {
                throw new Error(
                  "Invalid string. Length must be a multiple of 4"
                );
              }
              var validLen = b64.indexOf("=");
              if (validLen === -1) validLen = len2;
              var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
              return [validLen, placeHoldersLen];
            }
            function byteLength(b64) {
              var lens = getLens(b64);
              var validLen = lens[0];
              var placeHoldersLen = lens[1];
              return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
            }
            function _byteLength(b64, validLen, placeHoldersLen) {
              return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
            }
            function toByteArray(b64) {
              var tmp;
              var lens = getLens(b64);
              var validLen = lens[0];
              var placeHoldersLen = lens[1];
              var arr = new Arr(
                _byteLength(b64, validLen, placeHoldersLen)
              );
              var curByte = 0;
              var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
              for (var i22 = 0; i22 < len2; i22 += 4) {
                tmp = revLookup[b64.charCodeAt(i22)] << 18 | revLookup[b64.charCodeAt(i22 + 1)] << 12 | revLookup[b64.charCodeAt(i22 + 2)] << 6 | revLookup[b64.charCodeAt(i22 + 3)];
                arr[curByte++] = tmp >> 16 & 255;
                arr[curByte++] = tmp >> 8 & 255;
                arr[curByte++] = tmp & 255;
              }
              if (placeHoldersLen === 2) {
                tmp = revLookup[b64.charCodeAt(i22)] << 2 | revLookup[b64.charCodeAt(i22 + 1)] >> 4;
                arr[curByte++] = tmp & 255;
              }
              if (placeHoldersLen === 1) {
                tmp = revLookup[b64.charCodeAt(i22)] << 10 | revLookup[b64.charCodeAt(i22 + 1)] << 4 | revLookup[b64.charCodeAt(i22 + 2)] >> 2;
                arr[curByte++] = tmp >> 8 & 255;
                arr[curByte++] = tmp & 255;
              }
              return arr;
            }
            function tripletToBase64(num) {
              return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
            }
            function encodeChunk(uint8, start2, end) {
              var tmp;
              var output = [];
              for (var i22 = start2; i22 < end; i22 += 3) {
                tmp = (uint8[i22] << 16 & 16711680) + (uint8[i22 + 1] << 8 & 65280) + (uint8[i22 + 2] & 255);
                output.push(tripletToBase64(tmp));
              }
              return output.join("");
            }
            function fromByteArray(uint8) {
              var tmp;
              var len2 = uint8.length;
              var extraBytes = len2 % 3;
              var parts = [];
              var maxChunkLength = 16383;
              for (var i22 = 0, len22 = len2 - extraBytes; i22 < len22; i22 += maxChunkLength) {
                parts.push(
                  encodeChunk(
                    uint8,
                    i22,
                    i22 + maxChunkLength > len22 ? len22 : i22 + maxChunkLength
                  )
                );
              }
              if (extraBytes === 1) {
                tmp = uint8[len2 - 1];
                parts.push(
                  lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
                );
              } else if (extraBytes === 2) {
                tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
                parts.push(
                  lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
                );
              }
              return parts.join("");
            }
          },
          {}
        ],
        9: [
          function(require2, module2, exports2) {
            function PrefixCodeRange(offset4, nbits) {
              this.offset = offset4;
              this.nbits = nbits;
            }
            exports2.kBlockLengthPrefixCode = [
              new PrefixCodeRange(1, 2),
              new PrefixCodeRange(5, 2),
              new PrefixCodeRange(9, 2),
              new PrefixCodeRange(13, 2),
              new PrefixCodeRange(17, 3),
              new PrefixCodeRange(25, 3),
              new PrefixCodeRange(33, 3),
              new PrefixCodeRange(41, 3),
              new PrefixCodeRange(49, 4),
              new PrefixCodeRange(65, 4),
              new PrefixCodeRange(81, 4),
              new PrefixCodeRange(97, 4),
              new PrefixCodeRange(113, 5),
              new PrefixCodeRange(145, 5),
              new PrefixCodeRange(177, 5),
              new PrefixCodeRange(209, 5),
              new PrefixCodeRange(241, 6),
              new PrefixCodeRange(305, 6),
              new PrefixCodeRange(369, 7),
              new PrefixCodeRange(497, 8),
              new PrefixCodeRange(753, 9),
              new PrefixCodeRange(1265, 10),
              new PrefixCodeRange(2289, 11),
              new PrefixCodeRange(4337, 12),
              new PrefixCodeRange(8433, 13),
              new PrefixCodeRange(16625, 24)
            ];
            exports2.kInsertLengthPrefixCode = [
              new PrefixCodeRange(0, 0),
              new PrefixCodeRange(1, 0),
              new PrefixCodeRange(2, 0),
              new PrefixCodeRange(3, 0),
              new PrefixCodeRange(4, 0),
              new PrefixCodeRange(5, 0),
              new PrefixCodeRange(6, 1),
              new PrefixCodeRange(8, 1),
              new PrefixCodeRange(10, 2),
              new PrefixCodeRange(14, 2),
              new PrefixCodeRange(18, 3),
              new PrefixCodeRange(26, 3),
              new PrefixCodeRange(34, 4),
              new PrefixCodeRange(50, 4),
              new PrefixCodeRange(66, 5),
              new PrefixCodeRange(98, 5),
              new PrefixCodeRange(130, 6),
              new PrefixCodeRange(194, 7),
              new PrefixCodeRange(322, 8),
              new PrefixCodeRange(578, 9),
              new PrefixCodeRange(1090, 10),
              new PrefixCodeRange(2114, 12),
              new PrefixCodeRange(6210, 14),
              new PrefixCodeRange(22594, 24)
            ];
            exports2.kCopyLengthPrefixCode = [
              new PrefixCodeRange(2, 0),
              new PrefixCodeRange(3, 0),
              new PrefixCodeRange(4, 0),
              new PrefixCodeRange(5, 0),
              new PrefixCodeRange(6, 0),
              new PrefixCodeRange(7, 0),
              new PrefixCodeRange(8, 0),
              new PrefixCodeRange(9, 0),
              new PrefixCodeRange(10, 1),
              new PrefixCodeRange(12, 1),
              new PrefixCodeRange(14, 2),
              new PrefixCodeRange(18, 2),
              new PrefixCodeRange(22, 3),
              new PrefixCodeRange(30, 3),
              new PrefixCodeRange(38, 4),
              new PrefixCodeRange(54, 4),
              new PrefixCodeRange(70, 5),
              new PrefixCodeRange(102, 5),
              new PrefixCodeRange(134, 6),
              new PrefixCodeRange(198, 7),
              new PrefixCodeRange(326, 8),
              new PrefixCodeRange(582, 9),
              new PrefixCodeRange(1094, 10),
              new PrefixCodeRange(2118, 24)
            ];
            exports2.kInsertRangeLut = [0, 0, 8, 8, 0, 16, 8, 16, 16];
            exports2.kCopyRangeLut = [0, 8, 0, 8, 16, 0, 16, 8, 16];
          },
          {}
        ],
        10: [
          function(require2, module2, exports2) {
            function BrotliInput(buffer) {
              this.buffer = buffer;
              this.pos = 0;
            }
            BrotliInput.prototype.read = function(buf, i2, count) {
              if (this.pos + count > this.buffer.length) {
                count = this.buffer.length - this.pos;
              }
              for (var p3 = 0; p3 < count; p3++)
                buf[i2 + p3] = this.buffer[this.pos + p3];
              this.pos += count;
              return count;
            };
            exports2.BrotliInput = BrotliInput;
            function BrotliOutput(buf) {
              this.buffer = buf;
              this.pos = 0;
            }
            BrotliOutput.prototype.write = function(buf, count) {
              if (this.pos + count > this.buffer.length)
                throw new Error(
                  "Output buffer is not large enough"
                );
              this.buffer.set(buf.subarray(0, count), this.pos);
              this.pos += count;
              return count;
            };
            exports2.BrotliOutput = BrotliOutput;
          },
          {}
        ],
        11: [
          function(require2, module2, exports2) {
            var BrotliDictionary = require2("./dictionary");
            var kIdentity = 0;
            var kOmitLast1 = 1;
            var kOmitLast2 = 2;
            var kOmitLast3 = 3;
            var kOmitLast4 = 4;
            var kOmitLast5 = 5;
            var kOmitLast6 = 6;
            var kOmitLast7 = 7;
            var kOmitLast8 = 8;
            var kOmitLast9 = 9;
            var kUppercaseFirst = 10;
            var kUppercaseAll = 11;
            var kOmitFirst1 = 12;
            var kOmitFirst2 = 13;
            var kOmitFirst3 = 14;
            var kOmitFirst4 = 15;
            var kOmitFirst5 = 16;
            var kOmitFirst6 = 17;
            var kOmitFirst7 = 18;
            var kOmitFirst8 = 19;
            var kOmitFirst9 = 20;
            function Transform(prefix2, transform, suffix) {
              this.prefix = new Uint8Array(prefix2.length);
              this.transform = transform;
              this.suffix = new Uint8Array(suffix.length);
              for (var i2 = 0; i2 < prefix2.length; i2++)
                this.prefix[i2] = prefix2.charCodeAt(i2);
              for (var i2 = 0; i2 < suffix.length; i2++)
                this.suffix[i2] = suffix.charCodeAt(i2);
            }
            var kTransforms = [
              new Transform("", kIdentity, ""),
              new Transform("", kIdentity, " "),
              new Transform(" ", kIdentity, " "),
              new Transform("", kOmitFirst1, ""),
              new Transform("", kUppercaseFirst, " "),
              new Transform("", kIdentity, " the "),
              new Transform(" ", kIdentity, ""),
              new Transform("s ", kIdentity, " "),
              new Transform("", kIdentity, " of "),
              new Transform("", kUppercaseFirst, ""),
              new Transform("", kIdentity, " and "),
              new Transform("", kOmitFirst2, ""),
              new Transform("", kOmitLast1, ""),
              new Transform(", ", kIdentity, " "),
              new Transform("", kIdentity, ", "),
              new Transform(" ", kUppercaseFirst, " "),
              new Transform("", kIdentity, " in "),
              new Transform("", kIdentity, " to "),
              new Transform("e ", kIdentity, " "),
              new Transform("", kIdentity, '"'),
              new Transform("", kIdentity, "."),
              new Transform("", kIdentity, '">'),
              new Transform("", kIdentity, "\n"),
              new Transform("", kOmitLast3, ""),
              new Transform("", kIdentity, "]"),
              new Transform("", kIdentity, " for "),
              new Transform("", kOmitFirst3, ""),
              new Transform("", kOmitLast2, ""),
              new Transform("", kIdentity, " a "),
              new Transform("", kIdentity, " that "),
              new Transform(" ", kUppercaseFirst, ""),
              new Transform("", kIdentity, ". "),
              new Transform(".", kIdentity, ""),
              new Transform(" ", kIdentity, ", "),
              new Transform("", kOmitFirst4, ""),
              new Transform("", kIdentity, " with "),
              new Transform("", kIdentity, "'"),
              new Transform("", kIdentity, " from "),
              new Transform("", kIdentity, " by "),
              new Transform("", kOmitFirst5, ""),
              new Transform("", kOmitFirst6, ""),
              new Transform(" the ", kIdentity, ""),
              new Transform("", kOmitLast4, ""),
              new Transform("", kIdentity, ". The "),
              new Transform("", kUppercaseAll, ""),
              new Transform("", kIdentity, " on "),
              new Transform("", kIdentity, " as "),
              new Transform("", kIdentity, " is "),
              new Transform("", kOmitLast7, ""),
              new Transform("", kOmitLast1, "ing "),
              new Transform("", kIdentity, "\n	"),
              new Transform("", kIdentity, ":"),
              new Transform(" ", kIdentity, ". "),
              new Transform("", kIdentity, "ed "),
              new Transform("", kOmitFirst9, ""),
              new Transform("", kOmitFirst7, ""),
              new Transform("", kOmitLast6, ""),
              new Transform("", kIdentity, "("),
              new Transform("", kUppercaseFirst, ", "),
              new Transform("", kOmitLast8, ""),
              new Transform("", kIdentity, " at "),
              new Transform("", kIdentity, "ly "),
              new Transform(" the ", kIdentity, " of "),
              new Transform("", kOmitLast5, ""),
              new Transform("", kOmitLast9, ""),
              new Transform(" ", kUppercaseFirst, ", "),
              new Transform("", kUppercaseFirst, '"'),
              new Transform(".", kIdentity, "("),
              new Transform("", kUppercaseAll, " "),
              new Transform("", kUppercaseFirst, '">'),
              new Transform("", kIdentity, '="'),
              new Transform(" ", kIdentity, "."),
              new Transform(".com/", kIdentity, ""),
              new Transform(" the ", kIdentity, " of the "),
              new Transform("", kUppercaseFirst, "'"),
              new Transform("", kIdentity, ". This "),
              new Transform("", kIdentity, ","),
              new Transform(".", kIdentity, " "),
              new Transform("", kUppercaseFirst, "("),
              new Transform("", kUppercaseFirst, "."),
              new Transform("", kIdentity, " not "),
              new Transform(" ", kIdentity, '="'),
              new Transform("", kIdentity, "er "),
              new Transform(" ", kUppercaseAll, " "),
              new Transform("", kIdentity, "al "),
              new Transform(" ", kUppercaseAll, ""),
              new Transform("", kIdentity, "='"),
              new Transform("", kUppercaseAll, '"'),
              new Transform("", kUppercaseFirst, ". "),
              new Transform(" ", kIdentity, "("),
              new Transform("", kIdentity, "ful "),
              new Transform(" ", kUppercaseFirst, ". "),
              new Transform("", kIdentity, "ive "),
              new Transform("", kIdentity, "less "),
              new Transform("", kUppercaseAll, "'"),
              new Transform("", kIdentity, "est "),
              new Transform(" ", kUppercaseFirst, "."),
              new Transform("", kUppercaseAll, '">'),
              new Transform(" ", kIdentity, "='"),
              new Transform("", kUppercaseFirst, ","),
              new Transform("", kIdentity, "ize "),
              new Transform("", kUppercaseAll, "."),
              new Transform("\xC2\xA0", kIdentity, ""),
              new Transform(" ", kIdentity, ","),
              new Transform("", kUppercaseFirst, '="'),
              new Transform("", kUppercaseAll, '="'),
              new Transform("", kIdentity, "ous "),
              new Transform("", kUppercaseAll, ", "),
              new Transform("", kUppercaseFirst, "='"),
              new Transform(" ", kUppercaseFirst, ","),
              new Transform(" ", kUppercaseAll, '="'),
              new Transform(" ", kUppercaseAll, ", "),
              new Transform("", kUppercaseAll, ","),
              new Transform("", kUppercaseAll, "("),
              new Transform("", kUppercaseAll, ". "),
              new Transform(" ", kUppercaseAll, "."),
              new Transform("", kUppercaseAll, "='"),
              new Transform(" ", kUppercaseAll, ". "),
              new Transform(" ", kUppercaseFirst, '="'),
              new Transform(" ", kUppercaseAll, "='"),
              new Transform(" ", kUppercaseFirst, "='")
            ];
            exports2.kTransforms = kTransforms;
            exports2.kNumTransforms = kTransforms.length;
            function ToUpperCase(p3, i2) {
              if (p3[i2] < 192) {
                if (p3[i2] >= 97 && p3[i2] <= 122) {
                  p3[i2] ^= 32;
                }
                return 1;
              }
              if (p3[i2] < 224) {
                p3[i2 + 1] ^= 32;
                return 2;
              }
              p3[i2 + 2] ^= 5;
              return 3;
            }
            exports2.transformDictionaryWord = function(dst, idx, word, len, transform) {
              var prefix2 = kTransforms[transform].prefix;
              var suffix = kTransforms[transform].suffix;
              var t3 = kTransforms[transform].transform;
              var skip = t3 < kOmitFirst1 ? 0 : t3 - (kOmitFirst1 - 1);
              var i2 = 0;
              var start_idx = idx;
              var uppercase;
              if (skip > len) {
                skip = len;
              }
              var prefix_pos = 0;
              while (prefix_pos < prefix2.length) {
                dst[idx++] = prefix2[prefix_pos++];
              }
              word += skip;
              len -= skip;
              if (t3 <= kOmitLast9) {
                len -= t3;
              }
              for (i2 = 0; i2 < len; i2++) {
                dst[idx++] = BrotliDictionary.dictionary[word + i2];
              }
              uppercase = idx - len;
              if (t3 === kUppercaseFirst) {
                ToUpperCase(dst, uppercase);
              } else if (t3 === kUppercaseAll) {
                while (len > 0) {
                  var step = ToUpperCase(dst, uppercase);
                  uppercase += step;
                  len -= step;
                }
              }
              var suffix_pos = 0;
              while (suffix_pos < suffix.length) {
                dst[idx++] = suffix[suffix_pos++];
              }
              return idx - start_idx;
            };
          },
          { "./dictionary": 6 }
        ],
        12: [
          function(require2, module2, exports2) {
            module2.exports = require2("./dec/decode").BrotliDecompressBuffer;
          },
          { "./dec/decode": 3 }
        ]
      },
      {},
      [12]
    )(12);
  })();

  // packages/global-styles-ui/build-module/font-library/lib/inflate.mjs
  var __require3 = /* @__PURE__ */ ((x2) => typeof __require !== "undefined" ? __require : typeof Proxy !== "undefined" ? new Proxy(x2, {
    get: (a2, b2) => (typeof __require !== "undefined" ? __require : a2)[b2]
  }) : x2)(function(x2) {
    if (typeof __require !== "undefined") return __require.apply(this, arguments);
    throw Error('Dynamic require of "' + x2 + '" is not supported');
  });
  var inflate_default = (function() {
    var define, module, exports;
    return (/* @__PURE__ */ (function() {
      function r3(e2, n2, t3) {
        function o3(i22, f2) {
          if (!n2[i22]) {
            if (!e2[i22]) {
              var c6 = "function" == typeof __require3 && __require3;
              if (!f2 && c6) return c6(i22, true);
              if (u2) return u2(i22, true);
              var a2 = new Error("Cannot find module '" + i22 + "'");
              throw a2.code = "MODULE_NOT_FOUND", a2;
            }
            var p3 = n2[i22] = { exports: {} };
            e2[i22][0].call(
              p3.exports,
              function(r22) {
                var n22 = e2[i22][1][r22];
                return o3(n22 || r22);
              },
              p3,
              p3.exports,
              r3,
              e2,
              n2,
              t3
            );
          }
          return n2[i22].exports;
        }
        for (var u2 = "function" == typeof __require3 && __require3, i2 = 0; i2 < t3.length; i2++)
          o3(t3[i2]);
        return o3;
      }
      return r3;
    })())(
      {
        1: [
          function(require2, module2, exports2) {
            "use strict";
            var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined";
            function _has(obj, key) {
              return Object.prototype.hasOwnProperty.call(obj, key);
            }
            exports2.assign = function(obj) {
              var sources = Array.prototype.slice.call(
                arguments,
                1
              );
              while (sources.length) {
                var source = sources.shift();
                if (!source) {
                  continue;
                }
                if (typeof source !== "object") {
                  throw new TypeError(
                    source + "must be non-object"
                  );
                }
                for (var p3 in source) {
                  if (_has(source, p3)) {
                    obj[p3] = source[p3];
                  }
                }
              }
              return obj;
            };
            exports2.shrinkBuf = function(buf, size4) {
              if (buf.length === size4) {
                return buf;
              }
              if (buf.subarray) {
                return buf.subarray(0, size4);
              }
              buf.length = size4;
              return buf;
            };
            var fnTyped = {
              arraySet: function(dest, src, src_offs, len, dest_offs) {
                if (src.subarray && dest.subarray) {
                  dest.set(
                    src.subarray(src_offs, src_offs + len),
                    dest_offs
                  );
                  return;
                }
                for (var i2 = 0; i2 < len; i2++) {
                  dest[dest_offs + i2] = src[src_offs + i2];
                }
              },
              // Join array of chunks to single array.
              flattenChunks: function(chunks) {
                var i2, l2, len, pos, chunk2, result;
                len = 0;
                for (i2 = 0, l2 = chunks.length; i2 < l2; i2++) {
                  len += chunks[i2].length;
                }
                result = new Uint8Array(len);
                pos = 0;
                for (i2 = 0, l2 = chunks.length; i2 < l2; i2++) {
                  chunk2 = chunks[i2];
                  result.set(chunk2, pos);
                  pos += chunk2.length;
                }
                return result;
              }
            };
            var fnUntyped = {
              arraySet: function(dest, src, src_offs, len, dest_offs) {
                for (var i2 = 0; i2 < len; i2++) {
                  dest[dest_offs + i2] = src[src_offs + i2];
                }
              },
              // Join array of chunks to single array.
              flattenChunks: function(chunks) {
                return [].concat.apply([], chunks);
              }
            };
            exports2.setTyped = function(on) {
              if (on) {
                exports2.Buf8 = Uint8Array;
                exports2.Buf16 = Uint16Array;
                exports2.Buf32 = Int32Array;
                exports2.assign(exports2, fnTyped);
              } else {
                exports2.Buf8 = Array;
                exports2.Buf16 = Array;
                exports2.Buf32 = Array;
                exports2.assign(exports2, fnUntyped);
              }
            };
            exports2.setTyped(TYPED_OK);
          },
          {}
        ],
        2: [
          function(require2, module2, exports2) {
            "use strict";
            var utils = require2("./common");
            var STR_APPLY_OK = true;
            var STR_APPLY_UIA_OK = true;
            try {
              String.fromCharCode.apply(null, [0]);
            } catch (__149) {
              STR_APPLY_OK = false;
            }
            try {
              String.fromCharCode.apply(null, new Uint8Array(1));
            } catch (__149) {
              STR_APPLY_UIA_OK = false;
            }
            var _utf8len = new utils.Buf8(256);
            for (var q = 0; q < 256; q++) {
              _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
            }
            _utf8len[254] = _utf8len[254] = 1;
            exports2.string2buf = function(str) {
              var buf, c6, c22, m_pos, i2, str_len = str.length, buf_len = 0;
              for (m_pos = 0; m_pos < str_len; m_pos++) {
                c6 = str.charCodeAt(m_pos);
                if ((c6 & 64512) === 55296 && m_pos + 1 < str_len) {
                  c22 = str.charCodeAt(m_pos + 1);
                  if ((c22 & 64512) === 56320) {
                    c6 = 65536 + (c6 - 55296 << 10) + (c22 - 56320);
                    m_pos++;
                  }
                }
                buf_len += c6 < 128 ? 1 : c6 < 2048 ? 2 : c6 < 65536 ? 3 : 4;
              }
              buf = new utils.Buf8(buf_len);
              for (i2 = 0, m_pos = 0; i2 < buf_len; m_pos++) {
                c6 = str.charCodeAt(m_pos);
                if ((c6 & 64512) === 55296 && m_pos + 1 < str_len) {
                  c22 = str.charCodeAt(m_pos + 1);
                  if ((c22 & 64512) === 56320) {
                    c6 = 65536 + (c6 - 55296 << 10) + (c22 - 56320);
                    m_pos++;
                  }
                }
                if (c6 < 128) {
                  buf[i2++] = c6;
                } else if (c6 < 2048) {
                  buf[i2++] = 192 | c6 >>> 6;
                  buf[i2++] = 128 | c6 & 63;
                } else if (c6 < 65536) {
                  buf[i2++] = 224 | c6 >>> 12;
                  buf[i2++] = 128 | c6 >>> 6 & 63;
                  buf[i2++] = 128 | c6 & 63;
                } else {
                  buf[i2++] = 240 | c6 >>> 18;
                  buf[i2++] = 128 | c6 >>> 12 & 63;
                  buf[i2++] = 128 | c6 >>> 6 & 63;
                  buf[i2++] = 128 | c6 & 63;
                }
              }
              return buf;
            };
            function buf2binstring(buf, len) {
              if (len < 65534) {
                if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {
                  return String.fromCharCode.apply(
                    null,
                    utils.shrinkBuf(buf, len)
                  );
                }
              }
              var result = "";
              for (var i2 = 0; i2 < len; i2++) {
                result += String.fromCharCode(buf[i2]);
              }
              return result;
            }
            exports2.buf2binstring = function(buf) {
              return buf2binstring(buf, buf.length);
            };
            exports2.binstring2buf = function(str) {
              var buf = new utils.Buf8(str.length);
              for (var i2 = 0, len = buf.length; i2 < len; i2++) {
                buf[i2] = str.charCodeAt(i2);
              }
              return buf;
            };
            exports2.buf2string = function(buf, max2) {
              var i2, out, c6, c_len;
              var len = max2 || buf.length;
              var utf16buf = new Array(len * 2);
              for (out = 0, i2 = 0; i2 < len; ) {
                c6 = buf[i2++];
                if (c6 < 128) {
                  utf16buf[out++] = c6;
                  continue;
                }
                c_len = _utf8len[c6];
                if (c_len > 4) {
                  utf16buf[out++] = 65533;
                  i2 += c_len - 1;
                  continue;
                }
                c6 &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7;
                while (c_len > 1 && i2 < len) {
                  c6 = c6 << 6 | buf[i2++] & 63;
                  c_len--;
                }
                if (c_len > 1) {
                  utf16buf[out++] = 65533;
                  continue;
                }
                if (c6 < 65536) {
                  utf16buf[out++] = c6;
                } else {
                  c6 -= 65536;
                  utf16buf[out++] = 55296 | c6 >> 10 & 1023;
                  utf16buf[out++] = 56320 | c6 & 1023;
                }
              }
              return buf2binstring(utf16buf, out);
            };
            exports2.utf8border = function(buf, max2) {
              var pos;
              max2 = max2 || buf.length;
              if (max2 > buf.length) {
                max2 = buf.length;
              }
              pos = max2 - 1;
              while (pos >= 0 && (buf[pos] & 192) === 128) {
                pos--;
              }
              if (pos < 0) {
                return max2;
              }
              if (pos === 0) {
                return max2;
              }
              return pos + _utf8len[buf[pos]] > max2 ? pos : max2;
            };
          },
          { "./common": 1 }
        ],
        3: [
          function(require2, module2, exports2) {
            "use strict";
            function adler32(adler, buf, len, pos) {
              var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n2 = 0;
              while (len !== 0) {
                n2 = len > 2e3 ? 2e3 : len;
                len -= n2;
                do {
                  s1 = s1 + buf[pos++] | 0;
                  s2 = s2 + s1 | 0;
                } while (--n2);
                s1 %= 65521;
                s2 %= 65521;
              }
              return s1 | s2 << 16 | 0;
            }
            module2.exports = adler32;
          },
          {}
        ],
        4: [
          function(require2, module2, exports2) {
            "use strict";
            module2.exports = {
              /* Allowed flush values; see deflate() and inflate() below for details */
              Z_NO_FLUSH: 0,
              Z_PARTIAL_FLUSH: 1,
              Z_SYNC_FLUSH: 2,
              Z_FULL_FLUSH: 3,
              Z_FINISH: 4,
              Z_BLOCK: 5,
              Z_TREES: 6,
              /* Return codes for the compression/decompression functions. Negative values
               * are errors, positive values are used for special but normal events.
               */
              Z_OK: 0,
              Z_STREAM_END: 1,
              Z_NEED_DICT: 2,
              Z_ERRNO: -1,
              Z_STREAM_ERROR: -2,
              Z_DATA_ERROR: -3,
              //Z_MEM_ERROR:     -4,
              Z_BUF_ERROR: -5,
              //Z_VERSION_ERROR: -6,
              /* compression levels */
              Z_NO_COMPRESSION: 0,
              Z_BEST_SPEED: 1,
              Z_BEST_COMPRESSION: 9,
              Z_DEFAULT_COMPRESSION: -1,
              Z_FILTERED: 1,
              Z_HUFFMAN_ONLY: 2,
              Z_RLE: 3,
              Z_FIXED: 4,
              Z_DEFAULT_STRATEGY: 0,
              /* Possible values of the data_type field (though see inflate()) */
              Z_BINARY: 0,
              Z_TEXT: 1,
              //Z_ASCII:                1, // = Z_TEXT (deprecated)
              Z_UNKNOWN: 2,
              /* The deflate compression method */
              Z_DEFLATED: 8
              //Z_NULL:                 null // Use -1 or null inline, depending on var type
            };
          },
          {}
        ],
        5: [
          function(require2, module2, exports2) {
            "use strict";
            function makeTable() {
              var c6, table = [];
              for (var n2 = 0; n2 < 256; n2++) {
                c6 = n2;
                for (var k2 = 0; k2 < 8; k2++) {
                  c6 = c6 & 1 ? 3988292384 ^ c6 >>> 1 : c6 >>> 1;
                }
                table[n2] = c6;
              }
              return table;
            }
            var crcTable = makeTable();
            function crc32(crc, buf, len, pos) {
              var t3 = crcTable, end = pos + len;
              crc ^= -1;
              for (var i2 = pos; i2 < end; i2++) {
                crc = crc >>> 8 ^ t3[(crc ^ buf[i2]) & 255];
              }
              return crc ^ -1;
            }
            module2.exports = crc32;
          },
          {}
        ],
        6: [
          function(require2, module2, exports2) {
            "use strict";
            function GZheader() {
              this.text = 0;
              this.time = 0;
              this.xflags = 0;
              this.os = 0;
              this.extra = null;
              this.extra_len = 0;
              this.name = "";
              this.comment = "";
              this.hcrc = 0;
              this.done = false;
            }
            module2.exports = GZheader;
          },
          {}
        ],
        7: [
          function(require2, module2, exports2) {
            "use strict";
            var BAD = 30;
            var TYPE = 12;
            module2.exports = function inflate_fast(strm, start2) {
              var state;
              var _in;
              var last;
              var _out;
              var beg;
              var end;
              var dmax;
              var wsize;
              var whave;
              var wnext;
              var s_window;
              var hold;
              var bits;
              var lcode;
              var dcode;
              var lmask;
              var dmask;
              var here;
              var op;
              var len;
              var dist;
              var from;
              var from_source;
              var input, output;
              state = strm.state;
              _in = strm.next_in;
              input = strm.input;
              last = _in + (strm.avail_in - 5);
              _out = strm.next_out;
              output = strm.output;
              beg = _out - (start2 - strm.avail_out);
              end = _out + (strm.avail_out - 257);
              dmax = state.dmax;
              wsize = state.wsize;
              whave = state.whave;
              wnext = state.wnext;
              s_window = state.window;
              hold = state.hold;
              bits = state.bits;
              lcode = state.lencode;
              dcode = state.distcode;
              lmask = (1 << state.lenbits) - 1;
              dmask = (1 << state.distbits) - 1;
              top: do {
                if (bits < 15) {
                  hold += input[_in++] << bits;
                  bits += 8;
                  hold += input[_in++] << bits;
                  bits += 8;
                }
                here = lcode[hold & lmask];
                dolen: for (; ; ) {
                  op = here >>> 24;
                  hold >>>= op;
                  bits -= op;
                  op = here >>> 16 & 255;
                  if (op === 0) {
                    output[_out++] = here & 65535;
                  } else if (op & 16) {
                    len = here & 65535;
                    op &= 15;
                    if (op) {
                      if (bits < op) {
                        hold += input[_in++] << bits;
                        bits += 8;
                      }
                      len += hold & (1 << op) - 1;
                      hold >>>= op;
                      bits -= op;
                    }
                    if (bits < 15) {
                      hold += input[_in++] << bits;
                      bits += 8;
                      hold += input[_in++] << bits;
                      bits += 8;
                    }
                    here = dcode[hold & dmask];
                    dodist: for (; ; ) {
                      op = here >>> 24;
                      hold >>>= op;
                      bits -= op;
                      op = here >>> 16 & 255;
                      if (op & 16) {
                        dist = here & 65535;
                        op &= 15;
                        if (bits < op) {
                          hold += input[_in++] << bits;
                          bits += 8;
                          if (bits < op) {
                            hold += input[_in++] << bits;
                            bits += 8;
                          }
                        }
                        dist += hold & (1 << op) - 1;
                        if (dist > dmax) {
                          strm.msg = "invalid distance too far back";
                          state.mode = BAD;
                          break top;
                        }
                        hold >>>= op;
                        bits -= op;
                        op = _out - beg;
                        if (dist > op) {
                          op = dist - op;
                          if (op > whave) {
                            if (state.sane) {
                              strm.msg = "invalid distance too far back";
                              state.mode = BAD;
                              break top;
                            }
                          }
                          from = 0;
                          from_source = s_window;
                          if (wnext === 0) {
                            from += wsize - op;
                            if (op < len) {
                              len -= op;
                              do {
                                output[_out++] = s_window[from++];
                              } while (--op);
                              from = _out - dist;
                              from_source = output;
                            }
                          } else if (wnext < op) {
                            from += wsize + wnext - op;
                            op -= wnext;
                            if (op < len) {
                              len -= op;
                              do {
                                output[_out++] = s_window[from++];
                              } while (--op);
                              from = 0;
                              if (wnext < len) {
                                op = wnext;
                                len -= op;
                                do {
                                  output[_out++] = s_window[from++];
                                } while (--op);
                                from = _out - dist;
                                from_source = output;
                              }
                            }
                          } else {
                            from += wnext - op;
                            if (op < len) {
                              len -= op;
                              do {
                                output[_out++] = s_window[from++];
                              } while (--op);
                              from = _out - dist;
                              from_source = output;
                            }
                          }
                          while (len > 2) {
                            output[_out++] = from_source[from++];
                            output[_out++] = from_source[from++];
                            output[_out++] = from_source[from++];
                            len -= 3;
                          }
                          if (len) {
                            output[_out++] = from_source[from++];
                            if (len > 1) {
                              output[_out++] = from_source[from++];
                            }
                          }
                        } else {
                          from = _out - dist;
                          do {
                            output[_out++] = output[from++];
                            output[_out++] = output[from++];
                            output[_out++] = output[from++];
                            len -= 3;
                          } while (len > 2);
                          if (len) {
                            output[_out++] = output[from++];
                            if (len > 1) {
                              output[_out++] = output[from++];
                            }
                          }
                        }
                      } else if ((op & 64) === 0) {
                        here = dcode[(here & 65535) + (hold & (1 << op) - 1)];
                        continue dodist;
                      } else {
                        strm.msg = "invalid distance code";
                        state.mode = BAD;
                        break top;
                      }
                      break;
                    }
                  } else if ((op & 64) === 0) {
                    here = lcode[(here & 65535) + (hold & (1 << op) - 1)];
                    continue dolen;
                  } else if (op & 32) {
                    state.mode = TYPE;
                    break top;
                  } else {
                    strm.msg = "invalid literal/length code";
                    state.mode = BAD;
                    break top;
                  }
                  break;
                }
              } while (_in < last && _out < end);
              len = bits >> 3;
              _in -= len;
              bits -= len << 3;
              hold &= (1 << bits) - 1;
              strm.next_in = _in;
              strm.next_out = _out;
              strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last);
              strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end);
              state.hold = hold;
              state.bits = bits;
              return;
            };
          },
          {}
        ],
        8: [
          function(require2, module2, exports2) {
            "use strict";
            var utils = require2("../utils/common");
            var adler32 = require2("./adler32");
            var crc32 = require2("./crc32");
            var inflate_fast = require2("./inffast");
            var inflate_table = require2("./inftrees");
            var CODES = 0;
            var LENS = 1;
            var DISTS = 2;
            var Z_FINISH = 4;
            var Z_BLOCK = 5;
            var Z_TREES = 6;
            var Z_OK = 0;
            var Z_STREAM_END = 1;
            var Z_NEED_DICT = 2;
            var Z_STREAM_ERROR = -2;
            var Z_DATA_ERROR = -3;
            var Z_MEM_ERROR = -4;
            var Z_BUF_ERROR = -5;
            var Z_DEFLATED = 8;
            var HEAD = 1;
            var FLAGS = 2;
            var TIME = 3;
            var OS = 4;
            var EXLEN = 5;
            var EXTRA = 6;
            var NAME = 7;
            var COMMENT = 8;
            var HCRC = 9;
            var DICTID = 10;
            var DICT = 11;
            var TYPE = 12;
            var TYPEDO = 13;
            var STORED = 14;
            var COPY_ = 15;
            var COPY = 16;
            var TABLE = 17;
            var LENLENS = 18;
            var CODELENS = 19;
            var LEN_ = 20;
            var LEN = 21;
            var LENEXT = 22;
            var DIST = 23;
            var DISTEXT = 24;
            var MATCH = 25;
            var LIT = 26;
            var CHECK = 27;
            var LENGTH = 28;
            var DONE = 29;
            var BAD = 30;
            var MEM = 31;
            var SYNC = 32;
            var ENOUGH_LENS = 852;
            var ENOUGH_DISTS = 592;
            var MAX_WBITS = 15;
            var DEF_WBITS = MAX_WBITS;
            function zswap32(q) {
              return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24);
            }
            function InflateState() {
              this.mode = 0;
              this.last = false;
              this.wrap = 0;
              this.havedict = false;
              this.flags = 0;
              this.dmax = 0;
              this.check = 0;
              this.total = 0;
              this.head = null;
              this.wbits = 0;
              this.wsize = 0;
              this.whave = 0;
              this.wnext = 0;
              this.window = null;
              this.hold = 0;
              this.bits = 0;
              this.length = 0;
              this.offset = 0;
              this.extra = 0;
              this.lencode = null;
              this.distcode = null;
              this.lenbits = 0;
              this.distbits = 0;
              this.ncode = 0;
              this.nlen = 0;
              this.ndist = 0;
              this.have = 0;
              this.next = null;
              this.lens = new utils.Buf16(
                320
              );
              this.work = new utils.Buf16(
                288
              );
              this.lendyn = null;
              this.distdyn = null;
              this.sane = 0;
              this.back = 0;
              this.was = 0;
            }
            function inflateResetKeep(strm) {
              var state;
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              state = strm.state;
              strm.total_in = strm.total_out = state.total = 0;
              strm.msg = "";
              if (state.wrap) {
                strm.adler = state.wrap & 1;
              }
              state.mode = HEAD;
              state.last = 0;
              state.havedict = 0;
              state.dmax = 32768;
              state.head = null;
              state.hold = 0;
              state.bits = 0;
              state.lencode = state.lendyn = new utils.Buf32(
                ENOUGH_LENS
              );
              state.distcode = state.distdyn = new utils.Buf32(
                ENOUGH_DISTS
              );
              state.sane = 1;
              state.back = -1;
              return Z_OK;
            }
            function inflateReset(strm) {
              var state;
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              state = strm.state;
              state.wsize = 0;
              state.whave = 0;
              state.wnext = 0;
              return inflateResetKeep(strm);
            }
            function inflateReset2(strm, windowBits) {
              var wrap;
              var state;
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              state = strm.state;
              if (windowBits < 0) {
                wrap = 0;
                windowBits = -windowBits;
              } else {
                wrap = (windowBits >> 4) + 1;
                if (windowBits < 48) {
                  windowBits &= 15;
                }
              }
              if (windowBits && (windowBits < 8 || windowBits > 15)) {
                return Z_STREAM_ERROR;
              }
              if (state.window !== null && state.wbits !== windowBits) {
                state.window = null;
              }
              state.wrap = wrap;
              state.wbits = windowBits;
              return inflateReset(strm);
            }
            function inflateInit2(strm, windowBits) {
              var ret;
              var state;
              if (!strm) {
                return Z_STREAM_ERROR;
              }
              state = new InflateState();
              strm.state = state;
              state.window = null;
              ret = inflateReset2(strm, windowBits);
              if (ret !== Z_OK) {
                strm.state = null;
              }
              return ret;
            }
            function inflateInit(strm) {
              return inflateInit2(strm, DEF_WBITS);
            }
            var virgin = true;
            var lenfix, distfix;
            function fixedtables(state) {
              if (virgin) {
                var sym;
                lenfix = new utils.Buf32(512);
                distfix = new utils.Buf32(32);
                sym = 0;
                while (sym < 144) {
                  state.lens[sym++] = 8;
                }
                while (sym < 256) {
                  state.lens[sym++] = 9;
                }
                while (sym < 280) {
                  state.lens[sym++] = 7;
                }
                while (sym < 288) {
                  state.lens[sym++] = 8;
                }
                inflate_table(
                  LENS,
                  state.lens,
                  0,
                  288,
                  lenfix,
                  0,
                  state.work,
                  { bits: 9 }
                );
                sym = 0;
                while (sym < 32) {
                  state.lens[sym++] = 5;
                }
                inflate_table(
                  DISTS,
                  state.lens,
                  0,
                  32,
                  distfix,
                  0,
                  state.work,
                  { bits: 5 }
                );
                virgin = false;
              }
              state.lencode = lenfix;
              state.lenbits = 9;
              state.distcode = distfix;
              state.distbits = 5;
            }
            function updatewindow(strm, src, end, copy) {
              var dist;
              var state = strm.state;
              if (state.window === null) {
                state.wsize = 1 << state.wbits;
                state.wnext = 0;
                state.whave = 0;
                state.window = new utils.Buf8(state.wsize);
              }
              if (copy >= state.wsize) {
                utils.arraySet(
                  state.window,
                  src,
                  end - state.wsize,
                  state.wsize,
                  0
                );
                state.wnext = 0;
                state.whave = state.wsize;
              } else {
                dist = state.wsize - state.wnext;
                if (dist > copy) {
                  dist = copy;
                }
                utils.arraySet(
                  state.window,
                  src,
                  end - copy,
                  dist,
                  state.wnext
                );
                copy -= dist;
                if (copy) {
                  utils.arraySet(
                    state.window,
                    src,
                    end - copy,
                    copy,
                    0
                  );
                  state.wnext = copy;
                  state.whave = state.wsize;
                } else {
                  state.wnext += dist;
                  if (state.wnext === state.wsize) {
                    state.wnext = 0;
                  }
                  if (state.whave < state.wsize) {
                    state.whave += dist;
                  }
                }
              }
              return 0;
            }
            function inflate(strm, flush2) {
              var state;
              var input, output;
              var next;
              var put;
              var have, left;
              var hold;
              var bits;
              var _in, _out;
              var copy;
              var from;
              var from_source;
              var here = 0;
              var here_bits, here_op, here_val;
              var last_bits, last_op, last_val;
              var len;
              var ret;
              var hbuf = new utils.Buf8(
                4
              );
              var opts;
              var n2;
              var order = (
                /* permutation of code lengths */
                [
                  16,
                  17,
                  18,
                  0,
                  8,
                  7,
                  9,
                  6,
                  10,
                  5,
                  11,
                  4,
                  12,
                  3,
                  13,
                  2,
                  14,
                  1,
                  15
                ]
              );
              if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) {
                return Z_STREAM_ERROR;
              }
              state = strm.state;
              if (state.mode === TYPE) {
                state.mode = TYPEDO;
              }
              put = strm.next_out;
              output = strm.output;
              left = strm.avail_out;
              next = strm.next_in;
              input = strm.input;
              have = strm.avail_in;
              hold = state.hold;
              bits = state.bits;
              _in = have;
              _out = left;
              ret = Z_OK;
              inf_leave: for (; ; ) {
                switch (state.mode) {
                  case HEAD:
                    if (state.wrap === 0) {
                      state.mode = TYPEDO;
                      break;
                    }
                    while (bits < 16) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    if (state.wrap & 2 && hold === 35615) {
                      state.check = 0;
                      hbuf[0] = hold & 255;
                      hbuf[1] = hold >>> 8 & 255;
                      state.check = crc32(
                        state.check,
                        hbuf,
                        2,
                        0
                      );
                      hold = 0;
                      bits = 0;
                      state.mode = FLAGS;
                      break;
                    }
                    state.flags = 0;
                    if (state.head) {
                      state.head.done = false;
                    }
                    if (!(state.wrap & 1) || (((hold & 255) << 8) + (hold >> 8)) % 31) {
                      strm.msg = "incorrect header check";
                      state.mode = BAD;
                      break;
                    }
                    if ((hold & 15) !== Z_DEFLATED) {
                      strm.msg = "unknown compression method";
                      state.mode = BAD;
                      break;
                    }
                    hold >>>= 4;
                    bits -= 4;
                    len = (hold & 15) + 8;
                    if (state.wbits === 0) {
                      state.wbits = len;
                    } else if (len > state.wbits) {
                      strm.msg = "invalid window size";
                      state.mode = BAD;
                      break;
                    }
                    state.dmax = 1 << len;
                    strm.adler = state.check = 1;
                    state.mode = hold & 512 ? DICTID : TYPE;
                    hold = 0;
                    bits = 0;
                    break;
                  case FLAGS:
                    while (bits < 16) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    state.flags = hold;
                    if ((state.flags & 255) !== Z_DEFLATED) {
                      strm.msg = "unknown compression method";
                      state.mode = BAD;
                      break;
                    }
                    if (state.flags & 57344) {
                      strm.msg = "unknown header flags set";
                      state.mode = BAD;
                      break;
                    }
                    if (state.head) {
                      state.head.text = hold >> 8 & 1;
                    }
                    if (state.flags & 512) {
                      hbuf[0] = hold & 255;
                      hbuf[1] = hold >>> 8 & 255;
                      state.check = crc32(
                        state.check,
                        hbuf,
                        2,
                        0
                      );
                    }
                    hold = 0;
                    bits = 0;
                    state.mode = TIME;
                  /* falls through */
                  case TIME:
                    while (bits < 32) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    if (state.head) {
                      state.head.time = hold;
                    }
                    if (state.flags & 512) {
                      hbuf[0] = hold & 255;
                      hbuf[1] = hold >>> 8 & 255;
                      hbuf[2] = hold >>> 16 & 255;
                      hbuf[3] = hold >>> 24 & 255;
                      state.check = crc32(
                        state.check,
                        hbuf,
                        4,
                        0
                      );
                    }
                    hold = 0;
                    bits = 0;
                    state.mode = OS;
                  /* falls through */
                  case OS:
                    while (bits < 16) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    if (state.head) {
                      state.head.xflags = hold & 255;
                      state.head.os = hold >> 8;
                    }
                    if (state.flags & 512) {
                      hbuf[0] = hold & 255;
                      hbuf[1] = hold >>> 8 & 255;
                      state.check = crc32(
                        state.check,
                        hbuf,
                        2,
                        0
                      );
                    }
                    hold = 0;
                    bits = 0;
                    state.mode = EXLEN;
                  /* falls through */
                  case EXLEN:
                    if (state.flags & 1024) {
                      while (bits < 16) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      state.length = hold;
                      if (state.head) {
                        state.head.extra_len = hold;
                      }
                      if (state.flags & 512) {
                        hbuf[0] = hold & 255;
                        hbuf[1] = hold >>> 8 & 255;
                        state.check = crc32(
                          state.check,
                          hbuf,
                          2,
                          0
                        );
                      }
                      hold = 0;
                      bits = 0;
                    } else if (state.head) {
                      state.head.extra = null;
                    }
                    state.mode = EXTRA;
                  /* falls through */
                  case EXTRA:
                    if (state.flags & 1024) {
                      copy = state.length;
                      if (copy > have) {
                        copy = have;
                      }
                      if (copy) {
                        if (state.head) {
                          len = state.head.extra_len - state.length;
                          if (!state.head.extra) {
                            state.head.extra = new Array(
                              state.head.extra_len
                            );
                          }
                          utils.arraySet(
                            state.head.extra,
                            input,
                            next,
                            // extra field is limited to 65536 bytes
                            // - no need for additional size check
                            copy,
                            /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                            len
                          );
                        }
                        if (state.flags & 512) {
                          state.check = crc32(
                            state.check,
                            input,
                            copy,
                            next
                          );
                        }
                        have -= copy;
                        next += copy;
                        state.length -= copy;
                      }
                      if (state.length) {
                        break inf_leave;
                      }
                    }
                    state.length = 0;
                    state.mode = NAME;
                  /* falls through */
                  case NAME:
                    if (state.flags & 2048) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      copy = 0;
                      do {
                        len = input[next + copy++];
                        if (state.head && len && state.length < 65536) {
                          state.head.name += String.fromCharCode(len);
                        }
                      } while (len && copy < have);
                      if (state.flags & 512) {
                        state.check = crc32(
                          state.check,
                          input,
                          copy,
                          next
                        );
                      }
                      have -= copy;
                      next += copy;
                      if (len) {
                        break inf_leave;
                      }
                    } else if (state.head) {
                      state.head.name = null;
                    }
                    state.length = 0;
                    state.mode = COMMENT;
                  /* falls through */
                  case COMMENT:
                    if (state.flags & 4096) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      copy = 0;
                      do {
                        len = input[next + copy++];
                        if (state.head && len && state.length < 65536) {
                          state.head.comment += String.fromCharCode(len);
                        }
                      } while (len && copy < have);
                      if (state.flags & 512) {
                        state.check = crc32(
                          state.check,
                          input,
                          copy,
                          next
                        );
                      }
                      have -= copy;
                      next += copy;
                      if (len) {
                        break inf_leave;
                      }
                    } else if (state.head) {
                      state.head.comment = null;
                    }
                    state.mode = HCRC;
                  /* falls through */
                  case HCRC:
                    if (state.flags & 512) {
                      while (bits < 16) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      if (hold !== (state.check & 65535)) {
                        strm.msg = "header crc mismatch";
                        state.mode = BAD;
                        break;
                      }
                      hold = 0;
                      bits = 0;
                    }
                    if (state.head) {
                      state.head.hcrc = state.flags >> 9 & 1;
                      state.head.done = true;
                    }
                    strm.adler = state.check = 0;
                    state.mode = TYPE;
                    break;
                  case DICTID:
                    while (bits < 32) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    strm.adler = state.check = zswap32(hold);
                    hold = 0;
                    bits = 0;
                    state.mode = DICT;
                  /* falls through */
                  case DICT:
                    if (state.havedict === 0) {
                      strm.next_out = put;
                      strm.avail_out = left;
                      strm.next_in = next;
                      strm.avail_in = have;
                      state.hold = hold;
                      state.bits = bits;
                      return Z_NEED_DICT;
                    }
                    strm.adler = state.check = 1;
                    state.mode = TYPE;
                  /* falls through */
                  case TYPE:
                    if (flush2 === Z_BLOCK || flush2 === Z_TREES) {
                      break inf_leave;
                    }
                  /* falls through */
                  case TYPEDO:
                    if (state.last) {
                      hold >>>= bits & 7;
                      bits -= bits & 7;
                      state.mode = CHECK;
                      break;
                    }
                    while (bits < 3) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    state.last = hold & 1;
                    hold >>>= 1;
                    bits -= 1;
                    switch (hold & 3) {
                      case 0:
                        state.mode = STORED;
                        break;
                      case 1:
                        fixedtables(state);
                        state.mode = LEN_;
                        if (flush2 === Z_TREES) {
                          hold >>>= 2;
                          bits -= 2;
                          break inf_leave;
                        }
                        break;
                      case 2:
                        state.mode = TABLE;
                        break;
                      case 3:
                        strm.msg = "invalid block type";
                        state.mode = BAD;
                    }
                    hold >>>= 2;
                    bits -= 2;
                    break;
                  case STORED:
                    hold >>>= bits & 7;
                    bits -= bits & 7;
                    while (bits < 32) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    if ((hold & 65535) !== (hold >>> 16 ^ 65535)) {
                      strm.msg = "invalid stored block lengths";
                      state.mode = BAD;
                      break;
                    }
                    state.length = hold & 65535;
                    hold = 0;
                    bits = 0;
                    state.mode = COPY_;
                    if (flush2 === Z_TREES) {
                      break inf_leave;
                    }
                  /* falls through */
                  case COPY_:
                    state.mode = COPY;
                  /* falls through */
                  case COPY:
                    copy = state.length;
                    if (copy) {
                      if (copy > have) {
                        copy = have;
                      }
                      if (copy > left) {
                        copy = left;
                      }
                      if (copy === 0) {
                        break inf_leave;
                      }
                      utils.arraySet(
                        output,
                        input,
                        next,
                        copy,
                        put
                      );
                      have -= copy;
                      next += copy;
                      left -= copy;
                      put += copy;
                      state.length -= copy;
                      break;
                    }
                    state.mode = TYPE;
                    break;
                  case TABLE:
                    while (bits < 14) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    state.nlen = (hold & 31) + 257;
                    hold >>>= 5;
                    bits -= 5;
                    state.ndist = (hold & 31) + 1;
                    hold >>>= 5;
                    bits -= 5;
                    state.ncode = (hold & 15) + 4;
                    hold >>>= 4;
                    bits -= 4;
                    if (state.nlen > 286 || state.ndist > 30) {
                      strm.msg = "too many length or distance symbols";
                      state.mode = BAD;
                      break;
                    }
                    state.have = 0;
                    state.mode = LENLENS;
                  /* falls through */
                  case LENLENS:
                    while (state.have < state.ncode) {
                      while (bits < 3) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      state.lens[order[state.have++]] = hold & 7;
                      hold >>>= 3;
                      bits -= 3;
                    }
                    while (state.have < 19) {
                      state.lens[order[state.have++]] = 0;
                    }
                    state.lencode = state.lendyn;
                    state.lenbits = 7;
                    opts = { bits: state.lenbits };
                    ret = inflate_table(
                      CODES,
                      state.lens,
                      0,
                      19,
                      state.lencode,
                      0,
                      state.work,
                      opts
                    );
                    state.lenbits = opts.bits;
                    if (ret) {
                      strm.msg = "invalid code lengths set";
                      state.mode = BAD;
                      break;
                    }
                    state.have = 0;
                    state.mode = CODELENS;
                  /* falls through */
                  case CODELENS:
                    while (state.have < state.nlen + state.ndist) {
                      for (; ; ) {
                        here = state.lencode[hold & (1 << state.lenbits) - 1];
                        here_bits = here >>> 24;
                        here_op = here >>> 16 & 255;
                        here_val = here & 65535;
                        if (here_bits <= bits) {
                          break;
                        }
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      if (here_val < 16) {
                        hold >>>= here_bits;
                        bits -= here_bits;
                        state.lens[state.have++] = here_val;
                      } else {
                        if (here_val === 16) {
                          n2 = here_bits + 2;
                          while (bits < n2) {
                            if (have === 0) {
                              break inf_leave;
                            }
                            have--;
                            hold += input[next++] << bits;
                            bits += 8;
                          }
                          hold >>>= here_bits;
                          bits -= here_bits;
                          if (state.have === 0) {
                            strm.msg = "invalid bit length repeat";
                            state.mode = BAD;
                            break;
                          }
                          len = state.lens[state.have - 1];
                          copy = 3 + (hold & 3);
                          hold >>>= 2;
                          bits -= 2;
                        } else if (here_val === 17) {
                          n2 = here_bits + 3;
                          while (bits < n2) {
                            if (have === 0) {
                              break inf_leave;
                            }
                            have--;
                            hold += input[next++] << bits;
                            bits += 8;
                          }
                          hold >>>= here_bits;
                          bits -= here_bits;
                          len = 0;
                          copy = 3 + (hold & 7);
                          hold >>>= 3;
                          bits -= 3;
                        } else {
                          n2 = here_bits + 7;
                          while (bits < n2) {
                            if (have === 0) {
                              break inf_leave;
                            }
                            have--;
                            hold += input[next++] << bits;
                            bits += 8;
                          }
                          hold >>>= here_bits;
                          bits -= here_bits;
                          len = 0;
                          copy = 11 + (hold & 127);
                          hold >>>= 7;
                          bits -= 7;
                        }
                        if (state.have + copy > state.nlen + state.ndist) {
                          strm.msg = "invalid bit length repeat";
                          state.mode = BAD;
                          break;
                        }
                        while (copy--) {
                          state.lens[state.have++] = len;
                        }
                      }
                    }
                    if (state.mode === BAD) {
                      break;
                    }
                    if (state.lens[256] === 0) {
                      strm.msg = "invalid code -- missing end-of-block";
                      state.mode = BAD;
                      break;
                    }
                    state.lenbits = 9;
                    opts = { bits: state.lenbits };
                    ret = inflate_table(
                      LENS,
                      state.lens,
                      0,
                      state.nlen,
                      state.lencode,
                      0,
                      state.work,
                      opts
                    );
                    state.lenbits = opts.bits;
                    if (ret) {
                      strm.msg = "invalid literal/lengths set";
                      state.mode = BAD;
                      break;
                    }
                    state.distbits = 6;
                    state.distcode = state.distdyn;
                    opts = { bits: state.distbits };
                    ret = inflate_table(
                      DISTS,
                      state.lens,
                      state.nlen,
                      state.ndist,
                      state.distcode,
                      0,
                      state.work,
                      opts
                    );
                    state.distbits = opts.bits;
                    if (ret) {
                      strm.msg = "invalid distances set";
                      state.mode = BAD;
                      break;
                    }
                    state.mode = LEN_;
                    if (flush2 === Z_TREES) {
                      break inf_leave;
                    }
                  /* falls through */
                  case LEN_:
                    state.mode = LEN;
                  /* falls through */
                  case LEN:
                    if (have >= 6 && left >= 258) {
                      strm.next_out = put;
                      strm.avail_out = left;
                      strm.next_in = next;
                      strm.avail_in = have;
                      state.hold = hold;
                      state.bits = bits;
                      inflate_fast(strm, _out);
                      put = strm.next_out;
                      output = strm.output;
                      left = strm.avail_out;
                      next = strm.next_in;
                      input = strm.input;
                      have = strm.avail_in;
                      hold = state.hold;
                      bits = state.bits;
                      if (state.mode === TYPE) {
                        state.back = -1;
                      }
                      break;
                    }
                    state.back = 0;
                    for (; ; ) {
                      here = state.lencode[hold & (1 << state.lenbits) - 1];
                      here_bits = here >>> 24;
                      here_op = here >>> 16 & 255;
                      here_val = here & 65535;
                      if (here_bits <= bits) {
                        break;
                      }
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    if (here_op && (here_op & 240) === 0) {
                      last_bits = here_bits;
                      last_op = here_op;
                      last_val = here_val;
                      for (; ; ) {
                        here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)];
                        here_bits = here >>> 24;
                        here_op = here >>> 16 & 255;
                        here_val = here & 65535;
                        if (last_bits + here_bits <= bits) {
                          break;
                        }
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      hold >>>= last_bits;
                      bits -= last_bits;
                      state.back += last_bits;
                    }
                    hold >>>= here_bits;
                    bits -= here_bits;
                    state.back += here_bits;
                    state.length = here_val;
                    if (here_op === 0) {
                      state.mode = LIT;
                      break;
                    }
                    if (here_op & 32) {
                      state.back = -1;
                      state.mode = TYPE;
                      break;
                    }
                    if (here_op & 64) {
                      strm.msg = "invalid literal/length code";
                      state.mode = BAD;
                      break;
                    }
                    state.extra = here_op & 15;
                    state.mode = LENEXT;
                  /* falls through */
                  case LENEXT:
                    if (state.extra) {
                      n2 = state.extra;
                      while (bits < n2) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      state.length += hold & (1 << state.extra) - 1;
                      hold >>>= state.extra;
                      bits -= state.extra;
                      state.back += state.extra;
                    }
                    state.was = state.length;
                    state.mode = DIST;
                  /* falls through */
                  case DIST:
                    for (; ; ) {
                      here = state.distcode[hold & (1 << state.distbits) - 1];
                      here_bits = here >>> 24;
                      here_op = here >>> 16 & 255;
                      here_val = here & 65535;
                      if (here_bits <= bits) {
                        break;
                      }
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    if ((here_op & 240) === 0) {
                      last_bits = here_bits;
                      last_op = here_op;
                      last_val = here_val;
                      for (; ; ) {
                        here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)];
                        here_bits = here >>> 24;
                        here_op = here >>> 16 & 255;
                        here_val = here & 65535;
                        if (last_bits + here_bits <= bits) {
                          break;
                        }
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      hold >>>= last_bits;
                      bits -= last_bits;
                      state.back += last_bits;
                    }
                    hold >>>= here_bits;
                    bits -= here_bits;
                    state.back += here_bits;
                    if (here_op & 64) {
                      strm.msg = "invalid distance code";
                      state.mode = BAD;
                      break;
                    }
                    state.offset = here_val;
                    state.extra = here_op & 15;
                    state.mode = DISTEXT;
                  /* falls through */
                  case DISTEXT:
                    if (state.extra) {
                      n2 = state.extra;
                      while (bits < n2) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      state.offset += hold & (1 << state.extra) - 1;
                      hold >>>= state.extra;
                      bits -= state.extra;
                      state.back += state.extra;
                    }
                    if (state.offset > state.dmax) {
                      strm.msg = "invalid distance too far back";
                      state.mode = BAD;
                      break;
                    }
                    state.mode = MATCH;
                  /* falls through */
                  case MATCH:
                    if (left === 0) {
                      break inf_leave;
                    }
                    copy = _out - left;
                    if (state.offset > copy) {
                      copy = state.offset - copy;
                      if (copy > state.whave) {
                        if (state.sane) {
                          strm.msg = "invalid distance too far back";
                          state.mode = BAD;
                          break;
                        }
                      }
                      if (copy > state.wnext) {
                        copy -= state.wnext;
                        from = state.wsize - copy;
                      } else {
                        from = state.wnext - copy;
                      }
                      if (copy > state.length) {
                        copy = state.length;
                      }
                      from_source = state.window;
                    } else {
                      from_source = output;
                      from = put - state.offset;
                      copy = state.length;
                    }
                    if (copy > left) {
                      copy = left;
                    }
                    left -= copy;
                    state.length -= copy;
                    do {
                      output[put++] = from_source[from++];
                    } while (--copy);
                    if (state.length === 0) {
                      state.mode = LEN;
                    }
                    break;
                  case LIT:
                    if (left === 0) {
                      break inf_leave;
                    }
                    output[put++] = state.length;
                    left--;
                    state.mode = LEN;
                    break;
                  case CHECK:
                    if (state.wrap) {
                      while (bits < 32) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold |= input[next++] << bits;
                        bits += 8;
                      }
                      _out -= left;
                      strm.total_out += _out;
                      state.total += _out;
                      if (_out) {
                        strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/
                        state.flags ? crc32(
                          state.check,
                          output,
                          _out,
                          put - _out
                        ) : adler32(
                          state.check,
                          output,
                          _out,
                          put - _out
                        );
                      }
                      _out = left;
                      if ((state.flags ? hold : zswap32(hold)) !== state.check) {
                        strm.msg = "incorrect data check";
                        state.mode = BAD;
                        break;
                      }
                      hold = 0;
                      bits = 0;
                    }
                    state.mode = LENGTH;
                  /* falls through */
                  case LENGTH:
                    if (state.wrap && state.flags) {
                      while (bits < 32) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      if (hold !== (state.total & 4294967295)) {
                        strm.msg = "incorrect length check";
                        state.mode = BAD;
                        break;
                      }
                      hold = 0;
                      bits = 0;
                    }
                    state.mode = DONE;
                  /* falls through */
                  case DONE:
                    ret = Z_STREAM_END;
                    break inf_leave;
                  case BAD:
                    ret = Z_DATA_ERROR;
                    break inf_leave;
                  case MEM:
                    return Z_MEM_ERROR;
                  case SYNC:
                  /* falls through */
                  default:
                    return Z_STREAM_ERROR;
                }
              }
              strm.next_out = put;
              strm.avail_out = left;
              strm.next_in = next;
              strm.avail_in = have;
              state.hold = hold;
              state.bits = bits;
              if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush2 !== Z_FINISH)) {
                if (updatewindow(
                  strm,
                  strm.output,
                  strm.next_out,
                  _out - strm.avail_out
                )) {
                  state.mode = MEM;
                  return Z_MEM_ERROR;
                }
              }
              _in -= strm.avail_in;
              _out -= strm.avail_out;
              strm.total_in += _in;
              strm.total_out += _out;
              state.total += _out;
              if (state.wrap && _out) {
                strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
                state.flags ? crc32(
                  state.check,
                  output,
                  _out,
                  strm.next_out - _out
                ) : adler32(
                  state.check,
                  output,
                  _out,
                  strm.next_out - _out
                );
              }
              strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
              if ((_in === 0 && _out === 0 || flush2 === Z_FINISH) && ret === Z_OK) {
                ret = Z_BUF_ERROR;
              }
              return ret;
            }
            function inflateEnd(strm) {
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              var state = strm.state;
              if (state.window) {
                state.window = null;
              }
              strm.state = null;
              return Z_OK;
            }
            function inflateGetHeader(strm, head2) {
              var state;
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              state = strm.state;
              if ((state.wrap & 2) === 0) {
                return Z_STREAM_ERROR;
              }
              state.head = head2;
              head2.done = false;
              return Z_OK;
            }
            function inflateSetDictionary(strm, dictionary) {
              var dictLength = dictionary.length;
              var state;
              var dictid;
              var ret;
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              state = strm.state;
              if (state.wrap !== 0 && state.mode !== DICT) {
                return Z_STREAM_ERROR;
              }
              if (state.mode === DICT) {
                dictid = 1;
                dictid = adler32(
                  dictid,
                  dictionary,
                  dictLength,
                  0
                );
                if (dictid !== state.check) {
                  return Z_DATA_ERROR;
                }
              }
              ret = updatewindow(
                strm,
                dictionary,
                dictLength,
                dictLength
              );
              if (ret) {
                state.mode = MEM;
                return Z_MEM_ERROR;
              }
              state.havedict = 1;
              return Z_OK;
            }
            exports2.inflateReset = inflateReset;
            exports2.inflateReset2 = inflateReset2;
            exports2.inflateResetKeep = inflateResetKeep;
            exports2.inflateInit = inflateInit;
            exports2.inflateInit2 = inflateInit2;
            exports2.inflate = inflate;
            exports2.inflateEnd = inflateEnd;
            exports2.inflateGetHeader = inflateGetHeader;
            exports2.inflateSetDictionary = inflateSetDictionary;
            exports2.inflateInfo = "pako inflate (from Nodeca project)";
          },
          {
            "../utils/common": 1,
            "./adler32": 3,
            "./crc32": 5,
            "./inffast": 7,
            "./inftrees": 9
          }
        ],
        9: [
          function(require2, module2, exports2) {
            "use strict";
            var utils = require2("../utils/common");
            var MAXBITS = 15;
            var ENOUGH_LENS = 852;
            var ENOUGH_DISTS = 592;
            var CODES = 0;
            var LENS = 1;
            var DISTS = 2;
            var lbase = [
              /* Length codes 257..285 base */
              3,
              4,
              5,
              6,
              7,
              8,
              9,
              10,
              11,
              13,
              15,
              17,
              19,
              23,
              27,
              31,
              35,
              43,
              51,
              59,
              67,
              83,
              99,
              115,
              131,
              163,
              195,
              227,
              258,
              0,
              0
            ];
            var lext = [
              /* Length codes 257..285 extra */
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              16,
              17,
              17,
              17,
              17,
              18,
              18,
              18,
              18,
              19,
              19,
              19,
              19,
              20,
              20,
              20,
              20,
              21,
              21,
              21,
              21,
              16,
              72,
              78
            ];
            var dbase = [
              /* Distance codes 0..29 base */
              1,
              2,
              3,
              4,
              5,
              7,
              9,
              13,
              17,
              25,
              33,
              49,
              65,
              97,
              129,
              193,
              257,
              385,
              513,
              769,
              1025,
              1537,
              2049,
              3073,
              4097,
              6145,
              8193,
              12289,
              16385,
              24577,
              0,
              0
            ];
            var dext = [
              /* Distance codes 0..29 extra */
              16,
              16,
              16,
              16,
              17,
              17,
              18,
              18,
              19,
              19,
              20,
              20,
              21,
              21,
              22,
              22,
              23,
              23,
              24,
              24,
              25,
              25,
              26,
              26,
              27,
              27,
              28,
              28,
              29,
              29,
              64,
              64
            ];
            module2.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) {
              var bits = opts.bits;
              var len = 0;
              var sym = 0;
              var min2 = 0, max2 = 0;
              var root = 0;
              var curr = 0;
              var drop = 0;
              var left = 0;
              var used = 0;
              var huff = 0;
              var incr;
              var fill;
              var low;
              var mask;
              var next;
              var base = null;
              var base_index = 0;
              var end;
              var count = new utils.Buf16(MAXBITS + 1);
              var offs = new utils.Buf16(MAXBITS + 1);
              var extra = null;
              var extra_index = 0;
              var here_bits, here_op, here_val;
              for (len = 0; len <= MAXBITS; len++) {
                count[len] = 0;
              }
              for (sym = 0; sym < codes; sym++) {
                count[lens[lens_index + sym]]++;
              }
              root = bits;
              for (max2 = MAXBITS; max2 >= 1; max2--) {
                if (count[max2] !== 0) {
                  break;
                }
              }
              if (root > max2) {
                root = max2;
              }
              if (max2 === 0) {
                table[table_index++] = 1 << 24 | 64 << 16 | 0;
                table[table_index++] = 1 << 24 | 64 << 16 | 0;
                opts.bits = 1;
                return 0;
              }
              for (min2 = 1; min2 < max2; min2++) {
                if (count[min2] !== 0) {
                  break;
                }
              }
              if (root < min2) {
                root = min2;
              }
              left = 1;
              for (len = 1; len <= MAXBITS; len++) {
                left <<= 1;
                left -= count[len];
                if (left < 0) {
                  return -1;
                }
              }
              if (left > 0 && (type === CODES || max2 !== 1)) {
                return -1;
              }
              offs[1] = 0;
              for (len = 1; len < MAXBITS; len++) {
                offs[len + 1] = offs[len] + count[len];
              }
              for (sym = 0; sym < codes; sym++) {
                if (lens[lens_index + sym] !== 0) {
                  work[offs[lens[lens_index + sym]]++] = sym;
                }
              }
              if (type === CODES) {
                base = extra = work;
                end = 19;
              } else if (type === LENS) {
                base = lbase;
                base_index -= 257;
                extra = lext;
                extra_index -= 257;
                end = 256;
              } else {
                base = dbase;
                extra = dext;
                end = -1;
              }
              huff = 0;
              sym = 0;
              len = min2;
              next = table_index;
              curr = root;
              drop = 0;
              low = -1;
              used = 1 << root;
              mask = used - 1;
              if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) {
                return 1;
              }
              for (; ; ) {
                here_bits = len - drop;
                if (work[sym] < end) {
                  here_op = 0;
                  here_val = work[sym];
                } else if (work[sym] > end) {
                  here_op = extra[extra_index + work[sym]];
                  here_val = base[base_index + work[sym]];
                } else {
                  here_op = 32 + 64;
                  here_val = 0;
                }
                incr = 1 << len - drop;
                fill = 1 << curr;
                min2 = fill;
                do {
                  fill -= incr;
                  table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0;
                } while (fill !== 0);
                incr = 1 << len - 1;
                while (huff & incr) {
                  incr >>= 1;
                }
                if (incr !== 0) {
                  huff &= incr - 1;
                  huff += incr;
                } else {
                  huff = 0;
                }
                sym++;
                if (--count[len] === 0) {
                  if (len === max2) {
                    break;
                  }
                  len = lens[lens_index + work[sym]];
                }
                if (len > root && (huff & mask) !== low) {
                  if (drop === 0) {
                    drop = root;
                  }
                  next += min2;
                  curr = len - drop;
                  left = 1 << curr;
                  while (curr + drop < max2) {
                    left -= count[curr + drop];
                    if (left <= 0) {
                      break;
                    }
                    curr++;
                    left <<= 1;
                  }
                  used += 1 << curr;
                  if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) {
                    return 1;
                  }
                  low = huff & mask;
                  table[low] = root << 24 | curr << 16 | next - table_index | 0;
                }
              }
              if (huff !== 0) {
                table[next + huff] = len - drop << 24 | 64 << 16 | 0;
              }
              opts.bits = root;
              return 0;
            };
          },
          { "../utils/common": 1 }
        ],
        10: [
          function(require2, module2, exports2) {
            "use strict";
            module2.exports = {
              2: "need dictionary",
              1: "stream end",
              0: "",
              "-1": "file error",
              "-2": "stream error",
              "-3": "data error",
              "-4": "insufficient memory",
              "-5": "buffer error",
              "-6": "incompatible version"
            };
          },
          {}
        ],
        11: [
          function(require2, module2, exports2) {
            "use strict";
            function ZStream() {
              this.input = null;
              this.next_in = 0;
              this.avail_in = 0;
              this.total_in = 0;
              this.output = null;
              this.next_out = 0;
              this.avail_out = 0;
              this.total_out = 0;
              this.msg = "";
              this.state = null;
              this.data_type = 2;
              this.adler = 0;
            }
            module2.exports = ZStream;
          },
          {}
        ],
        "/lib/inflate.js": [
          function(require2, module2, exports2) {
            "use strict";
            var zlib_inflate = require2("./zlib/inflate");
            var utils = require2("./utils/common");
            var strings = require2("./utils/strings");
            var c6 = require2("./zlib/constants");
            var msg = require2("./zlib/messages");
            var ZStream = require2("./zlib/zstream");
            var GZheader = require2("./zlib/gzheader");
            var toString = Object.prototype.toString;
            function Inflate(options) {
              if (!(this instanceof Inflate))
                return new Inflate(options);
              this.options = utils.assign(
                {
                  chunkSize: 16384,
                  windowBits: 0,
                  to: ""
                },
                options || {}
              );
              var opt = this.options;
              if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) {
                opt.windowBits = -opt.windowBits;
                if (opt.windowBits === 0) {
                  opt.windowBits = -15;
                }
              }
              if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) {
                opt.windowBits += 32;
              }
              if (opt.windowBits > 15 && opt.windowBits < 48) {
                if ((opt.windowBits & 15) === 0) {
                  opt.windowBits |= 15;
                }
              }
              this.err = 0;
              this.msg = "";
              this.ended = false;
              this.chunks = [];
              this.strm = new ZStream();
              this.strm.avail_out = 0;
              var status = zlib_inflate.inflateInit2(
                this.strm,
                opt.windowBits
              );
              if (status !== c6.Z_OK) {
                throw new Error(msg[status]);
              }
              this.header = new GZheader();
              zlib_inflate.inflateGetHeader(this.strm, this.header);
              if (opt.dictionary) {
                if (typeof opt.dictionary === "string") {
                  opt.dictionary = strings.string2buf(
                    opt.dictionary
                  );
                } else if (toString.call(opt.dictionary) === "[object ArrayBuffer]") {
                  opt.dictionary = new Uint8Array(
                    opt.dictionary
                  );
                }
                if (opt.raw) {
                  status = zlib_inflate.inflateSetDictionary(
                    this.strm,
                    opt.dictionary
                  );
                  if (status !== c6.Z_OK) {
                    throw new Error(msg[status]);
                  }
                }
              }
            }
            Inflate.prototype.push = function(data, mode) {
              var strm = this.strm;
              var chunkSize = this.options.chunkSize;
              var dictionary = this.options.dictionary;
              var status, _mode;
              var next_out_utf8, tail, utf8str;
              var allowBufError = false;
              if (this.ended) {
                return false;
              }
              _mode = mode === ~~mode ? mode : mode === true ? c6.Z_FINISH : c6.Z_NO_FLUSH;
              if (typeof data === "string") {
                strm.input = strings.binstring2buf(data);
              } else if (toString.call(data) === "[object ArrayBuffer]") {
                strm.input = new Uint8Array(data);
              } else {
                strm.input = data;
              }
              strm.next_in = 0;
              strm.avail_in = strm.input.length;
              do {
                if (strm.avail_out === 0) {
                  strm.output = new utils.Buf8(chunkSize);
                  strm.next_out = 0;
                  strm.avail_out = chunkSize;
                }
                status = zlib_inflate.inflate(
                  strm,
                  c6.Z_NO_FLUSH
                );
                if (status === c6.Z_NEED_DICT && dictionary) {
                  status = zlib_inflate.inflateSetDictionary(
                    this.strm,
                    dictionary
                  );
                }
                if (status === c6.Z_BUF_ERROR && allowBufError === true) {
                  status = c6.Z_OK;
                  allowBufError = false;
                }
                if (status !== c6.Z_STREAM_END && status !== c6.Z_OK) {
                  this.onEnd(status);
                  this.ended = true;
                  return false;
                }
                if (strm.next_out) {
                  if (strm.avail_out === 0 || status === c6.Z_STREAM_END || strm.avail_in === 0 && (_mode === c6.Z_FINISH || _mode === c6.Z_SYNC_FLUSH)) {
                    if (this.options.to === "string") {
                      next_out_utf8 = strings.utf8border(
                        strm.output,
                        strm.next_out
                      );
                      tail = strm.next_out - next_out_utf8;
                      utf8str = strings.buf2string(
                        strm.output,
                        next_out_utf8
                      );
                      strm.next_out = tail;
                      strm.avail_out = chunkSize - tail;
                      if (tail) {
                        utils.arraySet(
                          strm.output,
                          strm.output,
                          next_out_utf8,
                          tail,
                          0
                        );
                      }
                      this.onData(utf8str);
                    } else {
                      this.onData(
                        utils.shrinkBuf(
                          strm.output,
                          strm.next_out
                        )
                      );
                    }
                  }
                }
                if (strm.avail_in === 0 && strm.avail_out === 0) {
                  allowBufError = true;
                }
              } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c6.Z_STREAM_END);
              if (status === c6.Z_STREAM_END) {
                _mode = c6.Z_FINISH;
              }
              if (_mode === c6.Z_FINISH) {
                status = zlib_inflate.inflateEnd(this.strm);
                this.onEnd(status);
                this.ended = true;
                return status === c6.Z_OK;
              }
              if (_mode === c6.Z_SYNC_FLUSH) {
                this.onEnd(c6.Z_OK);
                strm.avail_out = 0;
                return true;
              }
              return true;
            };
            Inflate.prototype.onData = function(chunk2) {
              this.chunks.push(chunk2);
            };
            Inflate.prototype.onEnd = function(status) {
              if (status === c6.Z_OK) {
                if (this.options.to === "string") {
                  this.result = this.chunks.join("");
                } else {
                  this.result = utils.flattenChunks(
                    this.chunks
                  );
                }
              }
              this.chunks = [];
              this.err = status;
              this.msg = this.strm.msg;
            };
            function inflate(input, options) {
              var inflator = new Inflate(options);
              inflator.push(input, true);
              if (inflator.err) {
                throw inflator.msg || msg[inflator.err];
              }
              return inflator.result;
            }
            function inflateRaw(input, options) {
              options = options || {};
              options.raw = true;
              return inflate(input, options);
            }
            exports2.Inflate = Inflate;
            exports2.inflate = inflate;
            exports2.inflateRaw = inflateRaw;
            exports2.ungzip = inflate;
          },
          {
            "./utils/common": 1,
            "./utils/strings": 2,
            "./zlib/constants": 4,
            "./zlib/gzheader": 6,
            "./zlib/inflate": 8,
            "./zlib/messages": 10,
            "./zlib/zstream": 11
          }
        ]
      },
      {},
      []
    )("/lib/inflate.js");
  })();

  // packages/global-styles-ui/build-module/font-library/lib/lib-font.browser.mjs
  var fetchFunction = globalThis.fetch;
  var Event2 = class {
    constructor(type, detail = {}, msg) {
      this.type = type;
      this.detail = detail;
      this.msg = msg;
      Object.defineProperty(this, `__mayPropagate`, {
        enumerable: false,
        writable: true
      });
      this.__mayPropagate = true;
    }
    preventDefault() {
    }
    stopPropagation() {
      this.__mayPropagate = false;
    }
    valueOf() {
      return this;
    }
    toString() {
      return this.msg ? `[${this.type} event]: ${this.msg}` : `[${this.type} event]`;
    }
  };
  var EventManager = class {
    constructor() {
      this.listeners = {};
    }
    addEventListener(type, listener, useCapture) {
      let bin = this.listeners[type] || [];
      if (useCapture) bin.unshift(listener);
      else bin.push(listener);
      this.listeners[type] = bin;
    }
    removeEventListener(type, listener) {
      let bin = this.listeners[type] || [];
      let pos = bin.findIndex((e2) => e2 === listener);
      if (pos > -1) {
        bin.splice(pos, 1);
        this.listeners[type] = bin;
      }
    }
    dispatch(event) {
      let bin = this.listeners[event.type];
      if (bin) {
        for (let l2 = 0, e2 = bin.length; l2 < e2; l2++) {
          if (!event.__mayPropagate) break;
          bin[l2](event);
        }
      }
    }
  };
  var startDate = (/* @__PURE__ */ new Date(`1904-01-01T00:00:00+0000`)).getTime();
  function asText(data) {
    return Array.from(data).map((v2) => String.fromCharCode(v2)).join(``);
  }
  var Parser = class {
    constructor(dict, dataview, name2) {
      this.name = (name2 || dict.tag || ``).trim();
      this.length = dict.length;
      this.start = dict.offset;
      this.offset = 0;
      this.data = dataview;
      [
        `getInt8`,
        `getUint8`,
        `getInt16`,
        `getUint16`,
        `getInt32`,
        `getUint32`,
        `getBigInt64`,
        `getBigUint64`
      ].forEach((name3) => {
        let fn = name3.replace(/get(Big)?/, "").toLowerCase();
        let increment = parseInt(name3.replace(/[^\d]/g, "")) / 8;
        Object.defineProperty(this, fn, {
          get: () => this.getValue(name3, increment)
        });
      });
    }
    get currentPosition() {
      return this.start + this.offset;
    }
    set currentPosition(position) {
      this.start = position;
      this.offset = 0;
    }
    skip(n2 = 0, bits = 8) {
      this.offset += n2 * bits / 8;
    }
    getValue(type, increment) {
      let pos = this.start + this.offset;
      this.offset += increment;
      try {
        return this.data[type](pos);
      } catch (e2) {
        console.error(`parser`, type, increment, this);
        console.error(`parser`, this.start, this.offset);
        throw e2;
      }
    }
    flags(n2) {
      if (n2 === 8 || n2 === 16 || n2 === 32 || n2 === 64) {
        return this[`uint${n2}`].toString(2).padStart(n2, 0).split(``).map((v2) => v2 === "1");
      }
      console.error(
        `Error parsing flags: flag types can only be 1, 2, 4, or 8 bytes long`
      );
      console.trace();
    }
    get tag() {
      const t3 = this.uint32;
      return asText([
        t3 >> 24 & 255,
        t3 >> 16 & 255,
        t3 >> 8 & 255,
        t3 & 255
      ]);
    }
    get fixed() {
      let major = this.int16;
      let minor = Math.round(1e3 * this.uint16 / 65356);
      return major + minor / 1e3;
    }
    get legacyFixed() {
      let major = this.uint16;
      let minor = this.uint16.toString(16).padStart(4, 0);
      return parseFloat(`${major}.${minor}`);
    }
    get uint24() {
      return (this.uint8 << 16) + (this.uint8 << 8) + this.uint8;
    }
    get uint128() {
      let value = 0;
      for (let i2 = 0; i2 < 5; i2++) {
        let byte = this.uint8;
        value = value * 128 + (byte & 127);
        if (byte < 128) break;
      }
      return value;
    }
    get longdatetime() {
      return new Date(startDate + 1e3 * parseInt(this.int64.toString()));
    }
    get fword() {
      return this.int16;
    }
    get ufword() {
      return this.uint16;
    }
    get Offset16() {
      return this.uint16;
    }
    get Offset32() {
      return this.uint32;
    }
    get F2DOT14() {
      const bits = p.uint16;
      const integer = [0, 1, -2, -1][bits >> 14];
      const fraction = bits & 16383;
      return integer + fraction / 16384;
    }
    verifyLength() {
      if (this.offset != this.length) {
        console.error(
          `unexpected parsed table size (${this.offset}) for "${this.name}" (expected ${this.length})`
        );
      }
    }
    readBytes(n2 = 0, position = 0, bits = 8, signed = false) {
      n2 = n2 || this.length;
      if (n2 === 0) return [];
      if (position) this.currentPosition = position;
      const fn = `${signed ? `` : `u`}int${bits}`, slice = [];
      while (n2--) slice.push(this[fn]);
      return slice;
    }
  };
  var ParsedData = class {
    constructor(parser) {
      const pGetter = { enumerable: false, get: () => parser };
      Object.defineProperty(this, `parser`, pGetter);
      const start2 = parser.currentPosition;
      const startGetter = { enumerable: false, get: () => start2 };
      Object.defineProperty(this, `start`, startGetter);
    }
    load(struct) {
      Object.keys(struct).forEach((p22) => {
        let props = Object.getOwnPropertyDescriptor(struct, p22);
        if (props.get) {
          this[p22] = props.get.bind(this);
        } else if (props.value !== void 0) {
          this[p22] = props.value;
        }
      });
      if (this.parser.length) {
        this.parser.verifyLength();
      }
    }
  };
  var SimpleTable = class extends ParsedData {
    constructor(dict, dataview, name2) {
      const { parser, start: start2 } = super(
        new Parser(dict, dataview, name2)
      );
      const pGetter = { enumerable: false, get: () => parser };
      Object.defineProperty(this, `p`, pGetter);
      const startGetter = { enumerable: false, get: () => start2 };
      Object.defineProperty(this, `tableStart`, startGetter);
    }
  };
  function lazy$1(object, property, getter) {
    let val;
    Object.defineProperty(object, property, {
      get: () => {
        if (val) return val;
        val = getter();
        return val;
      },
      enumerable: true
    });
  }
  var SFNT = class extends SimpleTable {
    constructor(font2, dataview, createTable2) {
      const { p: p22 } = super({ offset: 0, length: 12 }, dataview, `sfnt`);
      this.version = p22.uint32;
      this.numTables = p22.uint16;
      this.searchRange = p22.uint16;
      this.entrySelector = p22.uint16;
      this.rangeShift = p22.uint16;
      p22.verifyLength();
      this.directory = [...new Array(this.numTables)].map(
        (_) => new TableRecord(p22)
      );
      this.tables = {};
      this.directory.forEach((entry) => {
        const getter = () => createTable2(
          this.tables,
          {
            tag: entry.tag,
            offset: entry.offset,
            length: entry.length
          },
          dataview
        );
        lazy$1(this.tables, entry.tag.trim(), getter);
      });
    }
  };
  var TableRecord = class {
    constructor(p22) {
      this.tag = p22.tag;
      this.checksum = p22.uint32;
      this.offset = p22.uint32;
      this.length = p22.uint32;
    }
  };
  var gzipDecode = inflate_default.inflate || void 0;
  var nativeGzipDecode = void 0;
  var WOFF$1 = class extends SimpleTable {
    constructor(font2, dataview, createTable2) {
      const { p: p22 } = super({ offset: 0, length: 44 }, dataview, `woff`);
      this.signature = p22.tag;
      this.flavor = p22.uint32;
      this.length = p22.uint32;
      this.numTables = p22.uint16;
      p22.uint16;
      this.totalSfntSize = p22.uint32;
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
      this.metaOffset = p22.uint32;
      this.metaLength = p22.uint32;
      this.metaOrigLength = p22.uint32;
      this.privOffset = p22.uint32;
      this.privLength = p22.uint32;
      p22.verifyLength();
      this.directory = [...new Array(this.numTables)].map(
        (_) => new WoffTableDirectoryEntry(p22)
      );
      buildWoffLazyLookups(this, dataview, createTable2);
    }
  };
  var WoffTableDirectoryEntry = class {
    constructor(p22) {
      this.tag = p22.tag;
      this.offset = p22.uint32;
      this.compLength = p22.uint32;
      this.origLength = p22.uint32;
      this.origChecksum = p22.uint32;
    }
  };
  function buildWoffLazyLookups(woff, dataview, createTable2) {
    woff.tables = {};
    woff.directory.forEach((entry) => {
      lazy$1(woff.tables, entry.tag.trim(), () => {
        let offset4 = 0;
        let view = dataview;
        if (entry.compLength !== entry.origLength) {
          const data = dataview.buffer.slice(
            entry.offset,
            entry.offset + entry.compLength
          );
          let unpacked;
          if (gzipDecode) {
            unpacked = gzipDecode(new Uint8Array(data));
          } else if (nativeGzipDecode) {
            unpacked = nativeGzipDecode(new Uint8Array(data));
          } else {
            const msg = `no brotli decoder available to decode WOFF2 font`;
            if (font.onerror) font.onerror(msg);
            throw new Error(msg);
          }
          view = new DataView(unpacked.buffer);
        } else {
          offset4 = entry.offset;
        }
        return createTable2(
          woff.tables,
          { tag: entry.tag, offset: offset4, length: entry.origLength },
          view
        );
      });
    });
  }
  var brotliDecode = unbrotli_default;
  var nativeBrotliDecode = void 0;
  var WOFF2$1 = class extends SimpleTable {
    constructor(font2, dataview, createTable2) {
      const { p: p22 } = super({ offset: 0, length: 48 }, dataview, `woff2`);
      this.signature = p22.tag;
      this.flavor = p22.uint32;
      this.length = p22.uint32;
      this.numTables = p22.uint16;
      p22.uint16;
      this.totalSfntSize = p22.uint32;
      this.totalCompressedSize = p22.uint32;
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
      this.metaOffset = p22.uint32;
      this.metaLength = p22.uint32;
      this.metaOrigLength = p22.uint32;
      this.privOffset = p22.uint32;
      this.privLength = p22.uint32;
      p22.verifyLength();
      this.directory = [...new Array(this.numTables)].map(
        (_) => new Woff2TableDirectoryEntry(p22)
      );
      let dictOffset = p22.currentPosition;
      this.directory[0].offset = 0;
      this.directory.forEach((e2, i2) => {
        let next = this.directory[i2 + 1];
        if (next) {
          next.offset = e2.offset + (e2.transformLength !== void 0 ? e2.transformLength : e2.origLength);
        }
      });
      let decoded;
      let buffer = dataview.buffer.slice(dictOffset);
      if (brotliDecode) {
        decoded = brotliDecode(new Uint8Array(buffer));
      } else if (nativeBrotliDecode) {
        decoded = new Uint8Array(nativeBrotliDecode(buffer));
      } else {
        const msg = `no brotli decoder available to decode WOFF2 font`;
        if (font2.onerror) font2.onerror(msg);
        throw new Error(msg);
      }
      buildWoff2LazyLookups(this, decoded, createTable2);
    }
  };
  var Woff2TableDirectoryEntry = class {
    constructor(p22) {
      this.flags = p22.uint8;
      const tagNumber = this.tagNumber = this.flags & 63;
      if (tagNumber === 63) {
        this.tag = p22.tag;
      } else {
        this.tag = getWOFF2Tag(tagNumber);
      }
      const transformVersion = this.transformVersion = (this.flags & 192) >> 6;
      let hasTransforms = transformVersion !== 0;
      if (this.tag === `glyf` || this.tag === `loca`) {
        hasTransforms = this.transformVersion !== 3;
      }
      this.origLength = p22.uint128;
      if (hasTransforms) {
        this.transformLength = p22.uint128;
      }
    }
  };
  function buildWoff2LazyLookups(woff2, decoded, createTable2) {
    woff2.tables = {};
    woff2.directory.forEach((entry) => {
      lazy$1(woff2.tables, entry.tag.trim(), () => {
        const start2 = entry.offset;
        const end = start2 + (entry.transformLength ? entry.transformLength : entry.origLength);
        const data = new DataView(decoded.slice(start2, end).buffer);
        try {
          return createTable2(
            woff2.tables,
            { tag: entry.tag, offset: 0, length: entry.origLength },
            data
          );
        } catch (e2) {
          console.error(e2);
        }
      });
    });
  }
  function getWOFF2Tag(flag) {
    return [
      `cmap`,
      `head`,
      `hhea`,
      `hmtx`,
      `maxp`,
      `name`,
      `OS/2`,
      `post`,
      `cvt `,
      `fpgm`,
      `glyf`,
      `loca`,
      `prep`,
      `CFF `,
      `VORG`,
      `EBDT`,
      `EBLC`,
      `gasp`,
      `hdmx`,
      `kern`,
      `LTSH`,
      `PCLT`,
      `VDMX`,
      `vhea`,
      `vmtx`,
      `BASE`,
      `GDEF`,
      `GPOS`,
      `GSUB`,
      `EBSC`,
      `JSTF`,
      `MATH`,
      `CBDT`,
      `CBLC`,
      `COLR`,
      `CPAL`,
      `SVG `,
      `sbix`,
      `acnt`,
      `avar`,
      `bdat`,
      `bloc`,
      `bsln`,
      `cvar`,
      `fdsc`,
      `feat`,
      `fmtx`,
      `fvar`,
      `gvar`,
      `hsty`,
      `just`,
      `lcar`,
      `mort`,
      `morx`,
      `opbd`,
      `prop`,
      `trak`,
      `Zapf`,
      `Silf`,
      `Glat`,
      `Gloc`,
      `Feat`,
      `Sill`
    ][flag & 63];
  }
  var tableClasses = {};
  var tableClassesLoaded = false;
  Promise.all([
    Promise.resolve().then(function() {
      return cmap$1;
    }),
    Promise.resolve().then(function() {
      return head$1;
    }),
    Promise.resolve().then(function() {
      return hhea$1;
    }),
    Promise.resolve().then(function() {
      return hmtx$1;
    }),
    Promise.resolve().then(function() {
      return maxp$1;
    }),
    Promise.resolve().then(function() {
      return name$1;
    }),
    Promise.resolve().then(function() {
      return OS2$1;
    }),
    Promise.resolve().then(function() {
      return post$1;
    }),
    Promise.resolve().then(function() {
      return BASE$1;
    }),
    Promise.resolve().then(function() {
      return GDEF$1;
    }),
    Promise.resolve().then(function() {
      return GSUB$1;
    }),
    Promise.resolve().then(function() {
      return GPOS$1;
    }),
    Promise.resolve().then(function() {
      return SVG$1;
    }),
    Promise.resolve().then(function() {
      return fvar$1;
    }),
    Promise.resolve().then(function() {
      return cvt$1;
    }),
    Promise.resolve().then(function() {
      return fpgm$1;
    }),
    Promise.resolve().then(function() {
      return gasp$1;
    }),
    Promise.resolve().then(function() {
      return glyf$1;
    }),
    Promise.resolve().then(function() {
      return loca$1;
    }),
    Promise.resolve().then(function() {
      return prep$1;
    }),
    Promise.resolve().then(function() {
      return CFF$1;
    }),
    Promise.resolve().then(function() {
      return CFF2$1;
    }),
    Promise.resolve().then(function() {
      return VORG$1;
    }),
    Promise.resolve().then(function() {
      return EBLC$1;
    }),
    Promise.resolve().then(function() {
      return EBDT$1;
    }),
    Promise.resolve().then(function() {
      return EBSC$1;
    }),
    Promise.resolve().then(function() {
      return CBLC$1;
    }),
    Promise.resolve().then(function() {
      return CBDT$1;
    }),
    Promise.resolve().then(function() {
      return sbix$1;
    }),
    Promise.resolve().then(function() {
      return COLR$1;
    }),
    Promise.resolve().then(function() {
      return CPAL$1;
    }),
    Promise.resolve().then(function() {
      return DSIG$1;
    }),
    Promise.resolve().then(function() {
      return hdmx$1;
    }),
    Promise.resolve().then(function() {
      return kern$1;
    }),
    Promise.resolve().then(function() {
      return LTSH$1;
    }),
    Promise.resolve().then(function() {
      return MERG$1;
    }),
    Promise.resolve().then(function() {
      return meta$1;
    }),
    Promise.resolve().then(function() {
      return PCLT$1;
    }),
    Promise.resolve().then(function() {
      return VDMX$1;
    }),
    Promise.resolve().then(function() {
      return vhea$1;
    }),
    Promise.resolve().then(function() {
      return vmtx$1;
    })
  ]).then((data) => {
    data.forEach((e2) => {
      let name2 = Object.keys(e2)[0];
      tableClasses[name2] = e2[name2];
    });
    tableClassesLoaded = true;
  });
  function createTable(tables, dict, dataview) {
    let name2 = dict.tag.replace(/[^\w\d]/g, ``);
    let Type = tableClasses[name2];
    if (Type) return new Type(dict, dataview, tables);
    console.warn(
      `lib-font has no definition for ${name2}. The table was skipped.`
    );
    return {};
  }
  function loadTableClasses() {
    let count = 0;
    function checkLoaded(resolve, reject) {
      if (!tableClassesLoaded) {
        if (count > 10) {
          return reject(new Error(`loading took too long`));
        }
        count++;
        return setTimeout(() => checkLoaded(resolve), 250);
      }
      resolve(createTable);
    }
    return new Promise((resolve, reject) => checkLoaded(resolve));
  }
  function getFontCSSFormat(path, errorOnStyle) {
    let pos = path.lastIndexOf(`.`);
    let ext = (path.substring(pos + 1) || ``).toLowerCase();
    let format6 = {
      ttf: `truetype`,
      otf: `opentype`,
      woff: `woff`,
      woff2: `woff2`
    }[ext];
    if (format6) return format6;
    let msg = {
      eot: `The .eot format is not supported: it died in January 12, 2016, when Microsoft retired all versions of IE that didn't already support WOFF.`,
      svg: `The .svg format is not supported: SVG fonts (not to be confused with OpenType with embedded SVG) were so bad we took the entire fonts chapter out of the SVG specification again.`,
      fon: `The .fon format is not supported: this is an ancient Windows bitmap font format.`,
      ttc: `Based on the current CSS specification, font collections are not (yet?) supported.`
    }[ext];
    if (!msg) msg = `${path} is not a known webfont format.`;
    if (errorOnStyle) {
      throw new Error(msg);
    } else {
      console.warn(`Could not load font: ${msg}`);
    }
  }
  async function setupFontFace(name2, url, options = {}) {
    if (!globalThis.document) return;
    let format6 = getFontCSSFormat(url, options.errorOnStyle);
    if (!format6) return;
    let style = document.createElement(`style`);
    style.className = `injected-by-Font-js`;
    let rules = [];
    if (options.styleRules) {
      rules = Object.entries(options.styleRules).map(
        ([key, value]) => `${key}: ${value};`
      );
    }
    style.textContent = `
@font-face {
    font-family: "${name2}";
    ${rules.join(
      `
	`
    )}
    src: url("${url}") format("${format6}");
}`;
    globalThis.document.head.appendChild(style);
    return style;
  }
  var TTF = [0, 1, 0, 0];
  var OTF = [79, 84, 84, 79];
  var WOFF = [119, 79, 70, 70];
  var WOFF2 = [119, 79, 70, 50];
  function match2(ar1, ar2) {
    if (ar1.length !== ar2.length) return;
    for (let i2 = 0; i2 < ar1.length; i2++) {
      if (ar1[i2] !== ar2[i2]) return;
    }
    return true;
  }
  function validFontFormat(dataview) {
    const LEAD_BYTES = [
      dataview.getUint8(0),
      dataview.getUint8(1),
      dataview.getUint8(2),
      dataview.getUint8(3)
    ];
    if (match2(LEAD_BYTES, TTF) || match2(LEAD_BYTES, OTF)) return `SFNT`;
    if (match2(LEAD_BYTES, WOFF)) return `WOFF`;
    if (match2(LEAD_BYTES, WOFF2)) return `WOFF2`;
  }
  function checkFetchResponseStatus(response) {
    if (!response.ok) {
      throw new Error(
        `HTTP ${response.status} - ${response.statusText}`
      );
    }
    return response;
  }
  var Font = class extends EventManager {
    constructor(name2, options = {}) {
      super();
      this.name = name2;
      this.options = options;
      this.metrics = false;
    }
    get src() {
      return this.__src;
    }
    set src(src) {
      this.__src = src;
      (async () => {
        if (globalThis.document && !this.options.skipStyleSheet) {
          await setupFontFace(this.name, src, this.options);
        }
        this.loadFont(src);
      })();
    }
    async loadFont(url, filename) {
      fetch(url).then(
        (response) => checkFetchResponseStatus(response) && response.arrayBuffer()
      ).then(
        (buffer) => this.fromDataBuffer(buffer, filename || url)
      ).catch((err) => {
        const evt = new Event2(
          `error`,
          err,
          `Failed to load font at ${filename || url}`
        );
        this.dispatch(evt);
        if (this.onerror) this.onerror(evt);
      });
    }
    async fromDataBuffer(buffer, filenameOrUrL) {
      this.fontData = new DataView(buffer);
      let type = validFontFormat(this.fontData);
      if (!type) {
        throw new Error(
          `${filenameOrUrL} is either an unsupported font format, or not a font at all.`
        );
      }
      await this.parseBasicData(type);
      const evt = new Event2("load", { font: this });
      this.dispatch(evt);
      if (this.onload) this.onload(evt);
    }
    async parseBasicData(type) {
      return loadTableClasses().then((createTable2) => {
        if (type === `SFNT`) {
          this.opentype = new SFNT(this, this.fontData, createTable2);
        }
        if (type === `WOFF`) {
          this.opentype = new WOFF$1(this, this.fontData, createTable2);
        }
        if (type === `WOFF2`) {
          this.opentype = new WOFF2$1(this, this.fontData, createTable2);
        }
        return this.opentype;
      });
    }
    getGlyphId(char) {
      return this.opentype.tables.cmap.getGlyphId(char);
    }
    reverse(glyphid) {
      return this.opentype.tables.cmap.reverse(glyphid);
    }
    supports(char) {
      return this.getGlyphId(char) !== 0;
    }
    supportsVariation(variation) {
      return this.opentype.tables.cmap.supportsVariation(variation) !== false;
    }
    measureText(text, size4 = 16) {
      if (this.__unloaded)
        throw new Error(
          "Cannot measure text: font was unloaded. Please reload before calling measureText()"
        );
      let d2 = document.createElement("div");
      d2.textContent = text;
      d2.style.fontFamily = this.name;
      d2.style.fontSize = `${size4}px`;
      d2.style.color = `transparent`;
      d2.style.background = `transparent`;
      d2.style.top = `0`;
      d2.style.left = `0`;
      d2.style.position = `absolute`;
      document.body.appendChild(d2);
      let bbox = d2.getBoundingClientRect();
      document.body.removeChild(d2);
      const OS22 = this.opentype.tables["OS/2"];
      bbox.fontSize = size4;
      bbox.ascender = OS22.sTypoAscender;
      bbox.descender = OS22.sTypoDescender;
      return bbox;
    }
    unload() {
      if (this.styleElement.parentNode) {
        this.styleElement.parentNode.removeElement(this.styleElement);
        const evt = new Event2("unload", { font: this });
        this.dispatch(evt);
        if (this.onunload) this.onunload(evt);
      }
      this._unloaded = true;
    }
    load() {
      if (this.__unloaded) {
        delete this.__unloaded;
        document.head.appendChild(this.styleElement);
        const evt = new Event2("load", { font: this });
        this.dispatch(evt);
        if (this.onload) this.onload(evt);
      }
    }
  };
  globalThis.Font = Font;
  var Subtable = class extends ParsedData {
    constructor(p22, plaformID, encodingID) {
      super(p22);
      this.plaformID = plaformID;
      this.encodingID = encodingID;
    }
  };
  var Format0 = class extends Subtable {
    constructor(p22, platformID, encodingID) {
      super(p22, platformID, encodingID);
      this.format = 0;
      this.length = p22.uint16;
      this.language = p22.uint16;
      this.glyphIdArray = [...new Array(256)].map((_) => p22.uint8);
    }
    supports(charCode) {
      if (charCode.charCodeAt) {
        charCode = -1;
        console.warn(
          `supports(character) not implemented for cmap subtable format 0. only supports(id) is implemented.`
        );
      }
      return 0 <= charCode && charCode <= 255;
    }
    reverse(glyphID) {
      console.warn(`reverse not implemented for cmap subtable format 0`);
      return {};
    }
    getSupportedCharCodes() {
      return [{ start: 1, end: 256 }];
    }
  };
  var Format2 = class extends Subtable {
    constructor(p22, platformID, encodingID) {
      super(p22, platformID, encodingID);
      this.format = 2;
      this.length = p22.uint16;
      this.language = p22.uint16;
      this.subHeaderKeys = [...new Array(256)].map((_) => p22.uint16);
      const subHeaderCount = Math.max(...this.subHeaderKeys);
      const subHeaderOffset = p22.currentPosition;
      lazy$1(this, `subHeaders`, () => {
        p22.currentPosition = subHeaderOffset;
        return [...new Array(subHeaderCount)].map(
          (_) => new SubHeader(p22)
        );
      });
      const glyphIndexOffset = subHeaderOffset + subHeaderCount * 8;
      lazy$1(this, `glyphIndexArray`, () => {
        p22.currentPosition = glyphIndexOffset;
        return [...new Array(subHeaderCount)].map((_) => p22.uint16);
      });
    }
    supports(charCode) {
      if (charCode.charCodeAt) {
        charCode = -1;
        console.warn(
          `supports(character) not implemented for cmap subtable format 2. only supports(id) is implemented.`
        );
      }
      const low = charCode && 255;
      const high = charCode && 65280;
      const subHeaderKey = this.subHeaders[high];
      const subheader = this.subHeaders[subHeaderKey];
      const first = subheader.firstCode;
      const last = first + subheader.entryCount;
      return first <= low && low <= last;
    }
    reverse(glyphID) {
      console.warn(`reverse not implemented for cmap subtable format 2`);
      return {};
    }
    getSupportedCharCodes(preservePropNames = false) {
      if (preservePropNames) {
        return this.subHeaders.map((h2) => ({
          firstCode: h2.firstCode,
          lastCode: h2.lastCode
        }));
      }
      return this.subHeaders.map((h2) => ({
        start: h2.firstCode,
        end: h2.lastCode
      }));
    }
  };
  var SubHeader = class {
    constructor(p22) {
      this.firstCode = p22.uint16;
      this.entryCount = p22.uint16;
      this.lastCode = this.first + this.entryCount;
      this.idDelta = p22.int16;
      this.idRangeOffset = p22.uint16;
    }
  };
  var Format4 = class extends Subtable {
    constructor(p22, platformID, encodingID) {
      super(p22, platformID, encodingID);
      this.format = 4;
      this.length = p22.uint16;
      this.language = p22.uint16;
      this.segCountX2 = p22.uint16;
      this.segCount = this.segCountX2 / 2;
      this.searchRange = p22.uint16;
      this.entrySelector = p22.uint16;
      this.rangeShift = p22.uint16;
      const endCodePosition = p22.currentPosition;
      lazy$1(
        this,
        `endCode`,
        () => p22.readBytes(this.segCount, endCodePosition, 16)
      );
      const startCodePosition = endCodePosition + 2 + this.segCountX2;
      lazy$1(
        this,
        `startCode`,
        () => p22.readBytes(this.segCount, startCodePosition, 16)
      );
      const idDeltaPosition = startCodePosition + this.segCountX2;
      lazy$1(
        this,
        `idDelta`,
        () => p22.readBytes(this.segCount, idDeltaPosition, 16, true)
      );
      const idRangePosition = idDeltaPosition + this.segCountX2;
      lazy$1(
        this,
        `idRangeOffset`,
        () => p22.readBytes(this.segCount, idRangePosition, 16)
      );
      const glyphIdArrayPosition = idRangePosition + this.segCountX2;
      const glyphIdArrayLength = this.length - (glyphIdArrayPosition - this.tableStart);
      lazy$1(
        this,
        `glyphIdArray`,
        () => p22.readBytes(glyphIdArrayLength, glyphIdArrayPosition, 16)
      );
      lazy$1(
        this,
        `segments`,
        () => this.buildSegments(idRangePosition, glyphIdArrayPosition, p22)
      );
    }
    buildSegments(idRangePosition, glyphIdArrayPosition, p22) {
      const build = (_, i2) => {
        let startCode = this.startCode[i2], endCode = this.endCode[i2], idDelta = this.idDelta[i2], idRangeOffset = this.idRangeOffset[i2], idRangeOffsetPointer = idRangePosition + 2 * i2, glyphIDs = [];
        if (idRangeOffset === 0) {
          for (let i22 = startCode + idDelta, e2 = endCode + idDelta; i22 <= e2; i22++) {
            glyphIDs.push(i22);
          }
        } else {
          for (let i22 = 0, e2 = endCode - startCode; i22 <= e2; i22++) {
            p22.currentPosition = idRangeOffsetPointer + idRangeOffset + i22 * 2;
            glyphIDs.push(p22.uint16);
          }
        }
        return {
          startCode,
          endCode,
          idDelta,
          idRangeOffset,
          glyphIDs
        };
      };
      return [...new Array(this.segCount)].map(build);
    }
    reverse(glyphID) {
      let s2 = this.segments.find((v2) => v2.glyphIDs.includes(glyphID));
      if (!s2) return {};
      const code = s2.startCode + s2.glyphIDs.indexOf(glyphID);
      return { code, unicode: String.fromCodePoint(code) };
    }
    getGlyphId(charCode) {
      if (charCode.charCodeAt) charCode = charCode.charCodeAt(0);
      if (55296 <= charCode && charCode <= 57343) return 0;
      if ((charCode & 65534) === 65534 || (charCode & 65535) === 65535)
        return 0;
      let segment = this.segments.find(
        (s2) => s2.startCode <= charCode && charCode <= s2.endCode
      );
      if (!segment) return 0;
      return segment.glyphIDs[charCode - segment.startCode];
    }
    supports(charCode) {
      return this.getGlyphId(charCode) !== 0;
    }
    getSupportedCharCodes(preservePropNames = false) {
      if (preservePropNames) return this.segments;
      return this.segments.map((v2) => ({
        start: v2.startCode,
        end: v2.endCode
      }));
    }
  };
  var Format6 = class extends Subtable {
    constructor(p22, platformID, encodingID) {
      super(p22, platformID, encodingID);
      this.format = 6;
      this.length = p22.uint16;
      this.language = p22.uint16;
      this.firstCode = p22.uint16;
      this.entryCount = p22.uint16;
      this.lastCode = this.firstCode + this.entryCount - 1;
      const getter = () => [...new Array(this.entryCount)].map((_) => p22.uint16);
      lazy$1(this, `glyphIdArray`, getter);
    }
    supports(charCode) {
      if (charCode.charCodeAt) {
        charCode = -1;
        console.warn(
          `supports(character) not implemented for cmap subtable format 6. only supports(id) is implemented.`
        );
      }
      if (charCode < this.firstCode) return {};
      if (charCode > this.firstCode + this.entryCount) return {};
      const code = charCode - this.firstCode;
      return { code, unicode: String.fromCodePoint(code) };
    }
    reverse(glyphID) {
      let pos = this.glyphIdArray.indexOf(glyphID);
      if (pos > -1) return this.firstCode + pos;
    }
    getSupportedCharCodes(preservePropNames = false) {
      if (preservePropNames) {
        return [{ firstCode: this.firstCode, lastCode: this.lastCode }];
      }
      return [{ start: this.firstCode, end: this.lastCode }];
    }
  };
  var Format8 = class extends Subtable {
    constructor(p22, platformID, encodingID) {
      super(p22, platformID, encodingID);
      this.format = 8;
      p22.uint16;
      this.length = p22.uint32;
      this.language = p22.uint32;
      this.is32 = [...new Array(8192)].map((_) => p22.uint8);
      this.numGroups = p22.uint32;
      const getter = () => [...new Array(this.numGroups)].map(
        (_) => new SequentialMapGroup$1(p22)
      );
      lazy$1(this, `groups`, getter);
    }
    supports(charCode) {
      if (charCode.charCodeAt) {
        charCode = -1;
        console.warn(
          `supports(character) not implemented for cmap subtable format 8. only supports(id) is implemented.`
        );
      }
      return this.groups.findIndex(
        (s2) => s2.startcharCode <= charCode && charCode <= s2.endcharCode
      ) !== -1;
    }
    reverse(glyphID) {
      console.warn(`reverse not implemented for cmap subtable format 8`);
      return {};
    }
    getSupportedCharCodes(preservePropNames = false) {
      if (preservePropNames) return this.groups;
      return this.groups.map((v2) => ({
        start: v2.startcharCode,
        end: v2.endcharCode
      }));
    }
  };
  var SequentialMapGroup$1 = class {
    constructor(p22) {
      this.startcharCode = p22.uint32;
      this.endcharCode = p22.uint32;
      this.startGlyphID = p22.uint32;
    }
  };
  var Format10 = class extends Subtable {
    constructor(p22, platformID, encodingID) {
      super(p22, platformID, encodingID);
      this.format = 10;
      p22.uint16;
      this.length = p22.uint32;
      this.language = p22.uint32;
      this.startCharCode = p22.uint32;
      this.numChars = p22.uint32;
      this.endCharCode = this.startCharCode + this.numChars;
      const getter = () => [...new Array(this.numChars)].map((_) => p22.uint16);
      lazy$1(this, `glyphs`, getter);
    }
    supports(charCode) {
      if (charCode.charCodeAt) {
        charCode = -1;
        console.warn(
          `supports(character) not implemented for cmap subtable format 10. only supports(id) is implemented.`
        );
      }
      if (charCode < this.startCharCode) return false;
      if (charCode > this.startCharCode + this.numChars) return false;
      return charCode - this.startCharCode;
    }
    reverse(glyphID) {
      console.warn(`reverse not implemented for cmap subtable format 10`);
      return {};
    }
    getSupportedCharCodes(preservePropNames = false) {
      if (preservePropNames) {
        return [
          {
            startCharCode: this.startCharCode,
            endCharCode: this.endCharCode
          }
        ];
      }
      return [{ start: this.startCharCode, end: this.endCharCode }];
    }
  };
  var Format12 = class extends Subtable {
    constructor(p22, platformID, encodingID) {
      super(p22, platformID, encodingID);
      this.format = 12;
      p22.uint16;
      this.length = p22.uint32;
      this.language = p22.uint32;
      this.numGroups = p22.uint32;
      const getter = () => [...new Array(this.numGroups)].map(
        (_) => new SequentialMapGroup(p22)
      );
      lazy$1(this, `groups`, getter);
    }
    supports(charCode) {
      if (charCode.charCodeAt) charCode = charCode.charCodeAt(0);
      if (55296 <= charCode && charCode <= 57343) return 0;
      if ((charCode & 65534) === 65534 || (charCode & 65535) === 65535)
        return 0;
      return this.groups.findIndex(
        (s2) => s2.startCharCode <= charCode && charCode <= s2.endCharCode
      ) !== -1;
    }
    reverse(glyphID) {
      for (let group of this.groups) {
        let start2 = group.startGlyphID;
        if (start2 > glyphID) continue;
        if (start2 === glyphID) return group.startCharCode;
        let end = start2 + (group.endCharCode - group.startCharCode);
        if (end < glyphID) continue;
        const code = group.startCharCode + (glyphID - start2);
        return { code, unicode: String.fromCodePoint(code) };
      }
      return {};
    }
    getSupportedCharCodes(preservePropNames = false) {
      if (preservePropNames) return this.groups;
      return this.groups.map((v2) => ({
        start: v2.startCharCode,
        end: v2.endCharCode
      }));
    }
  };
  var SequentialMapGroup = class {
    constructor(p22) {
      this.startCharCode = p22.uint32;
      this.endCharCode = p22.uint32;
      this.startGlyphID = p22.uint32;
    }
  };
  var Format13 = class extends Subtable {
    constructor(p22, platformID, encodingID) {
      super(p22, platformID, encodingID);
      this.format = 13;
      p22.uint16;
      this.length = p22.uint32;
      this.language = p22.uint32;
      this.numGroups = p22.uint32;
      const getter = [...new Array(this.numGroups)].map(
        (_) => new ConstantMapGroup(p22)
      );
      lazy$1(this, `groups`, getter);
    }
    supports(charCode) {
      if (charCode.charCodeAt) charCode = charCode.charCodeAt(0);
      return this.groups.findIndex(
        (s2) => s2.startCharCode <= charCode && charCode <= s2.endCharCode
      ) !== -1;
    }
    reverse(glyphID) {
      console.warn(`reverse not implemented for cmap subtable format 13`);
      return {};
    }
    getSupportedCharCodes(preservePropNames = false) {
      if (preservePropNames) return this.groups;
      return this.groups.map((v2) => ({
        start: v2.startCharCode,
        end: v2.endCharCode
      }));
    }
  };
  var ConstantMapGroup = class {
    constructor(p22) {
      this.startCharCode = p22.uint32;
      this.endCharCode = p22.uint32;
      this.glyphID = p22.uint32;
    }
  };
  var Format14 = class extends Subtable {
    constructor(p22, platformID, encodingID) {
      super(p22, platformID, encodingID);
      this.subTableStart = p22.currentPosition;
      this.format = 14;
      this.length = p22.uint32;
      this.numVarSelectorRecords = p22.uint32;
      lazy$1(
        this,
        `varSelectors`,
        () => [...new Array(this.numVarSelectorRecords)].map(
          (_) => new VariationSelector(p22)
        )
      );
    }
    supports() {
      console.warn(`supports not implemented for cmap subtable format 14`);
      return 0;
    }
    getSupportedCharCodes() {
      console.warn(
        `getSupportedCharCodes not implemented for cmap subtable format 14`
      );
      return [];
    }
    reverse(glyphID) {
      console.warn(`reverse not implemented for cmap subtable format 14`);
      return {};
    }
    supportsVariation(variation) {
      let v2 = this.varSelector.find(
        (uvs) => uvs.varSelector === variation
      );
      return v2 ? v2 : false;
    }
    getSupportedVariations() {
      return this.varSelectors.map((v2) => v2.varSelector);
    }
  };
  var VariationSelector = class {
    constructor(p22) {
      this.varSelector = p22.uint24;
      this.defaultUVSOffset = p22.Offset32;
      this.nonDefaultUVSOffset = p22.Offset32;
    }
  };
  function createSubTable(parser, platformID, encodingID) {
    const format6 = parser.uint16;
    if (format6 === 0) return new Format0(parser, platformID, encodingID);
    if (format6 === 2) return new Format2(parser, platformID, encodingID);
    if (format6 === 4) return new Format4(parser, platformID, encodingID);
    if (format6 === 6) return new Format6(parser, platformID, encodingID);
    if (format6 === 8) return new Format8(parser, platformID, encodingID);
    if (format6 === 10) return new Format10(parser, platformID, encodingID);
    if (format6 === 12) return new Format12(parser, platformID, encodingID);
    if (format6 === 13) return new Format13(parser, platformID, encodingID);
    if (format6 === 14) return new Format14(parser, platformID, encodingID);
    return {};
  }
  var cmap = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.numTables = p22.uint16;
      this.encodingRecords = [...new Array(this.numTables)].map(
        (_) => new EncodingRecord(p22, this.tableStart)
      );
    }
    getSubTable(tableID) {
      return this.encodingRecords[tableID].table;
    }
    getSupportedEncodings() {
      return this.encodingRecords.map((r3) => ({
        platformID: r3.platformID,
        encodingId: r3.encodingID
      }));
    }
    getSupportedCharCodes(platformID, encodingID) {
      const recordID = this.encodingRecords.findIndex(
        (r3) => r3.platformID === platformID && r3.encodingID === encodingID
      );
      if (recordID === -1) return false;
      const subtable = this.getSubTable(recordID);
      return subtable.getSupportedCharCodes();
    }
    reverse(glyphid) {
      for (let i2 = 0; i2 < this.numTables; i2++) {
        let code = this.getSubTable(i2).reverse(glyphid);
        if (code) return code;
      }
    }
    getGlyphId(char) {
      let last = 0;
      this.encodingRecords.some((_, tableID) => {
        let t3 = this.getSubTable(tableID);
        if (!t3.getGlyphId) return false;
        last = t3.getGlyphId(char);
        return last !== 0;
      });
      return last;
    }
    supports(char) {
      return this.encodingRecords.some((_, tableID) => {
        const t3 = this.getSubTable(tableID);
        return t3.supports && t3.supports(char) !== false;
      });
    }
    supportsVariation(variation) {
      return this.encodingRecords.some((_, tableID) => {
        const t3 = this.getSubTable(tableID);
        return t3.supportsVariation && t3.supportsVariation(variation) !== false;
      });
    }
  };
  var EncodingRecord = class {
    constructor(p22, tableStart) {
      const platformID = this.platformID = p22.uint16;
      const encodingID = this.encodingID = p22.uint16;
      const offset4 = this.offset = p22.Offset32;
      lazy$1(this, `table`, () => {
        p22.currentPosition = tableStart + offset4;
        return createSubTable(p22, platformID, encodingID);
      });
    }
  };
  var cmap$1 = Object.freeze({ __proto__: null, cmap });
  var head = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.load({
        majorVersion: p22.uint16,
        minorVersion: p22.uint16,
        fontRevision: p22.fixed,
        checkSumAdjustment: p22.uint32,
        magicNumber: p22.uint32,
        flags: p22.flags(16),
        unitsPerEm: p22.uint16,
        created: p22.longdatetime,
        modified: p22.longdatetime,
        xMin: p22.int16,
        yMin: p22.int16,
        xMax: p22.int16,
        yMax: p22.int16,
        macStyle: p22.flags(16),
        lowestRecPPEM: p22.uint16,
        fontDirectionHint: p22.uint16,
        indexToLocFormat: p22.uint16,
        glyphDataFormat: p22.uint16
      });
    }
  };
  var head$1 = Object.freeze({ __proto__: null, head });
  var hhea = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
      this.ascender = p22.fword;
      this.descender = p22.fword;
      this.lineGap = p22.fword;
      this.advanceWidthMax = p22.ufword;
      this.minLeftSideBearing = p22.fword;
      this.minRightSideBearing = p22.fword;
      this.xMaxExtent = p22.fword;
      this.caretSlopeRise = p22.int16;
      this.caretSlopeRun = p22.int16;
      this.caretOffset = p22.int16;
      p22.int16;
      p22.int16;
      p22.int16;
      p22.int16;
      this.metricDataFormat = p22.int16;
      this.numberOfHMetrics = p22.uint16;
      p22.verifyLength();
    }
  };
  var hhea$1 = Object.freeze({ __proto__: null, hhea });
  var hmtx = class extends SimpleTable {
    constructor(dict, dataview, tables) {
      const { p: p22 } = super(dict, dataview);
      const numberOfHMetrics = tables.hhea.numberOfHMetrics;
      const numGlyphs = tables.maxp.numGlyphs;
      const metricsStart = p22.currentPosition;
      lazy$1(this, `hMetrics`, () => {
        p22.currentPosition = metricsStart;
        return [...new Array(numberOfHMetrics)].map(
          (_) => new LongHorMetric(p22.uint16, p22.int16)
        );
      });
      if (numberOfHMetrics < numGlyphs) {
        const lsbStart = metricsStart + numberOfHMetrics * 4;
        lazy$1(this, `leftSideBearings`, () => {
          p22.currentPosition = lsbStart;
          return [...new Array(numGlyphs - numberOfHMetrics)].map(
            (_) => p22.int16
          );
        });
      }
    }
  };
  var LongHorMetric = class {
    constructor(w2, b2) {
      this.advanceWidth = w2;
      this.lsb = b2;
    }
  };
  var hmtx$1 = Object.freeze({ __proto__: null, hmtx });
  var maxp = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.legacyFixed;
      this.numGlyphs = p22.uint16;
      if (this.version === 1) {
        this.maxPoints = p22.uint16;
        this.maxContours = p22.uint16;
        this.maxCompositePoints = p22.uint16;
        this.maxCompositeContours = p22.uint16;
        this.maxZones = p22.uint16;
        this.maxTwilightPoints = p22.uint16;
        this.maxStorage = p22.uint16;
        this.maxFunctionDefs = p22.uint16;
        this.maxInstructionDefs = p22.uint16;
        this.maxStackElements = p22.uint16;
        this.maxSizeOfInstructions = p22.uint16;
        this.maxComponentElements = p22.uint16;
        this.maxComponentDepth = p22.uint16;
      }
      p22.verifyLength();
    }
  };
  var maxp$1 = Object.freeze({ __proto__: null, maxp });
  var name = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.format = p22.uint16;
      this.count = p22.uint16;
      this.stringOffset = p22.Offset16;
      this.nameRecords = [...new Array(this.count)].map(
        (_) => new NameRecord(p22, this)
      );
      if (this.format === 1) {
        this.langTagCount = p22.uint16;
        this.langTagRecords = [...new Array(this.langTagCount)].map(
          (_) => new LangTagRecord(p22.uint16, p22.Offset16)
        );
      }
      this.stringStart = this.tableStart + this.stringOffset;
    }
    get(nameID) {
      let record = this.nameRecords.find(
        (record2) => record2.nameID === nameID
      );
      if (record) return record.string;
    }
  };
  var LangTagRecord = class {
    constructor(length, offset4) {
      this.length = length;
      this.offset = offset4;
    }
  };
  var NameRecord = class {
    constructor(p22, nameTable) {
      this.platformID = p22.uint16;
      this.encodingID = p22.uint16;
      this.languageID = p22.uint16;
      this.nameID = p22.uint16;
      this.length = p22.uint16;
      this.offset = p22.Offset16;
      lazy$1(this, `string`, () => {
        p22.currentPosition = nameTable.stringStart + this.offset;
        return decodeString(p22, this);
      });
    }
  };
  function decodeString(p22, record) {
    const { platformID, length } = record;
    if (length === 0) return ``;
    if (platformID === 0 || platformID === 3) {
      const str2 = [];
      for (let i2 = 0, e2 = length / 2; i2 < e2; i2++)
        str2[i2] = String.fromCharCode(p22.uint16);
      return str2.join(``);
    }
    const bytes = p22.readBytes(length);
    const str = [];
    bytes.forEach(function(b2, i2) {
      str[i2] = String.fromCharCode(b2);
    });
    return str.join(``);
  }
  var name$1 = Object.freeze({ __proto__: null, name });
  var OS2 = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.xAvgCharWidth = p22.int16;
      this.usWeightClass = p22.uint16;
      this.usWidthClass = p22.uint16;
      this.fsType = p22.uint16;
      this.ySubscriptXSize = p22.int16;
      this.ySubscriptYSize = p22.int16;
      this.ySubscriptXOffset = p22.int16;
      this.ySubscriptYOffset = p22.int16;
      this.ySuperscriptXSize = p22.int16;
      this.ySuperscriptYSize = p22.int16;
      this.ySuperscriptXOffset = p22.int16;
      this.ySuperscriptYOffset = p22.int16;
      this.yStrikeoutSize = p22.int16;
      this.yStrikeoutPosition = p22.int16;
      this.sFamilyClass = p22.int16;
      this.panose = [...new Array(10)].map((_) => p22.uint8);
      this.ulUnicodeRange1 = p22.flags(32);
      this.ulUnicodeRange2 = p22.flags(32);
      this.ulUnicodeRange3 = p22.flags(32);
      this.ulUnicodeRange4 = p22.flags(32);
      this.achVendID = p22.tag;
      this.fsSelection = p22.uint16;
      this.usFirstCharIndex = p22.uint16;
      this.usLastCharIndex = p22.uint16;
      this.sTypoAscender = p22.int16;
      this.sTypoDescender = p22.int16;
      this.sTypoLineGap = p22.int16;
      this.usWinAscent = p22.uint16;
      this.usWinDescent = p22.uint16;
      if (this.version === 0) return p22.verifyLength();
      this.ulCodePageRange1 = p22.flags(32);
      this.ulCodePageRange2 = p22.flags(32);
      if (this.version === 1) return p22.verifyLength();
      this.sxHeight = p22.int16;
      this.sCapHeight = p22.int16;
      this.usDefaultChar = p22.uint16;
      this.usBreakChar = p22.uint16;
      this.usMaxContext = p22.uint16;
      if (this.version <= 4) return p22.verifyLength();
      this.usLowerOpticalPointSize = p22.uint16;
      this.usUpperOpticalPointSize = p22.uint16;
      if (this.version === 5) return p22.verifyLength();
    }
  };
  var OS2$1 = Object.freeze({ __proto__: null, OS2 });
  var post = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.legacyFixed;
      this.italicAngle = p22.fixed;
      this.underlinePosition = p22.fword;
      this.underlineThickness = p22.fword;
      this.isFixedPitch = p22.uint32;
      this.minMemType42 = p22.uint32;
      this.maxMemType42 = p22.uint32;
      this.minMemType1 = p22.uint32;
      this.maxMemType1 = p22.uint32;
      if (this.version === 1 || this.version === 3) return p22.verifyLength();
      this.numGlyphs = p22.uint16;
      if (this.version === 2) {
        this.glyphNameIndex = [...new Array(this.numGlyphs)].map(
          (_) => p22.uint16
        );
        this.namesOffset = p22.currentPosition;
        this.glyphNameOffsets = [1];
        for (let i2 = 0; i2 < this.numGlyphs; i2++) {
          let index2 = this.glyphNameIndex[i2];
          if (index2 < macStrings.length) {
            this.glyphNameOffsets.push(this.glyphNameOffsets[i2]);
            continue;
          }
          let bytelength = p22.int8;
          p22.skip(bytelength);
          this.glyphNameOffsets.push(
            this.glyphNameOffsets[i2] + bytelength + 1
          );
        }
      }
      if (this.version === 2.5) {
        this.offset = [...new Array(this.numGlyphs)].map(
          (_) => p22.int8
        );
      }
    }
    getGlyphName(glyphid) {
      if (this.version !== 2) {
        console.warn(
          `post table version ${this.version} does not support glyph name lookups`
        );
        return ``;
      }
      let index2 = this.glyphNameIndex[glyphid];
      if (index2 < 258) return macStrings[index2];
      let offset4 = this.glyphNameOffsets[glyphid];
      let next = this.glyphNameOffsets[glyphid + 1];
      let len = next - offset4 - 1;
      if (len === 0) return `.notdef.`;
      this.parser.currentPosition = this.namesOffset + offset4;
      const data = this.parser.readBytes(
        len,
        this.namesOffset + offset4,
        8,
        true
      );
      return data.map((b2) => String.fromCharCode(b2)).join(``);
    }
  };
  var macStrings = [
    `.notdef`,
    `.null`,
    `nonmarkingreturn`,
    `space`,
    `exclam`,
    `quotedbl`,
    `numbersign`,
    `dollar`,
    `percent`,
    `ampersand`,
    `quotesingle`,
    `parenleft`,
    `parenright`,
    `asterisk`,
    `plus`,
    `comma`,
    `hyphen`,
    `period`,
    `slash`,
    `zero`,
    `one`,
    `two`,
    `three`,
    `four`,
    `five`,
    `six`,
    `seven`,
    `eight`,
    `nine`,
    `colon`,
    `semicolon`,
    `less`,
    `equal`,
    `greater`,
    `question`,
    `at`,
    `A`,
    `B`,
    `C`,
    `D`,
    `E`,
    `F`,
    `G`,
    `H`,
    `I`,
    `J`,
    `K`,
    `L`,
    `M`,
    `N`,
    `O`,
    `P`,
    `Q`,
    `R`,
    `S`,
    `T`,
    `U`,
    `V`,
    `W`,
    `X`,
    `Y`,
    `Z`,
    `bracketleft`,
    `backslash`,
    `bracketright`,
    `asciicircum`,
    `underscore`,
    `grave`,
    `a`,
    `b`,
    `c`,
    `d`,
    `e`,
    `f`,
    `g`,
    `h`,
    `i`,
    `j`,
    `k`,
    `l`,
    `m`,
    `n`,
    `o`,
    `p`,
    `q`,
    `r`,
    `s`,
    `t`,
    `u`,
    `v`,
    `w`,
    `x`,
    `y`,
    `z`,
    `braceleft`,
    `bar`,
    `braceright`,
    `asciitilde`,
    `Adieresis`,
    `Aring`,
    `Ccedilla`,
    `Eacute`,
    `Ntilde`,
    `Odieresis`,
    `Udieresis`,
    `aacute`,
    `agrave`,
    `acircumflex`,
    `adieresis`,
    `atilde`,
    `aring`,
    `ccedilla`,
    `eacute`,
    `egrave`,
    `ecircumflex`,
    `edieresis`,
    `iacute`,
    `igrave`,
    `icircumflex`,
    `idieresis`,
    `ntilde`,
    `oacute`,
    `ograve`,
    `ocircumflex`,
    `odieresis`,
    `otilde`,
    `uacute`,
    `ugrave`,
    `ucircumflex`,
    `udieresis`,
    `dagger`,
    `degree`,
    `cent`,
    `sterling`,
    `section`,
    `bullet`,
    `paragraph`,
    `germandbls`,
    `registered`,
    `copyright`,
    `trademark`,
    `acute`,
    `dieresis`,
    `notequal`,
    `AE`,
    `Oslash`,
    `infinity`,
    `plusminus`,
    `lessequal`,
    `greaterequal`,
    `yen`,
    `mu`,
    `partialdiff`,
    `summation`,
    `product`,
    `pi`,
    `integral`,
    `ordfeminine`,
    `ordmasculine`,
    `Omega`,
    `ae`,
    `oslash`,
    `questiondown`,
    `exclamdown`,
    `logicalnot`,
    `radical`,
    `florin`,
    `approxequal`,
    `Delta`,
    `guillemotleft`,
    `guillemotright`,
    `ellipsis`,
    `nonbreakingspace`,
    `Agrave`,
    `Atilde`,
    `Otilde`,
    `OE`,
    `oe`,
    `endash`,
    `emdash`,
    `quotedblleft`,
    `quotedblright`,
    `quoteleft`,
    `quoteright`,
    `divide`,
    `lozenge`,
    `ydieresis`,
    `Ydieresis`,
    `fraction`,
    `currency`,
    `guilsinglleft`,
    `guilsinglright`,
    `fi`,
    `fl`,
    `daggerdbl`,
    `periodcentered`,
    `quotesinglbase`,
    `quotedblbase`,
    `perthousand`,
    `Acircumflex`,
    `Ecircumflex`,
    `Aacute`,
    `Edieresis`,
    `Egrave`,
    `Iacute`,
    `Icircumflex`,
    `Idieresis`,
    `Igrave`,
    `Oacute`,
    `Ocircumflex`,
    `apple`,
    `Ograve`,
    `Uacute`,
    `Ucircumflex`,
    `Ugrave`,
    `dotlessi`,
    `circumflex`,
    `tilde`,
    `macron`,
    `breve`,
    `dotaccent`,
    `ring`,
    `cedilla`,
    `hungarumlaut`,
    `ogonek`,
    `caron`,
    `Lslash`,
    `lslash`,
    `Scaron`,
    `scaron`,
    `Zcaron`,
    `zcaron`,
    `brokenbar`,
    `Eth`,
    `eth`,
    `Yacute`,
    `yacute`,
    `Thorn`,
    `thorn`,
    `minus`,
    `multiply`,
    `onesuperior`,
    `twosuperior`,
    `threesuperior`,
    `onehalf`,
    `onequarter`,
    `threequarters`,
    `franc`,
    `Gbreve`,
    `gbreve`,
    `Idotaccent`,
    `Scedilla`,
    `scedilla`,
    `Cacute`,
    `cacute`,
    `Ccaron`,
    `ccaron`,
    `dcroat`
  ];
  var post$1 = Object.freeze({ __proto__: null, post });
  var BASE = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
      this.horizAxisOffset = p22.Offset16;
      this.vertAxisOffset = p22.Offset16;
      lazy$1(
        this,
        `horizAxis`,
        () => new AxisTable(
          { offset: dict.offset + this.horizAxisOffset },
          dataview
        )
      );
      lazy$1(
        this,
        `vertAxis`,
        () => new AxisTable(
          { offset: dict.offset + this.vertAxisOffset },
          dataview
        )
      );
      if (this.majorVersion === 1 && this.minorVersion === 1) {
        this.itemVarStoreOffset = p22.Offset32;
        lazy$1(
          this,
          `itemVarStore`,
          () => new AxisTable(
            { offset: dict.offset + this.itemVarStoreOffset },
            dataview
          )
        );
      }
    }
  };
  var AxisTable = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview, `AxisTable`);
      this.baseTagListOffset = p22.Offset16;
      this.baseScriptListOffset = p22.Offset16;
      lazy$1(
        this,
        `baseTagList`,
        () => new BaseTagListTable(
          { offset: dict.offset + this.baseTagListOffset },
          dataview
        )
      );
      lazy$1(
        this,
        `baseScriptList`,
        () => new BaseScriptListTable(
          { offset: dict.offset + this.baseScriptListOffset },
          dataview
        )
      );
    }
  };
  var BaseTagListTable = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview, `BaseTagListTable`);
      this.baseTagCount = p22.uint16;
      this.baselineTags = [...new Array(this.baseTagCount)].map(
        (_) => p22.tag
      );
    }
  };
  var BaseScriptListTable = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview, `BaseScriptListTable`);
      this.baseScriptCount = p22.uint16;
      const recordStart = p22.currentPosition;
      lazy$1(this, `baseScriptRecords`, () => {
        p22.currentPosition = recordStart;
        return [...new Array(this.baseScriptCount)].map(
          (_) => new BaseScriptRecord(this.start, p22)
        );
      });
    }
  };
  var BaseScriptRecord = class {
    constructor(baseScriptListTableStart, p22) {
      this.baseScriptTag = p22.tag;
      this.baseScriptOffset = p22.Offset16;
      lazy$1(this, `baseScriptTable`, () => {
        p22.currentPosition = baseScriptListTableStart + this.baseScriptOffset;
        return new BaseScriptTable(p22);
      });
    }
  };
  var BaseScriptTable = class {
    constructor(p22) {
      this.start = p22.currentPosition;
      this.baseValuesOffset = p22.Offset16;
      this.defaultMinMaxOffset = p22.Offset16;
      this.baseLangSysCount = p22.uint16;
      this.baseLangSysRecords = [...new Array(this.baseLangSysCount)].map(
        (_) => new BaseLangSysRecord(this.start, p22)
      );
      lazy$1(this, `baseValues`, () => {
        p22.currentPosition = this.start + this.baseValuesOffset;
        return new BaseValuesTable(p22);
      });
      lazy$1(this, `defaultMinMax`, () => {
        p22.currentPosition = this.start + this.defaultMinMaxOffset;
        return new MinMaxTable(p22);
      });
    }
  };
  var BaseLangSysRecord = class {
    constructor(baseScriptTableStart, p22) {
      this.baseLangSysTag = p22.tag;
      this.minMaxOffset = p22.Offset16;
      lazy$1(this, `minMax`, () => {
        p22.currentPosition = baseScriptTableStart + this.minMaxOffset;
        return new MinMaxTable(p22);
      });
    }
  };
  var BaseValuesTable = class {
    constructor(p22) {
      this.parser = p22;
      this.start = p22.currentPosition;
      this.defaultBaselineIndex = p22.uint16;
      this.baseCoordCount = p22.uint16;
      this.baseCoords = [...new Array(this.baseCoordCount)].map(
        (_) => p22.Offset16
      );
    }
    getTable(id) {
      this.parser.currentPosition = this.start + this.baseCoords[id];
      return new BaseCoordTable(this.parser);
    }
  };
  var MinMaxTable = class {
    constructor(p22) {
      this.minCoord = p22.Offset16;
      this.maxCoord = p22.Offset16;
      this.featMinMaxCount = p22.uint16;
      const recordStart = p22.currentPosition;
      lazy$1(this, `featMinMaxRecords`, () => {
        p22.currentPosition = recordStart;
        return [...new Array(this.featMinMaxCount)].map(
          (_) => new FeatMinMaxRecord(p22)
        );
      });
    }
  };
  var FeatMinMaxRecord = class {
    constructor(p22) {
      this.featureTableTag = p22.tag;
      this.minCoord = p22.Offset16;
      this.maxCoord = p22.Offset16;
    }
  };
  var BaseCoordTable = class {
    constructor(p22) {
      this.baseCoordFormat = p22.uint16;
      this.coordinate = p22.int16;
      if (this.baseCoordFormat === 2) {
        this.referenceGlyph = p22.uint16;
        this.baseCoordPoint = p22.uint16;
      }
      if (this.baseCoordFormat === 3) {
        this.deviceTable = p22.Offset16;
      }
    }
  };
  var BASE$1 = Object.freeze({ __proto__: null, BASE });
  var ClassDefinition = class {
    constructor(p22) {
      this.classFormat = p22.uint16;
      if (this.classFormat === 1) {
        this.startGlyphID = p22.uint16;
        this.glyphCount = p22.uint16;
        this.classValueArray = [...new Array(this.glyphCount)].map(
          (_) => p22.uint16
        );
      }
      if (this.classFormat === 2) {
        this.classRangeCount = p22.uint16;
        this.classRangeRecords = [
          ...new Array(this.classRangeCount)
        ].map((_) => new ClassRangeRecord(p22));
      }
    }
  };
  var ClassRangeRecord = class {
    constructor(p22) {
      this.startGlyphID = p22.uint16;
      this.endGlyphID = p22.uint16;
      this.class = p22.uint16;
    }
  };
  var CoverageTable = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.coverageFormat = p22.uint16;
      if (this.coverageFormat === 1) {
        this.glyphCount = p22.uint16;
        this.glyphArray = [...new Array(this.glyphCount)].map(
          (_) => p22.uint16
        );
      }
      if (this.coverageFormat === 2) {
        this.rangeCount = p22.uint16;
        this.rangeRecords = [...new Array(this.rangeCount)].map(
          (_) => new CoverageRangeRecord(p22)
        );
      }
    }
  };
  var CoverageRangeRecord = class {
    constructor(p22) {
      this.startGlyphID = p22.uint16;
      this.endGlyphID = p22.uint16;
      this.startCoverageIndex = p22.uint16;
    }
  };
  var ItemVariationStoreTable = class {
    constructor(table, p22) {
      this.table = table;
      this.parser = p22;
      this.start = p22.currentPosition;
      this.format = p22.uint16;
      this.variationRegionListOffset = p22.Offset32;
      this.itemVariationDataCount = p22.uint16;
      this.itemVariationDataOffsets = [
        ...new Array(this.itemVariationDataCount)
      ].map((_) => p22.Offset32);
    }
  };
  var GDEF = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
      this.glyphClassDefOffset = p22.Offset16;
      lazy$1(this, `glyphClassDefs`, () => {
        if (this.glyphClassDefOffset === 0) return void 0;
        p22.currentPosition = this.tableStart + this.glyphClassDefOffset;
        return new ClassDefinition(p22);
      });
      this.attachListOffset = p22.Offset16;
      lazy$1(this, `attachList`, () => {
        if (this.attachListOffset === 0) return void 0;
        p22.currentPosition = this.tableStart + this.attachListOffset;
        return new AttachList(p22);
      });
      this.ligCaretListOffset = p22.Offset16;
      lazy$1(this, `ligCaretList`, () => {
        if (this.ligCaretListOffset === 0) return void 0;
        p22.currentPosition = this.tableStart + this.ligCaretListOffset;
        return new LigCaretList(p22);
      });
      this.markAttachClassDefOffset = p22.Offset16;
      lazy$1(this, `markAttachClassDef`, () => {
        if (this.markAttachClassDefOffset === 0) return void 0;
        p22.currentPosition = this.tableStart + this.markAttachClassDefOffset;
        return new ClassDefinition(p22);
      });
      if (this.minorVersion >= 2) {
        this.markGlyphSetsDefOffset = p22.Offset16;
        lazy$1(this, `markGlyphSetsDef`, () => {
          if (this.markGlyphSetsDefOffset === 0) return void 0;
          p22.currentPosition = this.tableStart + this.markGlyphSetsDefOffset;
          return new MarkGlyphSetsTable(p22);
        });
      }
      if (this.minorVersion === 3) {
        this.itemVarStoreOffset = p22.Offset32;
        lazy$1(this, `itemVarStore`, () => {
          if (this.itemVarStoreOffset === 0) return void 0;
          p22.currentPosition = this.tableStart + this.itemVarStoreOffset;
          return new ItemVariationStoreTable(p22);
        });
      }
    }
  };
  var AttachList = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.coverageOffset = p22.Offset16;
      this.glyphCount = p22.uint16;
      this.attachPointOffsets = [...new Array(this.glyphCount)].map(
        (_) => p22.Offset16
      );
    }
    getPoint(pointID) {
      this.parser.currentPosition = this.start + this.attachPointOffsets[pointID];
      return new AttachPoint(this.parser);
    }
  };
  var AttachPoint = class {
    constructor(p22) {
      this.pointCount = p22.uint16;
      this.pointIndices = [...new Array(this.pointCount)].map(
        (_) => p22.uint16
      );
    }
  };
  var LigCaretList = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.coverageOffset = p22.Offset16;
      lazy$1(this, `coverage`, () => {
        p22.currentPosition = this.start + this.coverageOffset;
        return new CoverageTable(p22);
      });
      this.ligGlyphCount = p22.uint16;
      this.ligGlyphOffsets = [...new Array(this.ligGlyphCount)].map(
        (_) => p22.Offset16
      );
    }
    getLigGlyph(ligGlyphID) {
      this.parser.currentPosition = this.start + this.ligGlyphOffsets[ligGlyphID];
      return new LigGlyph(this.parser);
    }
  };
  var LigGlyph = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.caretCount = p22.uint16;
      this.caretValueOffsets = [...new Array(this.caretCount)].map(
        (_) => p22.Offset16
      );
    }
    getCaretValue(caretID) {
      this.parser.currentPosition = this.start + this.caretValueOffsets[caretID];
      return new CaretValue(this.parser);
    }
  };
  var CaretValue = class {
    constructor(p22) {
      this.caretValueFormat = p22.uint16;
      if (this.caretValueFormat === 1) {
        this.coordinate = p22.int16;
      }
      if (this.caretValueFormat === 2) {
        this.caretValuePointIndex = p22.uint16;
      }
      if (this.caretValueFormat === 3) {
        this.coordinate = p22.int16;
        this.deviceOffset = p22.Offset16;
      }
    }
  };
  var MarkGlyphSetsTable = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.markGlyphSetTableFormat = p22.uint16;
      this.markGlyphSetCount = p22.uint16;
      this.coverageOffsets = [...new Array(this.markGlyphSetCount)].map(
        (_) => p22.Offset32
      );
    }
    getMarkGlyphSet(markGlyphSetID) {
      this.parser.currentPosition = this.start + this.coverageOffsets[markGlyphSetID];
      return new CoverageTable(this.parser);
    }
  };
  var GDEF$1 = Object.freeze({ __proto__: null, GDEF });
  var ScriptList = class extends ParsedData {
    static EMPTY = { scriptCount: 0, scriptRecords: [] };
    constructor(p22) {
      super(p22);
      this.scriptCount = p22.uint16;
      this.scriptRecords = [...new Array(this.scriptCount)].map(
        (_) => new ScriptRecord(p22)
      );
    }
  };
  var ScriptRecord = class {
    constructor(p22) {
      this.scriptTag = p22.tag;
      this.scriptOffset = p22.Offset16;
    }
  };
  var ScriptTable = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.defaultLangSys = p22.Offset16;
      this.langSysCount = p22.uint16;
      this.langSysRecords = [...new Array(this.langSysCount)].map(
        (_) => new LangSysRecord(p22)
      );
    }
  };
  var LangSysRecord = class {
    constructor(p22) {
      this.langSysTag = p22.tag;
      this.langSysOffset = p22.Offset16;
    }
  };
  var LangSysTable = class {
    constructor(p22) {
      this.lookupOrder = p22.Offset16;
      this.requiredFeatureIndex = p22.uint16;
      this.featureIndexCount = p22.uint16;
      this.featureIndices = [...new Array(this.featureIndexCount)].map(
        (_) => p22.uint16
      );
    }
  };
  var FeatureList = class extends ParsedData {
    static EMPTY = { featureCount: 0, featureRecords: [] };
    constructor(p22) {
      super(p22);
      this.featureCount = p22.uint16;
      this.featureRecords = [...new Array(this.featureCount)].map(
        (_) => new FeatureRecord(p22)
      );
    }
  };
  var FeatureRecord = class {
    constructor(p22) {
      this.featureTag = p22.tag;
      this.featureOffset = p22.Offset16;
    }
  };
  var FeatureTable = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.featureParams = p22.Offset16;
      this.lookupIndexCount = p22.uint16;
      this.lookupListIndices = [...new Array(this.lookupIndexCount)].map(
        (_) => p22.uint16
      );
    }
    getFeatureParams() {
      if (this.featureParams > 0) {
        const p22 = this.parser;
        p22.currentPosition = this.start + this.featureParams;
        const tag = this.featureTag;
        if (tag === `size`) return new Size(p22);
        if (tag.startsWith(`cc`)) return new CharacterVariant(p22);
        if (tag.startsWith(`ss`)) return new StylisticSet(p22);
      }
    }
  };
  var CharacterVariant = class {
    constructor(p22) {
      this.format = p22.uint16;
      this.featUiLabelNameId = p22.uint16;
      this.featUiTooltipTextNameId = p22.uint16;
      this.sampleTextNameId = p22.uint16;
      this.numNamedParameters = p22.uint16;
      this.firstParamUiLabelNameId = p22.uint16;
      this.charCount = p22.uint16;
      this.character = [...new Array(this.charCount)].map(
        (_) => p22.uint24
      );
    }
  };
  var Size = class {
    constructor(p22) {
      this.designSize = p22.uint16;
      this.subfamilyIdentifier = p22.uint16;
      this.subfamilyNameID = p22.uint16;
      this.smallEnd = p22.uint16;
      this.largeEnd = p22.uint16;
    }
  };
  var StylisticSet = class {
    constructor(p22) {
      this.version = p22.uint16;
      this.UINameID = p22.uint16;
    }
  };
  function undoCoverageOffsetParsing(instance) {
    instance.parser.currentPosition -= 2;
    delete instance.coverageOffset;
    delete instance.getCoverageTable;
  }
  var LookupType$1 = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.substFormat = p22.uint16;
      this.coverageOffset = p22.Offset16;
    }
    getCoverageTable() {
      let p22 = this.parser;
      p22.currentPosition = this.start + this.coverageOffset;
      return new CoverageTable(p22);
    }
  };
  var SubstLookupRecord = class {
    constructor(p22) {
      this.glyphSequenceIndex = p22.uint16;
      this.lookupListIndex = p22.uint16;
    }
  };
  var LookupType1$1 = class extends LookupType$1 {
    constructor(p22) {
      super(p22);
      this.deltaGlyphID = p22.int16;
    }
  };
  var LookupType2$1 = class extends LookupType$1 {
    constructor(p22) {
      super(p22);
      this.sequenceCount = p22.uint16;
      this.sequenceOffsets = [...new Array(this.sequenceCount)].map(
        (_) => p22.Offset16
      );
    }
    getSequence(index2) {
      let p22 = this.parser;
      p22.currentPosition = this.start + this.sequenceOffsets[index2];
      return new SequenceTable(p22);
    }
  };
  var SequenceTable = class {
    constructor(p22) {
      this.glyphCount = p22.uint16;
      this.substituteGlyphIDs = [...new Array(this.glyphCount)].map(
        (_) => p22.uint16
      );
    }
  };
  var LookupType3$1 = class extends LookupType$1 {
    constructor(p22) {
      super(p22);
      this.alternateSetCount = p22.uint16;
      this.alternateSetOffsets = [
        ...new Array(this.alternateSetCount)
      ].map((_) => p22.Offset16);
    }
    getAlternateSet(index2) {
      let p22 = this.parser;
      p22.currentPosition = this.start + this.alternateSetOffsets[index2];
      return new AlternateSetTable(p22);
    }
  };
  var AlternateSetTable = class {
    constructor(p22) {
      this.glyphCount = p22.uint16;
      this.alternateGlyphIDs = [...new Array(this.glyphCount)].map(
        (_) => p22.uint16
      );
    }
  };
  var LookupType4$1 = class extends LookupType$1 {
    constructor(p22) {
      super(p22);
      this.ligatureSetCount = p22.uint16;
      this.ligatureSetOffsets = [...new Array(this.ligatureSetCount)].map(
        (_) => p22.Offset16
      );
    }
    getLigatureSet(index2) {
      let p22 = this.parser;
      p22.currentPosition = this.start + this.ligatureSetOffsets[index2];
      return new LigatureSetTable(p22);
    }
  };
  var LigatureSetTable = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.ligatureCount = p22.uint16;
      this.ligatureOffsets = [...new Array(this.ligatureCount)].map(
        (_) => p22.Offset16
      );
    }
    getLigature(index2) {
      let p22 = this.parser;
      p22.currentPosition = this.start + this.ligatureOffsets[index2];
      return new LigatureTable(p22);
    }
  };
  var LigatureTable = class {
    constructor(p22) {
      this.ligatureGlyph = p22.uint16;
      this.componentCount = p22.uint16;
      this.componentGlyphIDs = [
        ...new Array(this.componentCount - 1)
      ].map((_) => p22.uint16);
    }
  };
  var LookupType5$1 = class extends LookupType$1 {
    constructor(p22) {
      super(p22);
      if (this.substFormat === 1) {
        this.subRuleSetCount = p22.uint16;
        this.subRuleSetOffsets = [
          ...new Array(this.subRuleSetCount)
        ].map((_) => p22.Offset16);
      }
      if (this.substFormat === 2) {
        this.classDefOffset = p22.Offset16;
        this.subClassSetCount = p22.uint16;
        this.subClassSetOffsets = [
          ...new Array(this.subClassSetCount)
        ].map((_) => p22.Offset16);
      }
      if (this.substFormat === 3) {
        undoCoverageOffsetParsing(this);
        this.glyphCount = p22.uint16;
        this.substitutionCount = p22.uint16;
        this.coverageOffsets = [...new Array(this.glyphCount)].map(
          (_) => p22.Offset16
        );
        this.substLookupRecords = [
          ...new Array(this.substitutionCount)
        ].map((_) => new SubstLookupRecord(p22));
      }
    }
    getSubRuleSet(index2) {
      if (this.substFormat !== 1)
        throw new Error(
          `lookup type 5.${this.substFormat} has no subrule sets.`
        );
      let p22 = this.parser;
      p22.currentPosition = this.start + this.subRuleSetOffsets[index2];
      return new SubRuleSetTable(p22);
    }
    getSubClassSet(index2) {
      if (this.substFormat !== 2)
        throw new Error(
          `lookup type 5.${this.substFormat} has no subclass sets.`
        );
      let p22 = this.parser;
      p22.currentPosition = this.start + this.subClassSetOffsets[index2];
      return new SubClassSetTable(p22);
    }
    getCoverageTable(index2) {
      if (this.substFormat !== 3 && !index2)
        return super.getCoverageTable();
      if (!index2)
        throw new Error(
          `lookup type 5.${this.substFormat} requires an coverage table index.`
        );
      let p22 = this.parser;
      p22.currentPosition = this.start + this.coverageOffsets[index2];
      return new CoverageTable(p22);
    }
  };
  var SubRuleSetTable = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.subRuleCount = p22.uint16;
      this.subRuleOffsets = [...new Array(this.subRuleCount)].map(
        (_) => p22.Offset16
      );
    }
    getSubRule(index2) {
      let p22 = this.parser;
      p22.currentPosition = this.start + this.subRuleOffsets[index2];
      return new SubRuleTable(p22);
    }
  };
  var SubRuleTable = class {
    constructor(p22) {
      this.glyphCount = p22.uint16;
      this.substitutionCount = p22.uint16;
      this.inputSequence = [...new Array(this.glyphCount - 1)].map(
        (_) => p22.uint16
      );
      this.substLookupRecords = [
        ...new Array(this.substitutionCount)
      ].map((_) => new SubstLookupRecord(p22));
    }
  };
  var SubClassSetTable = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.subClassRuleCount = p22.uint16;
      this.subClassRuleOffsets = [
        ...new Array(this.subClassRuleCount)
      ].map((_) => p22.Offset16);
    }
    getSubClass(index2) {
      let p22 = this.parser;
      p22.currentPosition = this.start + this.subClassRuleOffsets[index2];
      return new SubClassRuleTable(p22);
    }
  };
  var SubClassRuleTable = class extends SubRuleTable {
    constructor(p22) {
      super(p22);
    }
  };
  var LookupType6$1 = class extends LookupType$1 {
    constructor(p22) {
      super(p22);
      if (this.substFormat === 1) {
        this.chainSubRuleSetCount = p22.uint16;
        this.chainSubRuleSetOffsets = [
          ...new Array(this.chainSubRuleSetCount)
        ].map((_) => p22.Offset16);
      }
      if (this.substFormat === 2) {
        this.backtrackClassDefOffset = p22.Offset16;
        this.inputClassDefOffset = p22.Offset16;
        this.lookaheadClassDefOffset = p22.Offset16;
        this.chainSubClassSetCount = p22.uint16;
        this.chainSubClassSetOffsets = [
          ...new Array(this.chainSubClassSetCount)
        ].map((_) => p22.Offset16);
      }
      if (this.substFormat === 3) {
        undoCoverageOffsetParsing(this);
        this.backtrackGlyphCount = p22.uint16;
        this.backtrackCoverageOffsets = [
          ...new Array(this.backtrackGlyphCount)
        ].map((_) => p22.Offset16);
        this.inputGlyphCount = p22.uint16;
        this.inputCoverageOffsets = [
          ...new Array(this.inputGlyphCount)
        ].map((_) => p22.Offset16);
        this.lookaheadGlyphCount = p22.uint16;
        this.lookaheadCoverageOffsets = [
          ...new Array(this.lookaheadGlyphCount)
        ].map((_) => p22.Offset16);
        this.seqLookupCount = p22.uint16;
        this.seqLookupRecords = [
          ...new Array(this.substitutionCount)
        ].map((_) => new SequenceLookupRecord(p22));
      }
    }
    getChainSubRuleSet(index2) {
      if (this.substFormat !== 1)
        throw new Error(
          `lookup type 6.${this.substFormat} has no chainsubrule sets.`
        );
      let p22 = this.parser;
      p22.currentPosition = this.start + this.chainSubRuleSetOffsets[index2];
      return new ChainSubRuleSetTable(p22);
    }
    getChainSubClassSet(index2) {
      if (this.substFormat !== 2)
        throw new Error(
          `lookup type 6.${this.substFormat} has no chainsubclass sets.`
        );
      let p22 = this.parser;
      p22.currentPosition = this.start + this.chainSubClassSetOffsets[index2];
      return new ChainSubClassSetTable(p22);
    }
    getCoverageFromOffset(offset4) {
      if (this.substFormat !== 3)
        throw new Error(
          `lookup type 6.${this.substFormat} does not use contextual coverage offsets.`
        );
      let p22 = this.parser;
      p22.currentPosition = this.start + offset4;
      return new CoverageTable(p22);
    }
  };
  var ChainSubRuleSetTable = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.chainSubRuleCount = p22.uint16;
      this.chainSubRuleOffsets = [
        ...new Array(this.chainSubRuleCount)
      ].map((_) => p22.Offset16);
    }
    getSubRule(index2) {
      let p22 = this.parser;
      p22.currentPosition = this.start + this.chainSubRuleOffsets[index2];
      return new ChainSubRuleTable(p22);
    }
  };
  var ChainSubRuleTable = class {
    constructor(p22) {
      this.backtrackGlyphCount = p22.uint16;
      this.backtrackSequence = [
        ...new Array(this.backtrackGlyphCount)
      ].map((_) => p22.uint16);
      this.inputGlyphCount = p22.uint16;
      this.inputSequence = [...new Array(this.inputGlyphCount - 1)].map(
        (_) => p22.uint16
      );
      this.lookaheadGlyphCount = p22.uint16;
      this.lookAheadSequence = [
        ...new Array(this.lookAheadGlyphCount)
      ].map((_) => p22.uint16);
      this.substitutionCount = p22.uint16;
      this.substLookupRecords = [...new Array(this.SubstCount)].map(
        (_) => new SubstLookupRecord(p22)
      );
    }
  };
  var ChainSubClassSetTable = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.chainSubClassRuleCount = p22.uint16;
      this.chainSubClassRuleOffsets = [
        ...new Array(this.chainSubClassRuleCount)
      ].map((_) => p22.Offset16);
    }
    getSubClass(index2) {
      let p22 = this.parser;
      p22.currentPosition = this.start + this.chainSubRuleOffsets[index2];
      return new ChainSubClassRuleTable(p22);
    }
  };
  var ChainSubClassRuleTable = class {
    constructor(p22) {
      this.backtrackGlyphCount = p22.uint16;
      this.backtrackSequence = [
        ...new Array(this.backtrackGlyphCount)
      ].map((_) => p22.uint16);
      this.inputGlyphCount = p22.uint16;
      this.inputSequence = [...new Array(this.inputGlyphCount - 1)].map(
        (_) => p22.uint16
      );
      this.lookaheadGlyphCount = p22.uint16;
      this.lookAheadSequence = [
        ...new Array(this.lookAheadGlyphCount)
      ].map((_) => p22.uint16);
      this.substitutionCount = p22.uint16;
      this.substLookupRecords = [
        ...new Array(this.substitutionCount)
      ].map((_) => new SequenceLookupRecord(p22));
    }
  };
  var SequenceLookupRecord = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.sequenceIndex = p22.uint16;
      this.lookupListIndex = p22.uint16;
    }
  };
  var LookupType7$1 = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.substFormat = p22.uint16;
      this.extensionLookupType = p22.uint16;
      this.extensionOffset = p22.Offset32;
    }
  };
  var LookupType8$1 = class extends LookupType$1 {
    constructor(p22) {
      super(p22);
      this.backtrackGlyphCount = p22.uint16;
      this.backtrackCoverageOffsets = [
        ...new Array(this.backtrackGlyphCount)
      ].map((_) => p22.Offset16);
      this.lookaheadGlyphCount = p22.uint16;
      this.lookaheadCoverageOffsets = [
        new Array(this.lookaheadGlyphCount)
      ].map((_) => p22.Offset16);
      this.glyphCount = p22.uint16;
      this.substituteGlyphIDs = [...new Array(this.glyphCount)].map(
        (_) => p22.uint16
      );
    }
  };
  var GSUBtables = {
    buildSubtable: function(type, p22) {
      const subtable = new [
        void 0,
        LookupType1$1,
        LookupType2$1,
        LookupType3$1,
        LookupType4$1,
        LookupType5$1,
        LookupType6$1,
        LookupType7$1,
        LookupType8$1
      ][type](p22);
      subtable.type = type;
      return subtable;
    }
  };
  var LookupType = class extends ParsedData {
    constructor(p22) {
      super(p22);
    }
  };
  var LookupType1 = class extends LookupType {
    constructor(p22) {
      super(p22);
      console.log(`lookup type 1`);
    }
  };
  var LookupType2 = class extends LookupType {
    constructor(p22) {
      super(p22);
      console.log(`lookup type 2`);
    }
  };
  var LookupType3 = class extends LookupType {
    constructor(p22) {
      super(p22);
      console.log(`lookup type 3`);
    }
  };
  var LookupType4 = class extends LookupType {
    constructor(p22) {
      super(p22);
      console.log(`lookup type 4`);
    }
  };
  var LookupType5 = class extends LookupType {
    constructor(p22) {
      super(p22);
      console.log(`lookup type 5`);
    }
  };
  var LookupType6 = class extends LookupType {
    constructor(p22) {
      super(p22);
      console.log(`lookup type 6`);
    }
  };
  var LookupType7 = class extends LookupType {
    constructor(p22) {
      super(p22);
      console.log(`lookup type 7`);
    }
  };
  var LookupType8 = class extends LookupType {
    constructor(p22) {
      super(p22);
      console.log(`lookup type 8`);
    }
  };
  var LookupType9 = class extends LookupType {
    constructor(p22) {
      super(p22);
      console.log(`lookup type 9`);
    }
  };
  var GPOStables = {
    buildSubtable: function(type, p22) {
      const subtable = new [
        void 0,
        LookupType1,
        LookupType2,
        LookupType3,
        LookupType4,
        LookupType5,
        LookupType6,
        LookupType7,
        LookupType8,
        LookupType9
      ][type](p22);
      subtable.type = type;
      return subtable;
    }
  };
  var LookupList = class extends ParsedData {
    static EMPTY = { lookupCount: 0, lookups: [] };
    constructor(p22) {
      super(p22);
      this.lookupCount = p22.uint16;
      this.lookups = [...new Array(this.lookupCount)].map(
        (_) => p22.Offset16
      );
    }
  };
  var LookupTable = class extends ParsedData {
    constructor(p22, type) {
      super(p22);
      this.ctType = type;
      this.lookupType = p22.uint16;
      this.lookupFlag = p22.uint16;
      this.subTableCount = p22.uint16;
      this.subtableOffsets = [...new Array(this.subTableCount)].map(
        (_) => p22.Offset16
      );
      this.markFilteringSet = p22.uint16;
    }
    get rightToLeft() {
      return this.lookupFlag & true;
    }
    get ignoreBaseGlyphs() {
      return this.lookupFlag & true;
    }
    get ignoreLigatures() {
      return this.lookupFlag & true;
    }
    get ignoreMarks() {
      return this.lookupFlag & true;
    }
    get useMarkFilteringSet() {
      return this.lookupFlag & true;
    }
    get markAttachmentType() {
      return this.lookupFlag & true;
    }
    getSubTable(index2) {
      const builder = this.ctType === `GSUB` ? GSUBtables : GPOStables;
      this.parser.currentPosition = this.start + this.subtableOffsets[index2];
      return builder.buildSubtable(this.lookupType, this.parser);
    }
  };
  var CommonLayoutTable = class extends SimpleTable {
    constructor(dict, dataview, name2) {
      const { p: p22, tableStart } = super(dict, dataview, name2);
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
      this.scriptListOffset = p22.Offset16;
      this.featureListOffset = p22.Offset16;
      this.lookupListOffset = p22.Offset16;
      if (this.majorVersion === 1 && this.minorVersion === 1) {
        this.featureVariationsOffset = p22.Offset32;
      }
      const no_content = !(this.scriptListOffset || this.featureListOffset || this.lookupListOffset);
      lazy$1(this, `scriptList`, () => {
        if (no_content) return ScriptList.EMPTY;
        p22.currentPosition = tableStart + this.scriptListOffset;
        return new ScriptList(p22);
      });
      lazy$1(this, `featureList`, () => {
        if (no_content) return FeatureList.EMPTY;
        p22.currentPosition = tableStart + this.featureListOffset;
        return new FeatureList(p22);
      });
      lazy$1(this, `lookupList`, () => {
        if (no_content) return LookupList.EMPTY;
        p22.currentPosition = tableStart + this.lookupListOffset;
        return new LookupList(p22);
      });
      if (this.featureVariationsOffset) {
        lazy$1(this, `featureVariations`, () => {
          if (no_content) return FeatureVariations.EMPTY;
          p22.currentPosition = tableStart + this.featureVariationsOffset;
          return new FeatureVariations(p22);
        });
      }
    }
    getSupportedScripts() {
      return this.scriptList.scriptRecords.map((r3) => r3.scriptTag);
    }
    getScriptTable(scriptTag) {
      let record = this.scriptList.scriptRecords.find(
        (r3) => r3.scriptTag === scriptTag
      );
      this.parser.currentPosition = this.scriptList.start + record.scriptOffset;
      let table = new ScriptTable(this.parser);
      table.scriptTag = scriptTag;
      return table;
    }
    ensureScriptTable(arg) {
      if (typeof arg === "string") {
        return this.getScriptTable(arg);
      }
      return arg;
    }
    getSupportedLangSys(scriptTable) {
      scriptTable = this.ensureScriptTable(scriptTable);
      const hasDefault = scriptTable.defaultLangSys !== 0;
      const supported = scriptTable.langSysRecords.map(
        (l2) => l2.langSysTag
      );
      if (hasDefault) supported.unshift(`dflt`);
      return supported;
    }
    getDefaultLangSysTable(scriptTable) {
      scriptTable = this.ensureScriptTable(scriptTable);
      let offset4 = scriptTable.defaultLangSys;
      if (offset4 !== 0) {
        this.parser.currentPosition = scriptTable.start + offset4;
        let table = new LangSysTable(this.parser);
        table.langSysTag = ``;
        table.defaultForScript = scriptTable.scriptTag;
        return table;
      }
    }
    getLangSysTable(scriptTable, langSysTag = `dflt`) {
      if (langSysTag === `dflt`)
        return this.getDefaultLangSysTable(scriptTable);
      scriptTable = this.ensureScriptTable(scriptTable);
      let record = scriptTable.langSysRecords.find(
        (l2) => l2.langSysTag === langSysTag
      );
      this.parser.currentPosition = scriptTable.start + record.langSysOffset;
      let table = new LangSysTable(this.parser);
      table.langSysTag = langSysTag;
      return table;
    }
    getFeatures(langSysTable) {
      return langSysTable.featureIndices.map(
        (index2) => this.getFeature(index2)
      );
    }
    getFeature(indexOrTag) {
      let record;
      if (parseInt(indexOrTag) == indexOrTag) {
        record = this.featureList.featureRecords[indexOrTag];
      } else {
        record = this.featureList.featureRecords.find(
          (f2) => f2.featureTag === indexOrTag
        );
      }
      if (!record) return;
      this.parser.currentPosition = this.featureList.start + record.featureOffset;
      let table = new FeatureTable(this.parser);
      table.featureTag = record.featureTag;
      return table;
    }
    getLookups(featureTable) {
      return featureTable.lookupListIndices.map(
        (index2) => this.getLookup(index2)
      );
    }
    getLookup(lookupIndex, type) {
      let lookupOffset = this.lookupList.lookups[lookupIndex];
      this.parser.currentPosition = this.lookupList.start + lookupOffset;
      return new LookupTable(this.parser, type);
    }
  };
  var GSUB = class extends CommonLayoutTable {
    constructor(dict, dataview) {
      super(dict, dataview, `GSUB`);
    }
    getLookup(lookupIndex) {
      return super.getLookup(lookupIndex, `GSUB`);
    }
  };
  var GSUB$1 = Object.freeze({ __proto__: null, GSUB });
  var GPOS = class extends CommonLayoutTable {
    constructor(dict, dataview) {
      super(dict, dataview, `GPOS`);
    }
    getLookup(lookupIndex) {
      return super.getLookup(lookupIndex, `GPOS`);
    }
  };
  var GPOS$1 = Object.freeze({ __proto__: null, GPOS });
  var SVG69 = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.offsetToSVGDocumentList = p22.Offset32;
      p22.currentPosition = this.tableStart + this.offsetToSVGDocumentList;
      this.documentList = new SVGDocumentList(p22);
    }
  };
  var SVGDocumentList = class extends ParsedData {
    constructor(p22) {
      super(p22);
      this.numEntries = p22.uint16;
      this.documentRecords = [...new Array(this.numEntries)].map(
        (_) => new SVGDocumentRecord(p22)
      );
    }
    getDocument(documentID) {
      let record = this.documentRecords[documentID];
      if (!record) return "";
      let offset4 = this.start + record.svgDocOffset;
      this.parser.currentPosition = offset4;
      return this.parser.readBytes(record.svgDocLength);
    }
    getDocumentForGlyph(glyphID) {
      let id = this.documentRecords.findIndex(
        (d2) => d2.startGlyphID <= glyphID && glyphID <= d2.endGlyphID
      );
      if (id === -1) return "";
      return this.getDocument(id);
    }
  };
  var SVGDocumentRecord = class {
    constructor(p22) {
      this.startGlyphID = p22.uint16;
      this.endGlyphID = p22.uint16;
      this.svgDocOffset = p22.Offset32;
      this.svgDocLength = p22.uint32;
    }
  };
  var SVG$1 = Object.freeze({ __proto__: null, SVG: SVG69 });
  var fvar = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
      this.axesArrayOffset = p22.Offset16;
      p22.uint16;
      this.axisCount = p22.uint16;
      this.axisSize = p22.uint16;
      this.instanceCount = p22.uint16;
      this.instanceSize = p22.uint16;
      const axisStart = this.tableStart + this.axesArrayOffset;
      lazy$1(this, `axes`, () => {
        p22.currentPosition = axisStart;
        return [...new Array(this.axisCount)].map(
          (_) => new VariationAxisRecord(p22)
        );
      });
      const instanceStart = axisStart + this.axisCount * this.axisSize;
      lazy$1(this, `instances`, () => {
        let instances = [];
        for (let i2 = 0; i2 < this.instanceCount; i2++) {
          p22.currentPosition = instanceStart + i2 * this.instanceSize;
          instances.push(
            new InstanceRecord(p22, this.axisCount, this.instanceSize)
          );
        }
        return instances;
      });
    }
    getSupportedAxes() {
      return this.axes.map((a2) => a2.tag);
    }
    getAxis(name2) {
      return this.axes.find((a2) => a2.tag === name2);
    }
  };
  var VariationAxisRecord = class {
    constructor(p22) {
      this.tag = p22.tag;
      this.minValue = p22.fixed;
      this.defaultValue = p22.fixed;
      this.maxValue = p22.fixed;
      this.flags = p22.flags(16);
      this.axisNameID = p22.uint16;
    }
  };
  var InstanceRecord = class {
    constructor(p22, axisCount, size4) {
      let start2 = p22.currentPosition;
      this.subfamilyNameID = p22.uint16;
      p22.uint16;
      this.coordinates = [...new Array(axisCount)].map(
        (_) => p22.fixed
      );
      if (p22.currentPosition - start2 < size4) {
        this.postScriptNameID = p22.uint16;
      }
    }
  };
  var fvar$1 = Object.freeze({ __proto__: null, fvar });
  var cvt = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      const n2 = dict.length / 2;
      lazy$1(
        this,
        `items`,
        () => [...new Array(n2)].map((_) => p22.fword)
      );
    }
  };
  var cvt$1 = Object.freeze({ __proto__: null, cvt });
  var fpgm = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      lazy$1(
        this,
        `instructions`,
        () => [...new Array(dict.length)].map((_) => p22.uint8)
      );
    }
  };
  var fpgm$1 = Object.freeze({ __proto__: null, fpgm });
  var gasp = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.numRanges = p22.uint16;
      const getter = () => [...new Array(this.numRanges)].map(
        (_) => new GASPRange(p22)
      );
      lazy$1(this, `gaspRanges`, getter);
    }
  };
  var GASPRange = class {
    constructor(p22) {
      this.rangeMaxPPEM = p22.uint16;
      this.rangeGaspBehavior = p22.uint16;
    }
  };
  var gasp$1 = Object.freeze({ __proto__: null, gasp });
  var glyf = class extends SimpleTable {
    constructor(dict, dataview) {
      super(dict, dataview);
    }
    getGlyphData(offset4, length) {
      this.parser.currentPosition = this.tableStart + offset4;
      return this.parser.readBytes(length);
    }
  };
  var glyf$1 = Object.freeze({ __proto__: null, glyf });
  var loca = class extends SimpleTable {
    constructor(dict, dataview, tables) {
      const { p: p22 } = super(dict, dataview);
      const n2 = tables.maxp.numGlyphs + 1;
      if (tables.head.indexToLocFormat === 0) {
        this.x2 = true;
        lazy$1(
          this,
          `offsets`,
          () => [...new Array(n2)].map((_) => p22.Offset16)
        );
      } else {
        lazy$1(
          this,
          `offsets`,
          () => [...new Array(n2)].map((_) => p22.Offset32)
        );
      }
    }
    getGlyphDataOffsetAndLength(glyphID) {
      let offset4 = this.offsets[glyphID] * this.x2 ? 2 : 1;
      let nextOffset = this.offsets[glyphID + 1] * this.x2 ? 2 : 1;
      return { offset: offset4, length: nextOffset - offset4 };
    }
  };
  var loca$1 = Object.freeze({ __proto__: null, loca });
  var prep = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      lazy$1(
        this,
        `instructions`,
        () => [...new Array(dict.length)].map((_) => p22.uint8)
      );
    }
  };
  var prep$1 = Object.freeze({ __proto__: null, prep });
  var CFF = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      lazy$1(this, `data`, () => p22.readBytes());
    }
  };
  var CFF$1 = Object.freeze({ __proto__: null, CFF });
  var CFF2 = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      lazy$1(this, `data`, () => p22.readBytes());
    }
  };
  var CFF2$1 = Object.freeze({ __proto__: null, CFF2 });
  var VORG = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
      this.defaultVertOriginY = p22.int16;
      this.numVertOriginYMetrics = p22.uint16;
      lazy$1(
        this,
        `vertORiginYMetrics`,
        () => [...new Array(this.numVertOriginYMetrics)].map(
          (_) => new VertOriginYMetric(p22)
        )
      );
    }
  };
  var VertOriginYMetric = class {
    constructor(p22) {
      this.glyphIndex = p22.uint16;
      this.vertOriginY = p22.int16;
    }
  };
  var VORG$1 = Object.freeze({ __proto__: null, VORG });
  var BitmapSize = class {
    constructor(p22) {
      this.indexSubTableArrayOffset = p22.Offset32;
      this.indexTablesSize = p22.uint32;
      this.numberofIndexSubTables = p22.uint32;
      this.colorRef = p22.uint32;
      this.hori = new SbitLineMetrics(p22);
      this.vert = new SbitLineMetrics(p22);
      this.startGlyphIndex = p22.uint16;
      this.endGlyphIndex = p22.uint16;
      this.ppemX = p22.uint8;
      this.ppemY = p22.uint8;
      this.bitDepth = p22.uint8;
      this.flags = p22.int8;
    }
  };
  var BitmapScale = class {
    constructor(p22) {
      this.hori = new SbitLineMetrics(p22);
      this.vert = new SbitLineMetrics(p22);
      this.ppemX = p22.uint8;
      this.ppemY = p22.uint8;
      this.substitutePpemX = p22.uint8;
      this.substitutePpemY = p22.uint8;
    }
  };
  var SbitLineMetrics = class {
    constructor(p22) {
      this.ascender = p22.int8;
      this.descender = p22.int8;
      this.widthMax = p22.uint8;
      this.caretSlopeNumerator = p22.int8;
      this.caretSlopeDenominator = p22.int8;
      this.caretOffset = p22.int8;
      this.minOriginSB = p22.int8;
      this.minAdvanceSB = p22.int8;
      this.maxBeforeBL = p22.int8;
      this.minAfterBL = p22.int8;
      this.pad1 = p22.int8;
      this.pad2 = p22.int8;
    }
  };
  var EBLC = class extends SimpleTable {
    constructor(dict, dataview, name2) {
      const { p: p22 } = super(dict, dataview, name2);
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
      this.numSizes = p22.uint32;
      lazy$1(
        this,
        `bitMapSizes`,
        () => [...new Array(this.numSizes)].map(
          (_) => new BitmapSize(p22)
        )
      );
    }
  };
  var EBLC$1 = Object.freeze({ __proto__: null, EBLC });
  var EBDT = class extends SimpleTable {
    constructor(dict, dataview, name2) {
      const { p: p22 } = super(dict, dataview, name2);
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
    }
  };
  var EBDT$1 = Object.freeze({ __proto__: null, EBDT });
  var EBSC = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.majorVersion = p22.uint16;
      this.minorVersion = p22.uint16;
      this.numSizes = p22.uint32;
      lazy$1(
        this,
        `bitmapScales`,
        () => [...new Array(this.numSizes)].map(
          (_) => new BitmapScale(p22)
        )
      );
    }
  };
  var EBSC$1 = Object.freeze({ __proto__: null, EBSC });
  var CBLC = class extends EBLC {
    constructor(dict, dataview) {
      super(dict, dataview, `CBLC`);
    }
  };
  var CBLC$1 = Object.freeze({ __proto__: null, CBLC });
  var CBDT = class extends EBDT {
    constructor(dict, dataview) {
      super(dict, dataview, `CBDT`);
    }
  };
  var CBDT$1 = Object.freeze({ __proto__: null, CBDT });
  var sbix = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.flags = p22.flags(16);
      this.numStrikes = p22.uint32;
      lazy$1(
        this,
        `strikeOffsets`,
        () => [...new Array(this.numStrikes)].map((_) => p22.Offset32)
      );
    }
  };
  var sbix$1 = Object.freeze({ __proto__: null, sbix });
  var COLR = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.numBaseGlyphRecords = p22.uint16;
      this.baseGlyphRecordsOffset = p22.Offset32;
      this.layerRecordsOffset = p22.Offset32;
      this.numLayerRecords = p22.uint16;
    }
    getBaseGlyphRecord(glyphID) {
      let start2 = this.tableStart + this.baseGlyphRecordsOffset;
      this.parser.currentPosition = start2;
      let first = new BaseGlyphRecord(this.parser);
      let firstID = first.gID;
      let end = this.tableStart + this.layerRecordsOffset - 6;
      this.parser.currentPosition = end;
      let last = new BaseGlyphRecord(this.parser);
      let lastID = last.gID;
      if (firstID === glyphID) return first;
      if (lastID === glyphID) return last;
      while (true) {
        if (start2 === end) break;
        let mid = start2 + (end - start2) / 12;
        this.parser.currentPosition = mid;
        let middle = new BaseGlyphRecord(this.parser);
        let midID = middle.gID;
        if (midID === glyphID) return middle;
        else if (midID > glyphID) {
          end = mid;
        } else if (midID < glyphID) {
          start2 = mid;
        }
      }
      return false;
    }
    getLayers(glyphID) {
      let record = this.getBaseGlyphRecord(glyphID);
      this.parser.currentPosition = this.tableStart + this.layerRecordsOffset + 4 * record.firstLayerIndex;
      return [...new Array(record.numLayers)].map(
        (_) => new LayerRecord(p)
      );
    }
  };
  var BaseGlyphRecord = class {
    constructor(p22) {
      this.gID = p22.uint16;
      this.firstLayerIndex = p22.uint16;
      this.numLayers = p22.uint16;
    }
  };
  var LayerRecord = class {
    constructor(p22) {
      this.gID = p22.uint16;
      this.paletteIndex = p22.uint16;
    }
  };
  var COLR$1 = Object.freeze({ __proto__: null, COLR });
  var CPAL = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.numPaletteEntries = p22.uint16;
      const numPalettes = this.numPalettes = p22.uint16;
      this.numColorRecords = p22.uint16;
      this.offsetFirstColorRecord = p22.Offset32;
      this.colorRecordIndices = [...new Array(this.numPalettes)].map(
        (_) => p22.uint16
      );
      lazy$1(this, `colorRecords`, () => {
        p22.currentPosition = this.tableStart + this.offsetFirstColorRecord;
        return [...new Array(this.numColorRecords)].map(
          (_) => new ColorRecord(p22)
        );
      });
      if (this.version === 1) {
        this.offsetPaletteTypeArray = p22.Offset32;
        this.offsetPaletteLabelArray = p22.Offset32;
        this.offsetPaletteEntryLabelArray = p22.Offset32;
        lazy$1(this, `paletteTypeArray`, () => {
          p22.currentPosition = this.tableStart + this.offsetPaletteTypeArray;
          return new PaletteTypeArray(p22, numPalettes);
        });
        lazy$1(this, `paletteLabelArray`, () => {
          p22.currentPosition = this.tableStart + this.offsetPaletteLabelArray;
          return new PaletteLabelsArray(p22, numPalettes);
        });
        lazy$1(this, `paletteEntryLabelArray`, () => {
          p22.currentPosition = this.tableStart + this.offsetPaletteEntryLabelArray;
          return new PaletteEntryLabelArray(p22, numPalettes);
        });
      }
    }
  };
  var ColorRecord = class {
    constructor(p22) {
      this.blue = p22.uint8;
      this.green = p22.uint8;
      this.red = p22.uint8;
      this.alpha = p22.uint8;
    }
  };
  var PaletteTypeArray = class {
    constructor(p22, numPalettes) {
      this.paletteTypes = [...new Array(numPalettes)].map(
        (_) => p22.uint32
      );
    }
  };
  var PaletteLabelsArray = class {
    constructor(p22, numPalettes) {
      this.paletteLabels = [...new Array(numPalettes)].map(
        (_) => p22.uint16
      );
    }
  };
  var PaletteEntryLabelArray = class {
    constructor(p22, numPalettes) {
      this.paletteEntryLabels = [...new Array(numPalettes)].map(
        (_) => p22.uint16
      );
    }
  };
  var CPAL$1 = Object.freeze({ __proto__: null, CPAL });
  var DSIG = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint32;
      this.numSignatures = p22.uint16;
      this.flags = p22.uint16;
      this.signatureRecords = [...new Array(this.numSignatures)].map(
        (_) => new SignatureRecord(p22)
      );
    }
    getData(signatureID) {
      const record = this.signatureRecords[signatureID];
      this.parser.currentPosition = this.tableStart + record.offset;
      return new SignatureBlockFormat1(this.parser);
    }
  };
  var SignatureRecord = class {
    constructor(p22) {
      this.format = p22.uint32;
      this.length = p22.uint32;
      this.offset = p22.Offset32;
    }
  };
  var SignatureBlockFormat1 = class {
    constructor(p22) {
      p22.uint16;
      p22.uint16;
      this.signatureLength = p22.uint32;
      this.signature = p22.readBytes(this.signatureLength);
    }
  };
  var DSIG$1 = Object.freeze({ __proto__: null, DSIG });
  var hdmx = class extends SimpleTable {
    constructor(dict, dataview, tables) {
      const { p: p22 } = super(dict, dataview);
      const numGlyphs = tables.hmtx.numGlyphs;
      this.version = p22.uint16;
      this.numRecords = p22.int16;
      this.sizeDeviceRecord = p22.int32;
      this.records = [...new Array(numRecords)].map(
        (_) => new DeviceRecord(p22, numGlyphs)
      );
    }
  };
  var DeviceRecord = class {
    constructor(p22, numGlyphs) {
      this.pixelSize = p22.uint8;
      this.maxWidth = p22.uint8;
      this.widths = p22.readBytes(numGlyphs);
    }
  };
  var hdmx$1 = Object.freeze({ __proto__: null, hdmx });
  var kern = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.nTables = p22.uint16;
      lazy$1(this, `tables`, () => {
        let offset4 = this.tableStart + 4;
        const tables = [];
        for (let i2 = 0; i2 < this.nTables; i2++) {
          p22.currentPosition = offset4;
          let subtable = new KernSubTable(p22);
          tables.push(subtable);
          offset4 += subtable;
        }
        return tables;
      });
    }
  };
  var KernSubTable = class {
    constructor(p22) {
      this.version = p22.uint16;
      this.length = p22.uint16;
      this.coverage = p22.flags(8);
      this.format = p22.uint8;
      if (this.format === 0) {
        this.nPairs = p22.uint16;
        this.searchRange = p22.uint16;
        this.entrySelector = p22.uint16;
        this.rangeShift = p22.uint16;
        lazy$1(
          this,
          `pairs`,
          () => [...new Array(this.nPairs)].map((_) => new Pair(p22))
        );
      }
      if (this.format === 2) {
        console.warn(
          `Kern subtable format 2 is not supported: this parser currently only parses universal table data.`
        );
      }
    }
    get horizontal() {
      return this.coverage[0];
    }
    get minimum() {
      return this.coverage[1];
    }
    get crossstream() {
      return this.coverage[2];
    }
    get override() {
      return this.coverage[3];
    }
  };
  var Pair = class {
    constructor(p22) {
      this.left = p22.uint16;
      this.right = p22.uint16;
      this.value = p22.fword;
    }
  };
  var kern$1 = Object.freeze({ __proto__: null, kern });
  var LTSH = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.numGlyphs = p22.uint16;
      this.yPels = p22.readBytes(this.numGlyphs);
    }
  };
  var LTSH$1 = Object.freeze({ __proto__: null, LTSH });
  var MERG = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.mergeClassCount = p22.uint16;
      this.mergeDataOffset = p22.Offset16;
      this.classDefCount = p22.uint16;
      this.offsetToClassDefOffsets = p22.Offset16;
      lazy$1(
        this,
        `mergeEntryMatrix`,
        () => [...new Array(this.mergeClassCount)].map(
          (_) => p22.readBytes(this.mergeClassCount)
        )
      );
      console.warn(`Full MERG parsing is currently not supported.`);
      console.warn(
        `If you need this table parsed, please file an issue, or better yet, a PR.`
      );
    }
  };
  var MERG$1 = Object.freeze({ __proto__: null, MERG });
  var meta = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint32;
      this.flags = p22.uint32;
      p22.uint32;
      this.dataMapsCount = p22.uint32;
      this.dataMaps = [...new Array(this.dataMapsCount)].map(
        (_) => new DataMap(this.tableStart, p22)
      );
    }
  };
  var DataMap = class {
    constructor(tableStart, p22) {
      this.tableStart = tableStart;
      this.parser = p22;
      this.tag = p22.tag;
      this.dataOffset = p22.Offset32;
      this.dataLength = p22.uint32;
    }
    getData() {
      this.parser.currentField = this.tableStart + this.dataOffset;
      return this.parser.readBytes(this.dataLength);
    }
  };
  var meta$1 = Object.freeze({ __proto__: null, meta });
  var PCLT = class extends SimpleTable {
    constructor(dict, dataview) {
      super(dict, dataview);
      console.warn(
        `This font uses a PCLT table, which is currently not supported by this parser.`
      );
      console.warn(
        `If you need this table parsed, please file an issue, or better yet, a PR.`
      );
    }
  };
  var PCLT$1 = Object.freeze({ __proto__: null, PCLT });
  var VDMX = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.uint16;
      this.numRecs = p22.uint16;
      this.numRatios = p22.uint16;
      this.ratRanges = [...new Array(this.numRatios)].map(
        (_) => new RatioRange(p22)
      );
      this.offsets = [...new Array(this.numRatios)].map(
        (_) => p22.Offset16
      );
      this.VDMXGroups = [...new Array(this.numRecs)].map(
        (_) => new VDMXGroup(p22)
      );
    }
  };
  var RatioRange = class {
    constructor(p22) {
      this.bCharSet = p22.uint8;
      this.xRatio = p22.uint8;
      this.yStartRatio = p22.uint8;
      this.yEndRatio = p22.uint8;
    }
  };
  var VDMXGroup = class {
    constructor(p22) {
      this.recs = p22.uint16;
      this.startsz = p22.uint8;
      this.endsz = p22.uint8;
      this.records = [...new Array(this.recs)].map(
        (_) => new vTable(p22)
      );
    }
  };
  var vTable = class {
    constructor(p22) {
      this.yPelHeight = p22.uint16;
      this.yMax = p22.int16;
      this.yMin = p22.int16;
    }
  };
  var VDMX$1 = Object.freeze({ __proto__: null, VDMX });
  var vhea = class extends SimpleTable {
    constructor(dict, dataview) {
      const { p: p22 } = super(dict, dataview);
      this.version = p22.fixed;
      this.ascent = this.vertTypoAscender = p22.int16;
      this.descent = this.vertTypoDescender = p22.int16;
      this.lineGap = this.vertTypoLineGap = p22.int16;
      this.advanceHeightMax = p22.int16;
      this.minTopSideBearing = p22.int16;
      this.minBottomSideBearing = p22.int16;
      this.yMaxExtent = p22.int16;
      this.caretSlopeRise = p22.int16;
      this.caretSlopeRun = p22.int16;
      this.caretOffset = p22.int16;
      this.reserved = p22.int16;
      this.reserved = p22.int16;
      this.reserved = p22.int16;
      this.reserved = p22.int16;
      this.metricDataFormat = p22.int16;
      this.numOfLongVerMetrics = p22.uint16;
      p22.verifyLength();
    }
  };
  var vhea$1 = Object.freeze({ __proto__: null, vhea });
  var vmtx = class extends SimpleTable {
    constructor(dict, dataview, tables) {
      super(dict, dataview);
      const numOfLongVerMetrics = tables.vhea.numOfLongVerMetrics;
      const numGlyphs = tables.maxp.numGlyphs;
      const metricsStart = p.currentPosition;
      lazy(this, `vMetrics`, () => {
        p.currentPosition = metricsStart;
        return [...new Array(numOfLongVerMetrics)].map(
          (_) => new LongVertMetric(p.uint16, p.int16)
        );
      });
      if (numOfLongVerMetrics < numGlyphs) {
        const tsbStart = metricsStart + numOfLongVerMetrics * 4;
        lazy(this, `topSideBearings`, () => {
          p.currentPosition = tsbStart;
          return [...new Array(numGlyphs - numOfLongVerMetrics)].map(
            (_) => p.int16
          );
        });
      }
    }
  };
  var LongVertMetric = class {
    constructor(h2, b2) {
      this.advanceHeight = h2;
      this.topSideBearing = b2;
    }
  };
  var vmtx$1 = Object.freeze({ __proto__: null, vmtx });

  // packages/global-styles-ui/build-module/font-library/utils/make-families-from-faces.mjs
  var import_components98 = __toESM(require_components(), 1);
  var { kebabCase: kebabCase4 } = unlock6(import_components98.privateApis);

  // packages/global-styles-ui/build-module/font-library/upload-fonts.mjs
  var import_jsx_runtime243 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-library/modal.mjs
  var import_jsx_runtime244 = __toESM(require_jsx_runtime(), 1);
  var { Tabs } = unlock6(import_components100.privateApis);
  var DEFAULT_TAB = {
    id: "installed-fonts",
    title: (0, import_i18n92._x)("Library", "Font library")
  };
  var UPLOAD_TAB = {
    id: "upload-fonts",
    title: (0, import_i18n92._x)("Upload", "noun")
  };

  // packages/global-styles-ui/build-module/font-family-item.mjs
  var import_i18n93 = __toESM(require_i18n(), 1);
  var import_components101 = __toESM(require_components(), 1);
  var import_element148 = __toESM(require_element(), 1);
  var import_jsx_runtime245 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-families.mjs
  var import_jsx_runtime246 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-sizes/font-sizes-count.mjs
  var import_i18n95 = __toESM(require_i18n(), 1);
  var import_components103 = __toESM(require_components(), 1);
  var import_jsx_runtime247 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-typography.mjs
  var import_jsx_runtime248 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-typography-element.mjs
  var import_i18n97 = __toESM(require_i18n(), 1);
  var import_components105 = __toESM(require_components(), 1);
  var import_element151 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/typography-panel.mjs
  var import_block_editor11 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime249 = __toESM(require_jsx_runtime(), 1);
  var { useSettingsForBlockElement: useSettingsForBlockElement4, TypographyPanel: StylesTypographyPanel2 } = unlock6(import_block_editor11.privateApis);

  // packages/global-styles-ui/build-module/typography-preview.mjs
  var import_jsx_runtime250 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-typography-element.mjs
  var import_jsx_runtime251 = __toESM(require_jsx_runtime(), 1);
  var elements = {
    text: {
      description: (0, import_i18n97.__)("Manage the fonts used on the site."),
      title: (0, import_i18n97.__)("Text")
    },
    link: {
      description: (0, import_i18n97.__)("Manage the fonts and typography used on the links."),
      title: (0, import_i18n97.__)("Links")
    },
    heading: {
      description: (0, import_i18n97.__)("Manage the fonts and typography used on headings."),
      title: (0, import_i18n97.__)("Headings")
    },
    caption: {
      description: (0, import_i18n97.__)("Manage the fonts and typography used on captions."),
      title: (0, import_i18n97.__)("Captions")
    },
    button: {
      description: (0, import_i18n97.__)("Manage the fonts and typography used on buttons."),
      title: (0, import_i18n97.__)("Buttons")
    }
  };

  // packages/global-styles-ui/build-module/screen-colors.mjs
  var import_i18n99 = __toESM(require_i18n(), 1);
  var import_components108 = __toESM(require_components(), 1);
  var import_block_editor12 = __toESM(require_block_editor(), 1);

  // packages/global-styles-ui/build-module/palette.mjs
  var import_components107 = __toESM(require_components(), 1);
  var import_i18n98 = __toESM(require_i18n(), 1);
  var import_element152 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/color-indicator-wrapper.mjs
  var import_components106 = __toESM(require_components(), 1);
  var import_jsx_runtime252 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/palette.mjs
  var import_jsx_runtime253 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-colors.mjs
  var import_jsx_runtime254 = __toESM(require_jsx_runtime(), 1);
  var { useSettingsForBlockElement: useSettingsForBlockElement5, ColorPanel: StylesColorPanel2 } = unlock6(
    import_block_editor12.privateApis
  );

  // packages/global-styles-ui/build-module/screen-color-palette.mjs
  var import_i18n102 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/color-palette-panel.mjs
  var import_compose25 = __toESM(require_compose(), 1);
  var import_components111 = __toESM(require_components(), 1);
  var import_i18n100 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/variations/variations-color.mjs
  var import_components110 = __toESM(require_components(), 1);

  // packages/global-styles-ui/build-module/preview-colors.mjs
  var import_components109 = __toESM(require_components(), 1);

  // packages/global-styles-ui/build-module/preset-colors.mjs
  var import_jsx_runtime255 = __toESM(require_jsx_runtime(), 1);
  function PresetColors() {
    const { paletteColors } = useStylesPreviewColors();
    return paletteColors.slice(0, 4).map(({ slug, color }, index2) => /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
      "div",
      {
        style: {
          flexGrow: 1,
          height: "100%",
          background: color
        }
      },
      `${slug}-${index2}`
    ));
  }

  // packages/global-styles-ui/build-module/preview-colors.mjs
  var import_jsx_runtime256 = __toESM(require_jsx_runtime(), 1);
  var firstFrameVariants2 = {
    start: {
      scale: 1,
      opacity: 1
    },
    hover: {
      scale: 0,
      opacity: 0
    }
  };
  var StylesPreviewColors = ({
    label,
    isFocused,
    withHoverView
  }) => {
    return /* @__PURE__ */ (0, import_jsx_runtime256.jsx)(
      preview_wrapper_default,
      {
        label,
        isFocused,
        withHoverView,
        children: ({ key }) => /* @__PURE__ */ (0, import_jsx_runtime256.jsx)(
          import_components109.__unstableMotion.div,
          {
            variants: firstFrameVariants2,
            style: {
              height: "100%",
              overflow: "hidden"
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime256.jsx)(
              import_components109.__experimentalHStack,
              {
                spacing: 0,
                justify: "center",
                style: {
                  height: "100%",
                  overflow: "hidden"
                },
                children: /* @__PURE__ */ (0, import_jsx_runtime256.jsx)(PresetColors, {})
              }
            )
          },
          key
        )
      }
    );
  };
  var preview_colors_default = StylesPreviewColors;

  // packages/global-styles-ui/build-module/variations/variations-color.mjs
  var import_jsx_runtime257 = __toESM(require_jsx_runtime(), 1);
  var propertiesToFilter2 = ["color"];
  function ColorVariations({
    title,
    gap = 2
  }) {
    const colorVariations = useCurrentMergeThemeStyleVariationsWithUserConfig(propertiesToFilter2);
    if (colorVariations?.length <= 1) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime257.jsxs)(import_components110.__experimentalVStack, { spacing: 3, children: [
      title && /* @__PURE__ */ (0, import_jsx_runtime257.jsx)(Subtitle, { level: 3, children: title }),
      /* @__PURE__ */ (0, import_jsx_runtime257.jsx)(import_components110.__experimentalGrid, { gap, children: colorVariations.map((variation, index2) => /* @__PURE__ */ (0, import_jsx_runtime257.jsx)(
        Variation,
        {
          variation,
          isPill: true,
          properties: propertiesToFilter2,
          showTooltip: true,
          children: () => /* @__PURE__ */ (0, import_jsx_runtime257.jsx)(preview_colors_default, {})
        },
        index2
      )) })
    ] });
  }

  // packages/global-styles-ui/build-module/color-palette-panel.mjs
  var import_jsx_runtime258 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/gradients-palette-panel.mjs
  var import_compose26 = __toESM(require_compose(), 1);
  var import_components112 = __toESM(require_components(), 1);
  var import_i18n101 = __toESM(require_i18n(), 1);
  var import_jsx_runtime259 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-color-palette.mjs
  var import_jsx_runtime260 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-background.mjs
  var import_i18n103 = __toESM(require_i18n(), 1);
  var import_block_editor14 = __toESM(require_block_editor(), 1);
  var import_components113 = __toESM(require_components(), 1);

  // packages/global-styles-ui/build-module/background-panel.mjs
  var import_block_editor13 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime261 = __toESM(require_jsx_runtime(), 1);
  var { BackgroundPanel: StylesBackgroundPanel2 } = unlock6(
    import_block_editor13.privateApis
  );

  // packages/global-styles-ui/build-module/screen-background.mjs
  var import_jsx_runtime262 = __toESM(require_jsx_runtime(), 1);
  var { useHasBackgroundPanel: useHasBackgroundPanel4 } = unlock6(import_block_editor14.privateApis);

  // packages/global-styles-ui/build-module/shadows-panel.mjs
  var import_components115 = __toESM(require_components(), 1);
  var import_i18n105 = __toESM(require_i18n(), 1);
  var import_element153 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/confirm-reset-shadow-dialog.mjs
  var import_components114 = __toESM(require_components(), 1);
  var import_i18n104 = __toESM(require_i18n(), 1);
  var import_jsx_runtime263 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/shadows-panel.mjs
  var import_jsx_runtime264 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu6 } = unlock6(import_components115.privateApis);

  // packages/global-styles-ui/build-module/shadows-edit-panel.mjs
  var import_components116 = __toESM(require_components(), 1);
  var import_i18n106 = __toESM(require_i18n(), 1);
  var import_element154 = __toESM(require_element(), 1);
  var import_jsx_runtime265 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu7 } = unlock6(import_components116.privateApis);
  var customShadowMenuItems = [
    {
      label: (0, import_i18n106.__)("Rename"),
      action: "rename"
    },
    {
      label: (0, import_i18n106.__)("Delete"),
      action: "delete"
    }
  ];
  var presetShadowMenuItems = [
    {
      label: (0, import_i18n106.__)("Reset"),
      action: "reset"
    }
  ];

  // packages/global-styles-ui/build-module/screen-shadows.mjs
  var import_jsx_runtime266 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-layout.mjs
  var import_i18n107 = __toESM(require_i18n(), 1);
  var import_block_editor16 = __toESM(require_block_editor(), 1);

  // packages/global-styles-ui/build-module/dimensions-panel.mjs
  var import_block_editor15 = __toESM(require_block_editor(), 1);
  var import_element155 = __toESM(require_element(), 1);
  var import_jsx_runtime267 = __toESM(require_jsx_runtime(), 1);
  var { useSettingsForBlockElement: useSettingsForBlockElement6, DimensionsPanel: StylesDimensionsPanel2 } = unlock6(import_block_editor15.privateApis);

  // packages/global-styles-ui/build-module/screen-layout.mjs
  var import_jsx_runtime268 = __toESM(require_jsx_runtime(), 1);
  var { useHasDimensionsPanel: useHasDimensionsPanel4, useSettingsForBlockElement: useSettingsForBlockElement7 } = unlock6(
    import_block_editor16.privateApis
  );

  // packages/global-styles-ui/build-module/screen-style-variations.mjs
  var import_components119 = __toESM(require_components(), 1);
  var import_i18n110 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/style-variations-content.mjs
  var import_i18n109 = __toESM(require_i18n(), 1);
  var import_components118 = __toESM(require_components(), 1);

  // packages/global-styles-ui/build-module/style-variations-container.mjs
  var import_core_data33 = __toESM(require_core_data(), 1);
  var import_data50 = __toESM(require_data(), 1);
  var import_element156 = __toESM(require_element(), 1);
  var import_components117 = __toESM(require_components(), 1);
  var import_i18n108 = __toESM(require_i18n(), 1);
  var import_jsx_runtime269 = __toESM(require_jsx_runtime(), 1);
  function StyleVariationsContainer({
    gap = 2
  }) {
    const { user } = (0, import_element156.useContext)(GlobalStylesContext);
    const userStyles = user?.styles;
    const variations = (0, import_data50.useSelect)((select4) => {
      const result = select4(
        import_core_data33.store
      ).__experimentalGetCurrentThemeGlobalStylesVariations();
      return Array.isArray(result) ? result : void 0;
    }, []);
    const fullStyleVariations = variations?.filter(
      (variation) => {
        return !isVariationWithProperties(variation, ["color"]) && !isVariationWithProperties(variation, [
          "typography",
          "spacing"
        ]);
      }
    );
    const themeVariations = (0, import_element156.useMemo)(() => {
      const withEmptyVariation = [
        {
          title: (0, import_i18n108.__)("Default"),
          settings: {},
          styles: {}
        },
        ...fullStyleVariations ?? []
      ];
      return [
        ...withEmptyVariation.map((variation) => {
          const blockStyles = variation?.styles?.blocks ? { ...variation.styles.blocks } : {};
          if (userStyles?.blocks) {
            Object.keys(userStyles.blocks).forEach((blockName) => {
              if (userStyles.blocks?.[blockName]?.css) {
                const variationBlockStyles = blockStyles[blockName] || {};
                const customCSS = {
                  css: `${blockStyles[blockName]?.css || ""} ${userStyles.blocks?.[blockName]?.css?.trim() || ""}`
                };
                blockStyles[blockName] = {
                  ...variationBlockStyles,
                  ...customCSS
                };
              }
            });
          }
          const css = userStyles?.css || variation.styles?.css ? {
            css: `${variation.styles?.css || ""} ${userStyles?.css || ""}`
          } : {};
          const blocks = Object.keys(blockStyles).length > 0 ? { blocks: blockStyles } : {};
          const styles = {
            ...variation.styles,
            ...css,
            ...blocks
          };
          return {
            ...variation,
            settings: variation.settings ?? {},
            styles
          };
        })
      ];
    }, [fullStyleVariations, userStyles?.blocks, userStyles?.css]);
    if (!fullStyleVariations || fullStyleVariations.length < 1) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
      import_components117.__experimentalGrid,
      {
        columns: 2,
        className: "global-styles-ui-style-variations-container",
        gap,
        children: themeVariations.map(
          (variation, index2) => /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(Variation, { variation, children: (isFocused) => /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
            preview_styles_default,
            {
              label: variation?.title,
              withHoverView: true,
              isFocused,
              variation
            }
          ) }, index2)
        )
      }
    );
  }
  var style_variations_container_default = StyleVariationsContainer;

  // packages/global-styles-ui/build-module/style-variations-content.mjs
  var import_jsx_runtime270 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-style-variations.mjs
  var import_jsx_runtime271 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-css.mjs
  var import_i18n111 = __toESM(require_i18n(), 1);
  var import_components120 = __toESM(require_components(), 1);
  var import_block_editor17 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime272 = __toESM(require_jsx_runtime(), 1);
  var { AdvancedPanel: StylesAdvancedPanel2 } = unlock6(import_block_editor17.privateApis);

  // packages/global-styles-ui/build-module/screen-revisions/index.mjs
  var import_i18n114 = __toESM(require_i18n(), 1);
  var import_components123 = __toESM(require_components(), 1);
  var import_element158 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/screen-revisions/use-global-styles-revisions.mjs
  var import_data51 = __toESM(require_data(), 1);
  var import_core_data34 = __toESM(require_core_data(), 1);
  var import_element157 = __toESM(require_element(), 1);
  var SITE_EDITOR_AUTHORS_QUERY = {
    per_page: -1,
    _fields: "id,name,avatar_urls",
    context: "view",
    capabilities: ["edit_theme_options"]
  };
  var DEFAULT_QUERY = { per_page: 100, page: 1 };
  var EMPTY_ARRAY11 = [];
  function useGlobalStylesRevisions({
    query
  } = {}) {
    const { user: userConfig } = (0, import_element157.useContext)(GlobalStylesContext);
    const _query = (0, import_element157.useMemo)(
      () => ({ ...DEFAULT_QUERY, ...query }),
      [query]
    );
    const {
      authors,
      currentUser,
      isDirty,
      revisions,
      isLoadingGlobalStylesRevisions,
      revisionsCount
    } = (0, import_data51.useSelect)(
      (select4) => {
        const {
          __experimentalGetDirtyEntityRecords,
          getCurrentUser,
          getUsers,
          getRevisions,
          __experimentalGetCurrentGlobalStylesId,
          getEntityRecord,
          isResolving
        } = select4(import_core_data34.store);
        const dirtyEntityRecords = __experimentalGetDirtyEntityRecords() || [];
        const _currentUser = getCurrentUser();
        const _isDirty = dirtyEntityRecords.length > 0;
        const globalStylesId = __experimentalGetCurrentGlobalStylesId();
        const globalStyles = globalStylesId ? getEntityRecord(
          "root",
          "globalStyles",
          globalStylesId
        ) : void 0;
        const _revisionsCount = (
          // @ts-expect-error - _links is not typed in GlobalStylesRevision
          globalStyles?._links?.["version-history"]?.[0]?.count ?? 0
        );
        const globalStylesRevisions = globalStylesId ? getRevisions(
          "root",
          "globalStyles",
          globalStylesId,
          _query
        ) || EMPTY_ARRAY11 : EMPTY_ARRAY11;
        const _authors = getUsers(SITE_EDITOR_AUTHORS_QUERY) || EMPTY_ARRAY11;
        const _isResolving = globalStylesId ? isResolving("getRevisions", [
          "root",
          "globalStyles",
          globalStylesId,
          _query
        ]) : false;
        return {
          authors: _authors,
          currentUser: _currentUser,
          isDirty: _isDirty,
          revisions: globalStylesRevisions,
          isLoadingGlobalStylesRevisions: _isResolving,
          revisionsCount: _revisionsCount
        };
      },
      [_query]
    );
    return (0, import_element157.useMemo)(() => {
      if (!authors.length || isLoadingGlobalStylesRevisions) {
        return {
          revisions: EMPTY_ARRAY11,
          hasUnsavedChanges: isDirty,
          isLoading: true,
          revisionsCount
        };
      }
      const _modifiedRevisions = revisions.map((revision) => {
        return {
          ...revision,
          author: authors.find(
            (author) => author.id === revision.author
          )
        };
      });
      const fetchedRevisionsCount = revisions.length;
      if (fetchedRevisionsCount) {
        if (_modifiedRevisions[0].id !== "unsaved" && _query.page === 1) {
          _modifiedRevisions[0].isLatest = true;
        }
        if (isDirty && userConfig && Object.keys(userConfig).length > 0 && currentUser && _query.page === 1) {
          const unsavedRevision = {
            id: "unsaved",
            styles: userConfig?.styles,
            settings: userConfig?.settings,
            _links: userConfig?._links,
            author: {
              name: currentUser?.name || "",
              // @ts-expect-error - avatar_urls is not typed in User
              avatar_urls: currentUser?.avatar_urls || {}
            },
            modified: /* @__PURE__ */ new Date()
          };
          _modifiedRevisions.unshift(unsavedRevision);
        }
        if (_query.per_page && _query.page === Math.ceil(revisionsCount / _query.per_page)) {
          _modifiedRevisions.push({
            id: "parent",
            styles: {},
            settings: {}
          });
        }
      }
      return {
        revisions: _modifiedRevisions,
        hasUnsavedChanges: isDirty,
        isLoading: false,
        revisionsCount
      };
    }, [
      isDirty,
      revisions,
      currentUser,
      authors,
      userConfig,
      isLoadingGlobalStylesRevisions,
      revisionsCount,
      _query.page,
      _query.per_page
    ]);
  }

  // packages/global-styles-ui/build-module/screen-revisions/revisions-buttons.mjs
  var import_i18n112 = __toESM(require_i18n(), 1);
  var import_components121 = __toESM(require_components(), 1);
  var import_date10 = __toESM(require_date(), 1);
  var import_core_data35 = __toESM(require_core_data(), 1);
  var import_data52 = __toESM(require_data(), 1);
  var import_keycodes6 = __toESM(require_keycodes(), 1);
  var import_jsx_runtime273 = __toESM(require_jsx_runtime(), 1);
  var { Badge: WCBadge3 } = unlock6(import_components121.privateApis);
  var DAY_IN_MILLISECONDS = 60 * 60 * 1e3 * 24;

  // packages/global-styles-ui/build-module/pagination/index.mjs
  var import_components122 = __toESM(require_components(), 1);
  var import_i18n113 = __toESM(require_i18n(), 1);
  var import_jsx_runtime274 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/screen-revisions/index.mjs
  var import_jsx_runtime275 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-sizes/font-sizes.mjs
  var import_i18n116 = __toESM(require_i18n(), 1);
  var import_components125 = __toESM(require_components(), 1);
  var import_element159 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/font-sizes/confirm-reset-font-sizes-dialog.mjs
  var import_components124 = __toESM(require_components(), 1);
  var import_i18n115 = __toESM(require_i18n(), 1);
  var import_jsx_runtime276 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-sizes/font-sizes.mjs
  var import_jsx_runtime277 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu8 } = unlock6(import_components125.privateApis);

  // packages/global-styles-ui/build-module/font-sizes/font-size.mjs
  var import_i18n120 = __toESM(require_i18n(), 1);
  var import_components129 = __toESM(require_components(), 1);
  var import_element161 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/font-sizes/font-size-preview.mjs
  var import_block_editor18 = __toESM(require_block_editor(), 1);
  var import_i18n117 = __toESM(require_i18n(), 1);
  var import_jsx_runtime278 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-sizes/confirm-delete-font-size-dialog.mjs
  var import_components126 = __toESM(require_components(), 1);
  var import_i18n118 = __toESM(require_i18n(), 1);
  var import_jsx_runtime279 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-sizes/rename-font-size-dialog.mjs
  var import_components127 = __toESM(require_components(), 1);
  var import_i18n119 = __toESM(require_i18n(), 1);
  var import_element160 = __toESM(require_element(), 1);
  var import_jsx_runtime280 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/size-control/index.mjs
  var import_components128 = __toESM(require_components(), 1);
  var import_jsx_runtime281 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/font-sizes/font-size.mjs
  var import_jsx_runtime282 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu9 } = unlock6(import_components129.privateApis);

  // packages/global-styles-ui/build-module/global-styles-ui.mjs
  var import_jsx_runtime283 = __toESM(require_jsx_runtime(), 1);

  // packages/global-styles-ui/build-module/with-global-styles-provider.mjs
  var import_jsx_runtime284 = __toESM(require_jsx_runtime(), 1);
  function withGlobalStylesProvider(Component) {
    return function WrappedComponent({
      value,
      baseValue,
      onChange,
      ...props
    }) {
      return /* @__PURE__ */ (0, import_jsx_runtime284.jsx)(
        GlobalStylesProvider,
        {
          value,
          baseValue,
          onChange,
          children: /* @__PURE__ */ (0, import_jsx_runtime284.jsx)(Component, { ...props })
        }
      );
    };
  }

  // packages/global-styles-ui/build-module/style-variations.mjs
  var StyleVariations = withGlobalStylesProvider(style_variations_container_default);

  // packages/global-styles-ui/build-module/color-variations.mjs
  var ColorVariations2 = withGlobalStylesProvider(ColorVariations);

  // packages/global-styles-ui/build-module/typography-variations.mjs
  var TypographyVariations2 = withGlobalStylesProvider(TypographyVariations);

  // packages/global-styles-ui/build-module/font-library/font-library.mjs
  var import_jsx_runtime285 = __toESM(require_jsx_runtime(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-details-footer/index.mjs
  var import_i18n121 = __toESM(require_i18n(), 1);
  var import_url11 = __toESM(require_url(), 1);
  var import_components131 = __toESM(require_components(), 1);
  var import_jsx_runtime286 = __toESM(require_jsx_runtime(), 1);
  function SidebarNavigationScreenDetailsFooter({
    record,
    revisionsCount,
    ...otherProps
  }) {
    const hrefProps = {};
    const lastRevisionId = record?._links?.["predecessor-version"]?.[0]?.id ?? null;
    revisionsCount = revisionsCount || record?._links?.["version-history"]?.[0]?.count || 0;
    if (lastRevisionId && revisionsCount > 1) {
      hrefProps.href = (0, import_url11.addQueryArgs)("revision.php", {
        revision: record?._links["predecessor-version"][0].id
      });
      hrefProps.as = "a";
    }
    return /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
      import_components131.__experimentalItemGroup,
      {
        size: "large",
        className: "edit-site-sidebar-navigation-screen-details-footer",
        children: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
          SidebarNavigationItem,
          {
            icon: backup_default,
            ...hrefProps,
            ...otherProps,
            children: (0, import_i18n121.sprintf)(
              /* translators: %d: Number of Styles revisions. */
              (0, import_i18n121._n)("%d Revision", "%d Revisions", revisionsCount),
              revisionsCount
            )
          }
        )
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-global-styles/index.mjs
  var import_jsx_runtime287 = __toESM(require_jsx_runtime(), 1);
  var { useLocation: useLocation18, useHistory: useHistory11 } = unlock(import_router18.privateApis);
  function SidebarNavigationScreenGlobalStyles() {
    const history = useHistory11();
    const { path } = useLocation18();
    const {
      revisions,
      isLoading: isLoadingRevisions,
      revisionsCount
    } = useGlobalStylesRevisions();
    const { openGeneralSidebar: openGeneralSidebar2 } = (0, import_data54.useDispatch)(store);
    const { setStylesPath } = unlock((0, import_data54.useDispatch)(import_editor22.store));
    const { set: setPreference } = (0, import_data54.useDispatch)(import_preferences10.store);
    const openGlobalStyles = (0, import_element163.useCallback)(async () => {
      history.navigate((0, import_url12.addQueryArgs)(path, { canvas: "edit" }), {
        transition: "canvas-mode-edit-transition"
      });
      return Promise.all([
        setPreference("core", "distractionFree", false),
        openGeneralSidebar2("edit-site/global-styles")
      ]);
    }, [path, history, openGeneralSidebar2, setPreference]);
    const openRevisions = (0, import_element163.useCallback)(async () => {
      await openGlobalStyles();
      setStylesPath("/revisions");
    }, [openGlobalStyles, setStylesPath]);
    const shouldShowGlobalStylesFooter = !!revisionsCount && !isLoadingRevisions;
    return /* @__PURE__ */ (0, import_jsx_runtime287.jsx)(import_jsx_runtime287.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime287.jsx)(
      SidebarNavigationScreen,
      {
        title: (0, import_i18n122.__)("Design"),
        isRoot: true,
        description: (0, import_i18n122.__)(
          "Customize the appearance of your website using the block editor."
        ),
        content: /* @__PURE__ */ (0, import_jsx_runtime287.jsx)(MainSidebarNavigationContent, {}),
        footer: shouldShowGlobalStylesFooter && /* @__PURE__ */ (0, import_jsx_runtime287.jsx)(
          SidebarNavigationScreenDetailsFooter,
          {
            record: revisions?.[0],
            revisionsCount,
            onClick: openRevisions
          }
        )
      }
    ) });
  }

  // packages/edit-site/build-module/components/sidebar-global-styles/index.mjs
  var import_i18n123 = __toESM(require_i18n(), 1);
  var import_element164 = __toESM(require_element(), 1);
  var import_router19 = __toESM(require_router(), 1);
  var import_editor23 = __toESM(require_editor(), 1);
  var import_compose28 = __toESM(require_compose(), 1);
  var import_data55 = __toESM(require_data(), 1);
  var import_components132 = __toESM(require_components(), 1);
  var import_url13 = __toESM(require_url(), 1);
  var import_jsx_runtime288 = __toESM(require_jsx_runtime(), 1);
  var { GlobalStylesUIWrapper, GlobalStylesActionMenu } = unlock(import_editor23.privateApis);
  var { useLocation: useLocation19, useHistory: useHistory12 } = unlock(import_router19.privateApis);
  var GlobalStylesPageActions = ({
    isStyleBookOpened,
    setIsStyleBookOpened,
    path,
    onChangeSection
  }) => {
    const history = useHistory12();
    return /* @__PURE__ */ (0, import_jsx_runtime288.jsxs)(import_components132.__experimentalHStack, { className: "edit-site-styles__header-actions", children: [
      /* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
        import_components132.Button,
        {
          isPressed: isStyleBookOpened,
          icon: seen_default,
          label: (0, import_i18n123.__)("Style Book"),
          onClick: () => {
            setIsStyleBookOpened(!isStyleBookOpened);
            const updatedPath = !isStyleBookOpened ? (0, import_url13.addQueryArgs)(path, { preview: "stylebook" }) : (0, import_url13.removeQueryArgs)(path, "preview");
            history.navigate(updatedPath);
          },
          size: "compact"
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
        GlobalStylesActionMenu,
        {
          hideWelcomeGuide: true,
          onChangePath: onChangeSection
        }
      )
    ] });
  };
  var useSection = () => {
    const { path, query } = useLocation19();
    const history = useHistory12();
    return (0, import_element164.useMemo)(() => {
      return [
        query.section ?? "/",
        (updatedSection) => {
          history.navigate(
            (0, import_url13.addQueryArgs)(path, {
              section: updatedSection
            })
          );
        }
      ];
    }, [path, query.section, history]);
  };
  function SidebarGlobalStyles() {
    const { path } = useLocation19();
    const [isStyleBookOpened, setIsStyleBookOpened] = (0, import_element164.useState)(
      path.includes("preview=stylebook")
    );
    const isMobileViewport = (0, import_compose28.useViewportMatch)("medium", "<");
    const [section, onChangeSection] = useSection();
    const settings2 = (0, import_data55.useSelect)(
      (select4) => select4(store).getSettings(),
      []
    );
    return /* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
      page_default2,
      {
        actions: !isMobileViewport ? /* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
          GlobalStylesPageActions,
          {
            isStyleBookOpened,
            setIsStyleBookOpened,
            path,
            onChangeSection
          }
        ) : null,
        className: "edit-site-styles",
        title: (0, import_i18n123.__)("Styles"),
        headingLevel: 2,
        children: /* @__PURE__ */ (0, import_jsx_runtime288.jsx)(
          GlobalStylesUIWrapper,
          {
            path: section,
            onPathChange: onChangeSection,
            settings: settings2
          }
        )
      }
    );
  }

  // packages/edit-site/build-module/components/site-editor-routes/styles.mjs
  var import_jsx_runtime289 = __toESM(require_jsx_runtime(), 1);
  var { useLocation: useLocation20, useHistory: useHistory13 } = unlock(import_router20.privateApis);
  var { StyleBookPreview, useGlobalStyles: useGlobalStyles3 } = unlock(import_editor24.privateApis);
  function StyleBookPreviewArea({ siteData }) {
    const { path, query } = useLocation20();
    const history = useHistory13();
    const { user: userConfig } = useGlobalStyles3();
    const section = query.section ?? "/";
    const onChangeSection = (updatedSection) => {
      history.navigate(
        (0, import_url14.addQueryArgs)(path, {
          section: updatedSection
        })
      );
    };
    return /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(
      StyleBookPreview,
      {
        path: section,
        onPathChange: onChangeSection,
        settings: siteData.editorSettings,
        userConfig
      }
    );
  }
  function StylesPreviewArea({ siteData }) {
    const { query } = useLocation20();
    if (query.preview === "stylebook") {
      return /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(StyleBookPreviewArea, { siteData });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(EditSiteEditor, {});
  }
  var stylesRoute = {
    name: "styles",
    path: "/styles",
    areas: {
      content: /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(SidebarGlobalStyles, {}),
      sidebar: /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(SidebarNavigationScreenGlobalStyles, { backPath: "/" }),
      preview: ({ siteData }) => /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(StylesPreviewArea, { siteData }),
      mobileContent: /* @__PURE__ */ (0, import_jsx_runtime289.jsx)(SidebarGlobalStyles, {})
    },
    widths: {
      content: 380
    }
  };

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menus/index.mjs
  var import_i18n132 = __toESM(require_i18n(), 1);
  var import_core_data40 = __toESM(require_core_data(), 1);
  var import_data61 = __toESM(require_data(), 1);
  var import_html_entities7 = __toESM(require_html_entities(), 1);
  var import_components138 = __toESM(require_components(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menus/constants.mjs
  var PRELOADED_NAVIGATION_MENUS_QUERY = {
    per_page: 100,
    status: ["publish", "draft"],
    order: "desc",
    orderby: "date"
  };

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/single-navigation-menu.mjs
  var import_i18n129 = __toESM(require_i18n(), 1);
  var import_html_entities5 = __toESM(require_html_entities(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/more-menu.mjs
  var import_components135 = __toESM(require_components(), 1);
  var import_i18n126 = __toESM(require_i18n(), 1);
  var import_element166 = __toESM(require_element(), 1);
  var import_router21 = __toESM(require_router(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/rename-modal.mjs
  var import_components133 = __toESM(require_components(), 1);
  var import_i18n124 = __toESM(require_i18n(), 1);
  var import_element165 = __toESM(require_element(), 1);
  var import_jsx_runtime290 = __toESM(require_jsx_runtime(), 1);
  var notEmptyString = (testString) => testString?.trim()?.length > 0;
  function RenameModal({ menuTitle, onClose, onSave }) {
    const [editedMenuTitle, setEditedMenuTitle] = (0, import_element165.useState)(menuTitle);
    const titleHasChanged = editedMenuTitle !== menuTitle;
    const isEditedMenuTitleValid = titleHasChanged && notEmptyString(editedMenuTitle);
    return /* @__PURE__ */ (0, import_jsx_runtime290.jsx)(
      import_components133.Modal,
      {
        title: (0, import_i18n124.__)("Rename"),
        onRequestClose: onClose,
        focusOnMount: "firstContentElement",
        size: "small",
        children: /* @__PURE__ */ (0, import_jsx_runtime290.jsx)("form", { className: "sidebar-navigation__rename-modal-form", children: /* @__PURE__ */ (0, import_jsx_runtime290.jsxs)(import_components133.__experimentalVStack, { spacing: "3", children: [
          /* @__PURE__ */ (0, import_jsx_runtime290.jsx)(
            import_components133.TextControl,
            {
              value: editedMenuTitle,
              placeholder: (0, import_i18n124.__)("Navigation title"),
              onChange: setEditedMenuTitle,
              label: (0, import_i18n124.__)("Name")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime290.jsxs)(import_components133.__experimentalHStack, { justify: "right", children: [
            /* @__PURE__ */ (0, import_jsx_runtime290.jsx)(
              import_components133.Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: onClose,
                children: (0, import_i18n124.__)("Cancel")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime290.jsx)(
              import_components133.Button,
              {
                __next40pxDefaultSize: true,
                accessibleWhenDisabled: true,
                disabled: !isEditedMenuTitleValid,
                variant: "primary",
                type: "submit",
                onClick: (e2) => {
                  e2.preventDefault();
                  if (!isEditedMenuTitleValid) {
                    return;
                  }
                  onSave({ title: editedMenuTitle });
                  onClose();
                },
                children: (0, import_i18n124.__)("Save")
              }
            )
          ] })
        ] }) })
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/delete-confirm-dialog.mjs
  var import_components134 = __toESM(require_components(), 1);
  var import_i18n125 = __toESM(require_i18n(), 1);
  var import_jsx_runtime291 = __toESM(require_jsx_runtime(), 1);
  function DeleteConfirmDialog({ onClose, onConfirm }) {
    return /* @__PURE__ */ (0, import_jsx_runtime291.jsx)(
      import_components134.__experimentalConfirmDialog,
      {
        isOpen: true,
        onConfirm: () => {
          onConfirm();
          onClose();
        },
        onCancel: onClose,
        confirmButtonText: (0, import_i18n125.__)("Delete"),
        size: "medium",
        children: (0, import_i18n125.__)("Are you sure you want to delete this Navigation Menu?")
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/more-menu.mjs
  var import_jsx_runtime292 = __toESM(require_jsx_runtime(), 1);
  var { useHistory: useHistory14 } = unlock(import_router21.privateApis);
  var POPOVER_PROPS = {
    position: "bottom right"
  };
  function ScreenNavigationMoreMenu(props) {
    const { onDelete, onSave, onDuplicate, menuTitle, menuId } = props;
    const [renameModalOpen, setRenameModalOpen] = (0, import_element166.useState)(false);
    const [deleteConfirmDialogOpen, setDeleteConfirmDialogOpen] = (0, import_element166.useState)(false);
    const history = useHistory14();
    const closeModals = () => {
      setRenameModalOpen(false);
      setDeleteConfirmDialogOpen(false);
    };
    const openRenameModal = () => setRenameModalOpen(true);
    const openDeleteConfirmDialog = () => setDeleteConfirmDialogOpen(true);
    return /* @__PURE__ */ (0, import_jsx_runtime292.jsxs)(import_jsx_runtime292.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
        import_components135.DropdownMenu,
        {
          className: "sidebar-navigation__more-menu",
          label: (0, import_i18n126.__)("Actions"),
          icon: more_vertical_default,
          popoverProps: POPOVER_PROPS,
          children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime292.jsxs)(import_components135.MenuGroup, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
              import_components135.MenuItem,
              {
                onClick: () => {
                  openRenameModal();
                  onClose();
                },
                children: (0, import_i18n126.__)("Rename")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
              import_components135.MenuItem,
              {
                onClick: () => {
                  history.navigate(
                    `/wp_navigation/${menuId}?canvas=edit`
                  );
                },
                children: (0, import_i18n126.__)("Edit")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
              import_components135.MenuItem,
              {
                onClick: () => {
                  onDuplicate();
                  onClose();
                },
                children: (0, import_i18n126.__)("Duplicate")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
              import_components135.MenuItem,
              {
                isDestructive: true,
                onClick: () => {
                  openDeleteConfirmDialog();
                  onClose();
                },
                children: (0, import_i18n126.__)("Delete")
              }
            )
          ] })
        }
      ),
      deleteConfirmDialogOpen && /* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
        DeleteConfirmDialog,
        {
          onClose: closeModals,
          onConfirm: onDelete
        }
      ),
      renameModalOpen && /* @__PURE__ */ (0, import_jsx_runtime292.jsx)(
        RenameModal,
        {
          onClose: closeModals,
          menuTitle,
          onSave
        }
      )
    ] });
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/navigation-menu-editor.mjs
  var import_element169 = __toESM(require_element(), 1);
  var import_data58 = __toESM(require_data(), 1);
  var import_block_editor22 = __toESM(require_block_editor(), 1);
  var import_blocks10 = __toESM(require_blocks(), 1);
  var import_core_data37 = __toESM(require_core_data(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menus/navigation-menu-content.mjs
  var import_block_editor21 = __toESM(require_block_editor(), 1);
  var import_data57 = __toESM(require_data(), 1);
  var import_blocks9 = __toESM(require_blocks(), 1);
  var import_element168 = __toESM(require_element(), 1);
  var import_core_data36 = __toESM(require_core_data(), 1);
  var import_block_library2 = __toESM(require_block_library(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menus/leaf-more-menu.mjs
  var import_components136 = __toESM(require_components(), 1);
  var import_data56 = __toESM(require_data(), 1);
  var import_element167 = __toESM(require_element(), 1);
  var import_i18n127 = __toESM(require_i18n(), 1);
  var import_block_editor20 = __toESM(require_block_editor(), 1);
  var import_router22 = __toESM(require_router(), 1);
  var import_jsx_runtime293 = __toESM(require_jsx_runtime(), 1);
  var POPOVER_PROPS2 = {
    className: "block-editor-block-settings-menu__popover",
    placement: "bottom-start"
  };
  var { useHistory: useHistory15, useLocation: useLocation21 } = unlock(import_router22.privateApis);
  function LeafMoreMenu(props) {
    const history = useHistory15();
    const { path } = useLocation21();
    const { block } = props;
    const { clientId } = block;
    const { moveBlocksDown, moveBlocksUp, removeBlocks } = (0, import_data56.useDispatch)(import_block_editor20.store);
    const removeLabel = (0, import_i18n127.sprintf)(
      /* translators: %s: block name */
      (0, import_i18n127.__)("Remove %s"),
      (0, import_block_editor20.BlockTitle)({ clientId, maximumLength: 25 })
    );
    const goToLabel = (0, import_i18n127.sprintf)(
      /* translators: %s: block name */
      (0, import_i18n127.__)("Go to %s"),
      (0, import_block_editor20.BlockTitle)({ clientId, maximumLength: 25 })
    );
    const rootClientId = (0, import_data56.useSelect)(
      (select4) => {
        const { getBlockRootClientId } = select4(import_block_editor20.store);
        return getBlockRootClientId(clientId);
      },
      [clientId]
    );
    const onGoToPage = (0, import_element167.useCallback)(
      (selectedBlock) => {
        const { attributes, name: name2 } = selectedBlock;
        if (attributes.kind === "post-type" && attributes.id && attributes.type && history) {
          history.navigate(
            `/${attributes.type}/${attributes.id}?canvas=edit`,
            {
              state: { backPath: path }
            }
          );
        }
        if (name2 === "core/page-list-item" && attributes.id && history) {
          history.navigate(`/page/${attributes.id}?canvas=edit`, {
            state: { backPath: path }
          });
        }
      },
      [path, history]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(
      import_components136.DropdownMenu,
      {
        icon: more_vertical_default,
        label: (0, import_i18n127.__)("Options"),
        className: "block-editor-block-settings-menu",
        popoverProps: POPOVER_PROPS2,
        noIcons: true,
        ...props,
        children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime293.jsxs)(import_jsx_runtime293.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime293.jsxs)(import_components136.MenuGroup, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(
              import_components136.MenuItem,
              {
                icon: chevron_up_default,
                onClick: () => {
                  moveBlocksUp([clientId], rootClientId);
                  onClose();
                },
                children: (0, import_i18n127.__)("Move up")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(
              import_components136.MenuItem,
              {
                icon: chevron_down_default,
                onClick: () => {
                  moveBlocksDown([clientId], rootClientId);
                  onClose();
                },
                children: (0, import_i18n127.__)("Move down")
              }
            ),
            block.attributes?.type === "page" && block.attributes?.id && /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(
              import_components136.MenuItem,
              {
                onClick: () => {
                  onGoToPage(block);
                  onClose();
                },
                children: goToLabel
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(import_components136.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime293.jsx)(
            import_components136.MenuItem,
            {
              onClick: () => {
                removeBlocks([clientId], false);
                onClose();
              },
              children: removeLabel
            }
          ) })
        ] })
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menus/navigation-menu-content.mjs
  var import_jsx_runtime294 = __toESM(require_jsx_runtime(), 1);
  var { PrivateListView } = unlock(import_block_editor21.privateApis);
  var { NavigationLinkUI } = unlock(import_block_library2.privateApis);
  var MAX_PAGE_COUNT = 100;
  var PAGES_QUERY = [
    "postType",
    "page",
    {
      per_page: MAX_PAGE_COUNT,
      _fields: ["id", "link", "menu_order", "parent", "title", "type"],
      // TODO: When https://core.trac.wordpress.org/ticket/39037 REST API support for multiple orderby
      // values is resolved, update 'orderby' to [ 'menu_order', 'post_title' ] to provide a consistent
      // sort.
      orderby: "menu_order",
      order: "asc"
    }
  ];
  function NavigationMenuContent({ rootClientId }) {
    const { listViewRootClientId, isLoading } = (0, import_data57.useSelect)(
      (select4) => {
        const {
          areInnerBlocksControlled,
          getBlockName,
          getBlockCount,
          getBlockOrder
        } = select4(import_block_editor21.store);
        const { isResolving } = select4(import_core_data36.store);
        const blockClientIds = getBlockOrder(rootClientId);
        const hasOnlyPageListBlock = blockClientIds.length === 1 && getBlockName(blockClientIds[0]) === "core/page-list";
        const pageListHasBlocks = hasOnlyPageListBlock && getBlockCount(blockClientIds[0]) > 0;
        const isLoadingPages = isResolving(
          "getEntityRecords",
          PAGES_QUERY
        );
        return {
          listViewRootClientId: pageListHasBlocks ? blockClientIds[0] : rootClientId,
          // This is a small hack to wait for the navigation block
          // to actually load its inner blocks.
          isLoading: !areInnerBlocksControlled(rootClientId) || isLoadingPages
        };
      },
      [rootClientId]
    );
    const { replaceBlock, __unstableMarkNextChangeAsNotPersistent } = (0, import_data57.useDispatch)(import_block_editor21.store);
    const offCanvasOnselect = (0, import_element168.useCallback)(
      (block) => {
        if (block.name === "core/navigation-link" && !block.attributes.url) {
          __unstableMarkNextChangeAsNotPersistent();
          replaceBlock(
            block.clientId,
            (0, import_blocks9.createBlock)("core/navigation-link", block.attributes)
          );
        }
      },
      [__unstableMarkNextChangeAsNotPersistent, replaceBlock]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime294.jsxs)(import_jsx_runtime294.Fragment, { children: [
      !isLoading && /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(
        PrivateListView,
        {
          rootClientId: listViewRootClientId,
          onSelect: offCanvasOnselect,
          blockSettingsMenu: LeafMoreMenu,
          showAppender: true,
          additionalBlockContent: NavigationLinkUI,
          isExpanded: true
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime294.jsx)("div", { className: "edit-site-sidebar-navigation-screen-navigation-menus__helper-block-editor", children: /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(import_block_editor21.BlockList, {}) })
    ] });
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/navigation-menu-editor.mjs
  var import_jsx_runtime295 = __toESM(require_jsx_runtime(), 1);
  var noop6 = () => {
  };
  function NavigationMenuEditor({ navigationMenuId }) {
    const { storedSettings } = (0, import_data58.useSelect)((select4) => {
      const { getSettings: getSettings7 } = unlock(select4(store));
      return {
        storedSettings: getSettings7()
      };
    }, []);
    const settings2 = (0, import_element169.useMemo)(() => {
      return {
        ...storedSettings,
        __experimentalFetchLinkSuggestions: (search, searchOptions) => (0, import_core_data37.__experimentalFetchLinkSuggestions)(search, searchOptions, storedSettings)
      };
    }, [storedSettings]);
    const blocks = (0, import_element169.useMemo)(() => {
      if (!navigationMenuId) {
        return [];
      }
      return [(0, import_blocks10.createBlock)("core/navigation", { ref: navigationMenuId })];
    }, [navigationMenuId]);
    if (!navigationMenuId || !blocks?.length) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(
      import_block_editor22.BlockEditorProvider,
      {
        settings: settings2,
        value: blocks,
        onChange: noop6,
        onInput: noop6,
        children: /* @__PURE__ */ (0, import_jsx_runtime295.jsx)("div", { className: "edit-site-sidebar-navigation-screen-navigation-menus__content", children: /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(NavigationMenuContent, { rootClientId: blocks[0].clientId }) })
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menus/build-navigation-label.mjs
  var import_i18n128 = __toESM(require_i18n(), 1);
  var import_html_entities4 = __toESM(require_html_entities(), 1);
  function buildNavigationLabel(title, id, status) {
    if (!title?.rendered) {
      return (0, import_i18n128.sprintf)((0, import_i18n128.__)("(no title %s)"), id);
    }
    if (status === "publish") {
      return (0, import_html_entities4.decodeEntities)(title?.rendered);
    }
    return (0, import_i18n128.sprintf)(
      // translators: 1: title of the menu. 2: status of the menu (draft, pending, etc.).
      (0, import_i18n128._x)("%1$s (%2$s)", "menu label"),
      (0, import_html_entities4.decodeEntities)(title?.rendered),
      status
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/single-navigation-menu.mjs
  var import_jsx_runtime296 = __toESM(require_jsx_runtime(), 1);
  function SingleNavigationMenu({
    navigationMenu,
    backPath,
    handleDelete,
    handleDuplicate,
    handleSave
  }) {
    const menuTitle = navigationMenu?.title?.rendered;
    return /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
      SidebarNavigationScreenWrapper,
      {
        actions: /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_jsx_runtime296.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
          ScreenNavigationMoreMenu,
          {
            menuId: navigationMenu?.id,
            menuTitle: (0, import_html_entities5.decodeEntities)(menuTitle),
            onDelete: handleDelete,
            onSave: handleSave,
            onDuplicate: handleDuplicate
          }
        ) }),
        backPath,
        title: buildNavigationLabel(
          navigationMenu?.title,
          navigationMenu?.id,
          navigationMenu?.status
        ),
        description: (0, import_i18n129.__)(
          "Navigation Menus are a curated collection of blocks that allow visitors to get around your site."
        ),
        children: /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(NavigationMenuEditor, { navigationMenuId: navigationMenu?.id })
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/use-navigation-menu-handlers.mjs
  var import_core_data39 = __toESM(require_core_data(), 1);
  var import_i18n131 = __toESM(require_i18n(), 1);
  var import_data60 = __toESM(require_data(), 1);
  var import_notices5 = __toESM(require_notices(), 1);
  var import_router24 = __toESM(require_router(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/index.mjs
  var import_core_data38 = __toESM(require_core_data(), 1);
  var import_components137 = __toESM(require_components(), 1);
  var import_i18n130 = __toESM(require_i18n(), 1);
  var import_data59 = __toESM(require_data(), 1);
  var import_html_entities6 = __toESM(require_html_entities(), 1);
  var import_router23 = __toESM(require_router(), 1);
  var import_jsx_runtime297 = __toESM(require_jsx_runtime(), 1);
  var { useLocation: useLocation22 } = unlock(import_router23.privateApis);
  var postType = `wp_navigation`;
  function SidebarNavigationScreenNavigationMenu({ backPath }) {
    const {
      params: { postId }
    } = useLocation22();
    const { record: navigationMenu, isResolving } = (0, import_core_data38.useEntityRecord)(
      "postType",
      postType,
      postId
    );
    const { isSaving, isDeleting } = (0, import_data59.useSelect)(
      (select4) => {
        const { isSavingEntityRecord, isDeletingEntityRecord } = select4(import_core_data38.store);
        return {
          isSaving: isSavingEntityRecord("postType", postType, postId),
          isDeleting: isDeletingEntityRecord(
            "postType",
            postType,
            postId
          )
        };
      },
      [postId]
    );
    const isLoading = isResolving || isSaving || isDeleting;
    const menuTitle = navigationMenu?.title?.rendered || navigationMenu?.slug;
    const { handleSave, handleDelete, handleDuplicate } = useNavigationMenuHandlers();
    const _handleDelete = () => handleDelete(navigationMenu);
    const _handleSave = (edits) => handleSave(navigationMenu, edits);
    const _handleDuplicate = () => handleDuplicate(navigationMenu);
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime297.jsx)(
        SidebarNavigationScreenWrapper,
        {
          description: (0, import_i18n130.__)(
            "Navigation Menus are a curated collection of blocks that allow visitors to get around your site."
          ),
          backPath,
          children: /* @__PURE__ */ (0, import_jsx_runtime297.jsx)(import_components137.Spinner, { className: "edit-site-sidebar-navigation-screen-navigation-menus__loading" })
        }
      );
    }
    if (!isLoading && !navigationMenu) {
      return /* @__PURE__ */ (0, import_jsx_runtime297.jsx)(
        SidebarNavigationScreenWrapper,
        {
          description: (0, import_i18n130.__)("Navigation Menu missing."),
          backPath
        }
      );
    }
    if (!navigationMenu?.content?.raw) {
      return /* @__PURE__ */ (0, import_jsx_runtime297.jsx)(
        SidebarNavigationScreenWrapper,
        {
          actions: /* @__PURE__ */ (0, import_jsx_runtime297.jsx)(
            ScreenNavigationMoreMenu,
            {
              menuId: navigationMenu?.id,
              menuTitle: (0, import_html_entities6.decodeEntities)(menuTitle),
              onDelete: _handleDelete,
              onSave: _handleSave,
              onDuplicate: _handleDuplicate
            }
          ),
          backPath,
          title: buildNavigationLabel(
            navigationMenu?.title,
            navigationMenu?.id,
            navigationMenu?.status
          ),
          description: (0, import_i18n130.__)("This Navigation Menu is empty.")
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime297.jsx)(
      SingleNavigationMenu,
      {
        navigationMenu,
        backPath,
        handleDelete: _handleDelete,
        handleSave: _handleSave,
        handleDuplicate: _handleDuplicate
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menu/use-navigation-menu-handlers.mjs
  var { useHistory: useHistory16 } = unlock(import_router24.privateApis);
  function useDeleteNavigationMenu() {
    const { deleteEntityRecord } = (0, import_data60.useDispatch)(import_core_data39.store);
    const { createSuccessNotice, createErrorNotice } = (0, import_data60.useDispatch)(import_notices5.store);
    const history = useHistory16();
    const handleDelete = async (navigationMenu) => {
      const postId = navigationMenu?.id;
      try {
        await deleteEntityRecord(
          "postType",
          postType,
          postId,
          {
            force: true
          },
          {
            throwOnError: true
          }
        );
        createSuccessNotice(
          (0, import_i18n131.__)("Navigation Menu successfully deleted."),
          {
            type: "snackbar"
          }
        );
        history.navigate("/navigation");
      } catch (error2) {
        createErrorNotice(
          (0, import_i18n131.sprintf)(
            /* translators: %s: error message describing why the navigation menu could not be deleted. */
            (0, import_i18n131.__)(`Unable to delete Navigation Menu (%s).`),
            error2?.message
          ),
          {
            type: "snackbar"
          }
        );
      }
    };
    return handleDelete;
  }
  function useSaveNavigationMenu() {
    const { getEditedEntityRecord } = (0, import_data60.useSelect)((select4) => {
      const { getEditedEntityRecord: getEditedEntityRecordSelector } = select4(import_core_data39.store);
      return {
        getEditedEntityRecord: getEditedEntityRecordSelector
      };
    }, []);
    const {
      editEntityRecord,
      __experimentalSaveSpecifiedEntityEdits: saveSpecifiedEntityEdits
    } = (0, import_data60.useDispatch)(import_core_data39.store);
    const { createSuccessNotice, createErrorNotice } = (0, import_data60.useDispatch)(import_notices5.store);
    const handleSave = async (navigationMenu, edits) => {
      if (!edits) {
        return;
      }
      const postId = navigationMenu?.id;
      const originalRecord = getEditedEntityRecord(
        "postType",
        NAVIGATION_POST_TYPE,
        postId
      );
      editEntityRecord("postType", postType, postId, edits);
      const recordPropertiesToSave = Object.keys(edits);
      try {
        await saveSpecifiedEntityEdits(
          "postType",
          postType,
          postId,
          recordPropertiesToSave,
          {
            throwOnError: true
          }
        );
        createSuccessNotice((0, import_i18n131.__)("Renamed Navigation Menu"), {
          type: "snackbar"
        });
      } catch (error2) {
        editEntityRecord("postType", postType, postId, originalRecord);
        createErrorNotice(
          (0, import_i18n131.sprintf)(
            /* translators: %s: error message describing why the navigation menu could not be renamed. */
            (0, import_i18n131.__)(`Unable to rename Navigation Menu (%s).`),
            error2?.message
          ),
          {
            type: "snackbar"
          }
        );
      }
    };
    return handleSave;
  }
  function useDuplicateNavigationMenu() {
    const history = useHistory16();
    const { saveEntityRecord } = (0, import_data60.useDispatch)(import_core_data39.store);
    const { createSuccessNotice, createErrorNotice } = (0, import_data60.useDispatch)(import_notices5.store);
    const handleDuplicate = async (navigationMenu) => {
      const menuTitle = navigationMenu?.title?.rendered || navigationMenu?.slug;
      try {
        const savedRecord = await saveEntityRecord(
          "postType",
          postType,
          {
            title: (0, import_i18n131.sprintf)(
              /* translators: %s: Navigation menu title */
              (0, import_i18n131._x)("%s (Copy)", "navigation menu"),
              menuTitle
            ),
            content: navigationMenu?.content?.raw,
            status: "publish"
          },
          {
            throwOnError: true
          }
        );
        if (savedRecord) {
          createSuccessNotice((0, import_i18n131.__)("Duplicated Navigation Menu"), {
            type: "snackbar"
          });
          history.navigate(`/wp_navigation/${savedRecord.id}`);
        }
      } catch (error2) {
        createErrorNotice(
          (0, import_i18n131.sprintf)(
            /* translators: %s: error message describing why the navigation menu could not be deleted. */
            (0, import_i18n131.__)(`Unable to duplicate Navigation Menu (%s).`),
            error2?.message
          ),
          {
            type: "snackbar"
          }
        );
      }
    };
    return handleDuplicate;
  }
  function useNavigationMenuHandlers() {
    return {
      handleDelete: useDeleteNavigationMenu(),
      handleSave: useSaveNavigationMenu(),
      handleDuplicate: useDuplicateNavigationMenu()
    };
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-navigation-menus/index.mjs
  var import_jsx_runtime298 = __toESM(require_jsx_runtime(), 1);
  function buildMenuLabel(title, id, status) {
    if (!title) {
      return (0, import_i18n132.sprintf)((0, import_i18n132.__)("(no title %s)"), id);
    }
    if (status === "publish") {
      return (0, import_html_entities7.decodeEntities)(title);
    }
    return (0, import_i18n132.sprintf)(
      // translators: 1: title of the menu. 2: status of the menu (draft, pending, etc.).
      (0, import_i18n132._x)("%1$s (%2$s)", "menu label"),
      (0, import_html_entities7.decodeEntities)(title),
      status
    );
  }
  function SidebarNavigationScreenNavigationMenus({ backPath }) {
    const {
      records: navigationMenus,
      isResolving: isResolvingNavigationMenus,
      hasResolved: hasResolvedNavigationMenus
    } = (0, import_core_data40.useEntityRecords)(
      "postType",
      NAVIGATION_POST_TYPE,
      PRELOADED_NAVIGATION_MENUS_QUERY
    );
    const isLoading = isResolvingNavigationMenus && !hasResolvedNavigationMenus;
    const { getNavigationFallbackId } = unlock((0, import_data61.useSelect)(import_core_data40.store));
    const isCreatingNavigationFallback = (0, import_data61.useSelect)(
      (select4) => select4(import_core_data40.store).isResolving("getNavigationFallbackId"),
      []
    );
    const firstNavigationMenu = navigationMenus?.[0];
    if (!firstNavigationMenu && !isResolvingNavigationMenus && hasResolvedNavigationMenus && // Ensure a fallback navigation is created only once
    !isCreatingNavigationFallback) {
      getNavigationFallbackId();
    }
    const { handleSave, handleDelete, handleDuplicate } = useNavigationMenuHandlers();
    const hasNavigationMenus = !!navigationMenus?.length;
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(SidebarNavigationScreenWrapper, { backPath, children: /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(import_components138.Spinner, { className: "edit-site-sidebar-navigation-screen-navigation-menus__loading" }) });
    }
    if (!isLoading && !hasNavigationMenus) {
      return /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
        SidebarNavigationScreenWrapper,
        {
          description: (0, import_i18n132.__)("No Navigation Menus found."),
          backPath
        }
      );
    }
    if (navigationMenus?.length === 1) {
      return /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
        SingleNavigationMenu,
        {
          navigationMenu: firstNavigationMenu,
          backPath,
          handleDelete: () => handleDelete(firstNavigationMenu),
          handleDuplicate: () => handleDuplicate(firstNavigationMenu),
          handleSave: (edits) => handleSave(firstNavigationMenu, edits)
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(SidebarNavigationScreenWrapper, { backPath, children: /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(import_components138.__experimentalItemGroup, { className: "edit-site-sidebar-navigation-screen-navigation-menus", children: navigationMenus?.map(({ id, title, status }, index2) => /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
      NavMenuItem,
      {
        postId: id,
        withChevron: true,
        icon: navigation_default,
        children: buildMenuLabel(title?.rendered, index2 + 1, status)
      },
      id
    )) }) });
  }
  function SidebarNavigationScreenWrapper({
    children,
    actions,
    title,
    description,
    backPath
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
      SidebarNavigationScreen,
      {
        title: title || (0, import_i18n132.__)("Navigation"),
        actions,
        description: description || (0, import_i18n132.__)("Manage your Navigation Menus."),
        backPath,
        content: children
      }
    );
  }
  var NavMenuItem = ({ postId, ...props }) => {
    return /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
      SidebarNavigationItem,
      {
        to: `/wp_navigation/${postId}`,
        ...props
      }
    );
  };

  // packages/edit-site/build-module/components/site-editor-routes/navigation.mjs
  var import_jsx_runtime299 = __toESM(require_jsx_runtime(), 1);
  var navigationRoute = {
    name: "navigation",
    path: "/navigation",
    areas: {
      sidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return null;
        }
        return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(SidebarNavigationScreenNavigationMenus, { backPath: "/" }) : /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(SidebarNavigationScreenUnsupported, {});
      },
      preview({ siteData }) {
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        return isBlockTheme ? /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(EditSiteEditor, {}) : void 0;
      },
      mobileSidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(import_jsx_runtime299.Fragment, {});
        }
        return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(SidebarNavigationScreenNavigationMenus, { backPath: "/" }) : /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(SidebarNavigationScreenUnsupported, {});
      }
    }
  };

  // packages/edit-site/build-module/components/site-editor-routes/navigation-item.mjs
  var import_jsx_runtime300 = __toESM(require_jsx_runtime(), 1);
  var navigationItemRoute = {
    name: "navigation-item",
    path: "/wp_navigation/:postId",
    areas: {
      sidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return null;
        }
        return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(SidebarNavigationScreenNavigationMenu, { backPath: "/navigation" }) : /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(SidebarNavigationScreenUnsupported, {});
      },
      preview({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return null;
        }
        return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(EditSiteEditor, {}) : /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(SidebarNavigationScreenUnsupported, {});
      },
      mobileSidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(import_jsx_runtime300.Fragment, {});
        }
        return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(SidebarNavigationScreenNavigationMenu, { backPath: "/navigation" }) : /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(SidebarNavigationScreenUnsupported, {});
      }
    }
  };

  // packages/edit-site/build-module/components/sidebar-navigation-screen-patterns/index.mjs
  var import_components139 = __toESM(require_components(), 1);
  var import_editor28 = __toESM(require_editor(), 1);
  var import_element174 = __toESM(require_element(), 1);
  var import_i18n134 = __toESM(require_i18n(), 1);
  var import_router25 = __toESM(require_router(), 1);

  // node_modules/dequal/dist/index.mjs
  var has = Object.prototype.hasOwnProperty;
  function find(iter, tar, key) {
    for (key of iter.keys()) {
      if (dequal(key, tar)) return key;
    }
  }
  function dequal(foo, bar) {
    var ctor, len, tmp;
    if (foo === bar) return true;
    if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
      if (ctor === Date) return foo.getTime() === bar.getTime();
      if (ctor === RegExp) return foo.toString() === bar.toString();
      if (ctor === Array) {
        if ((len = foo.length) === bar.length) {
          while (len-- && dequal(foo[len], bar[len])) ;
        }
        return len === -1;
      }
      if (ctor === Set) {
        if (foo.size !== bar.size) {
          return false;
        }
        for (len of foo) {
          tmp = len;
          if (tmp && typeof tmp === "object") {
            tmp = find(bar, tmp);
            if (!tmp) return false;
          }
          if (!bar.has(tmp)) return false;
        }
        return true;
      }
      if (ctor === Map) {
        if (foo.size !== bar.size) {
          return false;
        }
        for (len of foo) {
          tmp = len[0];
          if (tmp && typeof tmp === "object") {
            tmp = find(bar, tmp);
            if (!tmp) return false;
          }
          if (!dequal(len[1], bar.get(tmp))) {
            return false;
          }
        }
        return true;
      }
      if (ctor === ArrayBuffer) {
        foo = new Uint8Array(foo);
        bar = new Uint8Array(bar);
      } else if (ctor === DataView) {
        if ((len = foo.byteLength) === bar.byteLength) {
          while (len-- && foo.getInt8(len) === bar.getInt8(len)) ;
        }
        return len === -1;
      }
      if (ArrayBuffer.isView(foo)) {
        if ((len = foo.byteLength) === bar.byteLength) {
          while (len-- && foo[len] === bar[len]) ;
        }
        return len === -1;
      }
      if (!ctor || typeof foo === "object") {
        len = 0;
        for (ctor in foo) {
          if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;
          if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;
        }
        return Object.keys(bar).length === len;
      }
    }
    return foo !== foo && bar !== bar;
  }

  // packages/views/build-module/use-view.mjs
  var import_element170 = __toESM(require_element(), 1);
  var import_data62 = __toESM(require_data(), 1);
  var import_preferences11 = __toESM(require_preferences(), 1);

  // packages/views/build-module/preference-keys.mjs
  function generatePreferenceKey(kind, name2, slug) {
    return `dataviews-${kind}-${name2}-${slug}`;
  }

  // packages/views/build-module/filter-utils.mjs
  var SCALAR_VALUES = [
    "titleField",
    "mediaField",
    "descriptionField",
    "showTitle",
    "showMedia",
    "showDescription",
    "showLevels",
    "infiniteScrollEnabled"
  ];
  function mergeActiveViewOverrides(view, activeViewOverrides, defaultView) {
    if (!activeViewOverrides) {
      return view;
    }
    let result = view;
    for (const key of SCALAR_VALUES) {
      if (key in activeViewOverrides) {
        result = { ...result, [key]: activeViewOverrides[key] };
      }
    }
    if (activeViewOverrides.filters && activeViewOverrides.filters.length > 0) {
      const activeFields = new Set(
        activeViewOverrides.filters.map((f2) => f2.field)
      );
      const preserved = (view.filters ?? []).filter(
        (f2) => !activeFields.has(f2.field)
      );
      result = {
        ...result,
        filters: [...preserved, ...activeViewOverrides.filters]
      };
    }
    if (activeViewOverrides.sort) {
      const isDefaultSort = defaultView && view.sort?.field === defaultView.sort?.field && view.sort?.direction === defaultView.sort?.direction;
      if (isDefaultSort) {
        result = {
          ...result,
          sort: activeViewOverrides.sort
        };
      }
    }
    if (activeViewOverrides.layout) {
      result = {
        ...result,
        layout: {
          ...result.layout,
          ...activeViewOverrides.layout
        }
      };
    }
    if (activeViewOverrides.groupBy) {
      result = {
        ...result,
        groupBy: activeViewOverrides.groupBy
      };
    }
    return result;
  }
  function stripActiveViewOverrides(view, activeViewOverrides, defaultView) {
    if (!activeViewOverrides) {
      return view;
    }
    let result = view;
    for (const key of SCALAR_VALUES) {
      if (key in activeViewOverrides) {
        const { [key]: _, ...rest } = result;
        result = rest;
      }
    }
    if (activeViewOverrides.filters && activeViewOverrides.filters.length > 0) {
      const activeFields = new Set(
        activeViewOverrides.filters.map((f2) => f2.field)
      );
      result = {
        ...result,
        filters: (view.filters ?? []).filter(
          (f2) => !activeFields.has(f2.field)
        )
      };
    }
    if (activeViewOverrides.sort && view.sort?.field === activeViewOverrides.sort.field && view.sort?.direction === activeViewOverrides.sort.direction) {
      result = {
        ...result,
        sort: defaultView?.sort
      };
    }
    if (activeViewOverrides.layout && "layout" in result && result.layout) {
      const layout = { ...result.layout };
      for (const key of Object.keys(activeViewOverrides.layout)) {
        delete layout[key];
      }
      result = {
        ...result,
        layout: Object.keys(layout).length > 0 ? layout : void 0
      };
    }
    if (activeViewOverrides.groupBy && "groupBy" in result) {
      const { groupBy: _, ...rest } = result;
      result = rest;
    }
    return result;
  }

  // packages/views/build-module/use-view.mjs
  function omit3(obj, keys) {
    const result = { ...obj };
    for (const key of keys) {
      delete result[key];
    }
    return result;
  }
  function useView(config2) {
    const {
      kind,
      name: name2,
      slug,
      defaultView,
      activeViewOverrides,
      queryParams,
      onChangeQueryParams
    } = config2;
    const preferenceKey = generatePreferenceKey(kind, name2, slug);
    const persistedView = (0, import_data62.useSelect)(
      (select4) => {
        return select4(import_preferences11.store).get(
          "core/views",
          preferenceKey
        );
      },
      [preferenceKey]
    );
    const { set: set3 } = (0, import_data62.useDispatch)(import_preferences11.store);
    const baseView = (0, import_element170.useMemo)(
      () => persistedView ?? defaultView ?? {},
      [persistedView, defaultView]
    );
    const page = Number(queryParams?.page ?? baseView.page ?? 1);
    const search = queryParams?.search ?? baseView.search ?? "";
    const combinedOverrides = (0, import_element170.useMemo)(() => {
      const rawDefaults = config2.defaultLayouts?.[baseView.type];
      const layoutTypeDefaults = !rawDefaults || rawDefaults === true ? {} : rawDefaults;
      return { ...layoutTypeDefaults, ...activeViewOverrides };
    }, [config2.defaultLayouts, baseView.type, activeViewOverrides]);
    const view = (0, import_element170.useMemo)(() => {
      return mergeActiveViewOverrides(
        {
          ...baseView,
          page,
          search
        },
        combinedOverrides,
        defaultView
      );
    }, [baseView, page, search, combinedOverrides, defaultView]);
    const isModified = !!persistedView;
    const updateView = (0, import_element170.useCallback)(
      (newView) => {
        const urlParams = {
          page: newView?.page,
          search: newView?.search
        };
        const preferenceView = stripActiveViewOverrides(
          omit3(newView, ["page", "search"]),
          combinedOverrides,
          defaultView
        );
        if (onChangeQueryParams && !dequal(urlParams, { page, search })) {
          onChangeQueryParams(urlParams);
        }
        const comparableBaseView = stripActiveViewOverrides(
          baseView,
          combinedOverrides,
          defaultView
        );
        const comparableDefaultView = stripActiveViewOverrides(
          defaultView,
          combinedOverrides,
          defaultView
        );
        if (!dequal(comparableBaseView, preferenceView)) {
          if (dequal(preferenceView, comparableDefaultView)) {
            set3("core/views", preferenceKey, void 0);
          } else {
            set3("core/views", preferenceKey, preferenceView);
          }
        }
      },
      [
        onChangeQueryParams,
        page,
        search,
        baseView,
        defaultView,
        combinedOverrides,
        set3,
        preferenceKey
      ]
    );
    const resetToDefault = (0, import_element170.useCallback)(() => {
      set3("core/views", preferenceKey, void 0);
    }, [preferenceKey, set3]);
    return {
      view,
      isModified,
      updateView,
      resetToDefault
    };
  }

  // packages/views/build-module/load-view.mjs
  var import_data63 = __toESM(require_data(), 1);
  var import_preferences12 = __toESM(require_preferences(), 1);
  async function loadView(config2) {
    const { kind, name: name2, slug, defaultView, activeViewOverrides, queryParams } = config2;
    const preferenceKey = generatePreferenceKey(kind, name2, slug);
    const persistedView = (0, import_data63.select)(import_preferences12.store).get(
      "core/views",
      preferenceKey
    );
    const baseView = persistedView ?? defaultView;
    const page = queryParams?.page ?? 1;
    const search = queryParams?.search ?? "";
    const rawDefaults = config2.defaultLayouts?.[baseView?.type];
    const layoutTypeDefaults = !rawDefaults || rawDefaults === true ? {} : rawDefaults;
    const combinedOverrides = { ...layoutTypeDefaults, ...activeViewOverrides };
    return mergeActiveViewOverrides(
      {
        ...baseView,
        page,
        search
      },
      combinedOverrides,
      defaultView
    );
  }

  // packages/views/build-module/use-view-config.mjs
  var import_data64 = __toESM(require_data(), 1);
  var import_core_data41 = __toESM(require_core_data(), 1);

  // packages/views/build-module/lock-unlock.mjs
  var import_private_apis8 = __toESM(require_private_apis(), 1);
  var { lock: lock7, unlock: unlock7 } = (0, import_private_apis8.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
    "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
    "@wordpress/views"
  );

  // packages/views/build-module/use-view-config.mjs
  function useViewConfig({
    kind,
    name: name2,
    fields: fields2
  }) {
    const fieldList = Array.isArray(fields2) ? fields2 : fields2?.split(",");
    const fieldsKey = fieldList ? [...fieldList].sort().join(",") : void 0;
    return (0, import_data64.useSelect)(
      (select4) => {
        return unlock7(select4(import_core_data41.store)).getViewConfig(kind, name2, {
          fields: fieldsKey
        });
      },
      [kind, name2, fieldsKey]
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-patterns/category-item.mjs
  var import_jsx_runtime301 = __toESM(require_jsx_runtime(), 1);
  function CategoryItem({
    count,
    icon,
    id,
    isActive,
    label,
    type
  }) {
    if (!count) {
      return;
    }
    const queryArgs = [`postType=${type}`];
    if (id) {
      queryArgs.push(`categoryId=${id}`);
    }
    return /* @__PURE__ */ (0, import_jsx_runtime301.jsx)(
      SidebarNavigationItem,
      {
        icon,
        suffix: /* @__PURE__ */ (0, import_jsx_runtime301.jsx)("span", { children: count }),
        "aria-current": isActive ? "true" : void 0,
        to: `/pattern?${queryArgs.join("&")}`,
        children: label
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-patterns/use-pattern-categories.mjs
  var import_element173 = __toESM(require_element(), 1);
  var import_i18n133 = __toESM(require_i18n(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-patterns/use-default-pattern-categories.mjs
  var import_core_data42 = __toESM(require_core_data(), 1);
  var import_data65 = __toESM(require_data(), 1);
  function useDefaultPatternCategories() {
    const blockPatternCategories = (0, import_data65.useSelect)((select4) => {
      const { getSettings: getSettings7 } = unlock(select4(store));
      const settings2 = getSettings7();
      return settings2.__experimentalAdditionalBlockPatternCategories ?? settings2.__experimentalBlockPatternCategories;
    });
    const restBlockPatternCategories = (0, import_data65.useSelect)(
      (select4) => select4(import_core_data42.store).getBlockPatternCategories()
    );
    return [
      ...blockPatternCategories || [],
      ...restBlockPatternCategories || []
    ];
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-patterns/use-theme-patterns.mjs
  var import_core_data43 = __toESM(require_core_data(), 1);
  var import_data66 = __toESM(require_data(), 1);
  var import_element171 = __toESM(require_element(), 1);

  // packages/edit-site/build-module/components/page-patterns/utils.mjs
  var filterOutDuplicatesByName = (currentItem, index2, items) => index2 === items.findIndex((item) => currentItem.name === item.name);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-patterns/use-theme-patterns.mjs
  function useThemePatterns() {
    const blockPatterns = (0, import_data66.useSelect)((select4) => {
      const { getSettings: getSettings7 } = unlock(select4(store));
      return getSettings7().__experimentalAdditionalBlockPatterns ?? getSettings7().__experimentalBlockPatterns;
    });
    const restBlockPatterns = (0, import_data66.useSelect)(
      (select4) => select4(import_core_data43.store).getBlockPatterns()
    );
    const patterns = (0, import_element171.useMemo)(
      () => [...blockPatterns || [], ...restBlockPatterns || []].filter(
        (pattern) => !EXCLUDED_PATTERN_SOURCES.includes(pattern.source)
      ).filter(filterOutDuplicatesByName).filter((pattern) => pattern.inserter !== false),
      [blockPatterns, restBlockPatterns]
    );
    return patterns;
  }

  // packages/edit-site/build-module/components/page-patterns/use-patterns.mjs
  var import_blocks11 = __toESM(require_blocks(), 1);
  var import_data67 = __toESM(require_data(), 1);
  var import_core_data44 = __toESM(require_core_data(), 1);
  var import_element172 = __toESM(require_element(), 1);

  // packages/edit-site/build-module/components/page-patterns/search-items.mjs
  var import_block_editor23 = __toESM(require_block_editor(), 1);
  var { extractWords, getNormalizedSearchTerms, normalizeString: normalizeString2 } = unlock(
    import_block_editor23.privateApis
  );
  var defaultGetName = (item) => {
    if (item.type === PATTERN_TYPES.user) {
      return item.slug;
    }
    if (item.type === TEMPLATE_PART_POST_TYPE) {
      return "";
    }
    return item.name || "";
  };
  var defaultGetTitle = (item) => {
    if (typeof item.title === "string") {
      return item.title;
    }
    if (item.title && item.title.rendered) {
      return item.title.rendered;
    }
    if (item.title && item.title.raw) {
      return item.title.raw;
    }
    return "";
  };
  var defaultGetDescription = (item) => {
    if (item.type === PATTERN_TYPES.user) {
      return item.excerpt.raw;
    }
    return item.description || "";
  };
  var defaultGetKeywords = (item) => item.keywords || [];
  var defaultHasCategory = () => false;
  var removeMatchingTerms = (unmatchedTerms, unprocessedTerms) => {
    return unmatchedTerms.filter(
      (term) => !getNormalizedSearchTerms(unprocessedTerms).some(
        (unprocessedTerm) => unprocessedTerm.includes(term)
      )
    );
  };
  var searchItems = (items = [], searchInput = "", config2 = {}) => {
    const normalizedSearchTerms = getNormalizedSearchTerms(searchInput);
    const onlyFilterByCategory = config2.categoryId !== PATTERN_DEFAULT_CATEGORY && !normalizedSearchTerms.length;
    const searchRankConfig = { ...config2, onlyFilterByCategory };
    const threshold = onlyFilterByCategory ? 0 : 1;
    const rankedItems = items.map((item) => {
      return [
        item,
        getItemSearchRank(item, searchInput, searchRankConfig)
      ];
    }).filter(([, rank]) => rank > threshold);
    if (normalizedSearchTerms.length === 0) {
      return rankedItems.map(([item]) => item);
    }
    rankedItems.sort(([, rank1], [, rank2]) => rank2 - rank1);
    return rankedItems.map(([item]) => item);
  };
  function getItemSearchRank(item, searchTerm, config2) {
    const {
      categoryId,
      getName = defaultGetName,
      getTitle = defaultGetTitle,
      getDescription = defaultGetDescription,
      getKeywords = defaultGetKeywords,
      hasCategory = defaultHasCategory,
      onlyFilterByCategory
    } = config2;
    let rank = categoryId === PATTERN_DEFAULT_CATEGORY || categoryId === TEMPLATE_PART_ALL_AREAS_CATEGORY || categoryId === PATTERN_USER_CATEGORY && item.type === PATTERN_TYPES.user || hasCategory(item, categoryId) ? 1 : 0;
    if (!rank || onlyFilterByCategory) {
      return rank;
    }
    const name2 = getName(item);
    const title = getTitle(item);
    const description = getDescription(item);
    const keywords = getKeywords(item);
    const normalizedSearchInput = normalizeString2(searchTerm);
    const normalizedTitle = normalizeString2(title);
    if (normalizedSearchInput === normalizedTitle) {
      rank += 30;
    } else if (normalizedTitle.startsWith(normalizedSearchInput)) {
      rank += 20;
    } else {
      const terms = [name2, title, description, ...keywords].join(" ");
      const normalizedSearchTerms = extractWords(normalizedSearchInput);
      const unmatchedTerms = removeMatchingTerms(
        normalizedSearchTerms,
        terms
      );
      if (unmatchedTerms.length === 0) {
        rank += 10;
      }
    }
    return rank;
  }

  // packages/edit-site/build-module/components/page-patterns/use-patterns.mjs
  var EMPTY_PATTERN_LIST = [];
  var selectTemplateParts = (0, import_data67.createSelector)(
    (select4, categoryId, search = "") => {
      const {
        getEntityRecords,
        getCurrentTheme,
        isResolving: isResolvingSelector
      } = select4(import_core_data44.store);
      const query = { per_page: -1 };
      const templateParts = getEntityRecords("postType", TEMPLATE_PART_POST_TYPE, query) ?? EMPTY_PATTERN_LIST;
      const knownAreas = getCurrentTheme()?.default_template_part_areas || [];
      const templatePartAreas = knownAreas.map((area) => area.area);
      const templatePartHasCategory = (item, category) => {
        if (category !== TEMPLATE_PART_AREA_DEFAULT_CATEGORY) {
          return item.area === category;
        }
        return item.area === category || !templatePartAreas.includes(item.area);
      };
      const isResolving = isResolvingSelector("getEntityRecords", [
        "postType",
        TEMPLATE_PART_POST_TYPE,
        query
      ]);
      const patterns = searchItems(templateParts, search, {
        categoryId,
        hasCategory: templatePartHasCategory
      });
      return { patterns, isResolving };
    },
    (select4) => [
      select4(import_core_data44.store).getEntityRecords(
        "postType",
        TEMPLATE_PART_POST_TYPE,
        {
          per_page: -1
        }
      ),
      select4(import_core_data44.store).isResolving("getEntityRecords", [
        "postType",
        TEMPLATE_PART_POST_TYPE,
        { per_page: -1 }
      ]),
      select4(import_core_data44.store).getCurrentTheme()?.default_template_part_areas
    ]
  );
  var selectThemePatterns = (0, import_data67.createSelector)(
    (select4) => {
      const { getSettings: getSettings7 } = unlock(select4(store));
      const { isResolving: isResolvingSelector } = select4(import_core_data44.store);
      const settings2 = getSettings7();
      const blockPatterns = settings2.__experimentalAdditionalBlockPatterns ?? settings2.__experimentalBlockPatterns;
      const restBlockPatterns = select4(import_core_data44.store).getBlockPatterns();
      const patterns = [
        ...blockPatterns || [],
        ...restBlockPatterns || []
      ].filter(
        (pattern) => !EXCLUDED_PATTERN_SOURCES.includes(pattern.source)
      ).filter(filterOutDuplicatesByName).filter((pattern) => pattern.inserter !== false).map((pattern) => ({
        ...pattern,
        keywords: pattern.keywords || [],
        type: PATTERN_TYPES.theme,
        blocks: (0, import_blocks11.parse)(pattern.content, {
          __unstableSkipMigrationLogs: true
        })
      }));
      return {
        patterns,
        isResolving: isResolvingSelector("getBlockPatterns")
      };
    },
    (select4) => [
      select4(import_core_data44.store).getBlockPatterns(),
      select4(import_core_data44.store).isResolving("getBlockPatterns"),
      unlock(select4(store)).getSettings()
    ]
  );
  var selectPatterns = (0, import_data67.createSelector)(
    (select4, categoryId, syncStatus, search = "") => {
      const {
        patterns: themePatterns,
        isResolving: isResolvingThemePatterns
      } = selectThemePatterns(select4);
      const {
        patterns: userPatterns,
        isResolving: isResolvingUserPatterns,
        categories: userPatternCategories
      } = selectUserPatterns(select4);
      let patterns = [
        ...themePatterns || [],
        ...userPatterns || []
      ];
      if (syncStatus) {
        patterns = patterns.filter((pattern) => {
          return pattern.type === PATTERN_TYPES.user ? (pattern.wp_pattern_sync_status || PATTERN_SYNC_TYPES.full) === syncStatus : syncStatus === PATTERN_SYNC_TYPES.unsynced;
        });
      }
      if (categoryId) {
        patterns = searchItems(patterns, search, {
          categoryId,
          hasCategory: (item, currentCategory) => {
            if (item.type === PATTERN_TYPES.user) {
              return item.wp_pattern_category?.some(
                (catId) => userPatternCategories.find(
                  (cat) => cat.id === catId
                )?.slug === currentCategory
              );
            }
            return item.categories?.includes(currentCategory);
          }
        });
      } else {
        patterns = searchItems(patterns, search, {
          hasCategory: (item) => {
            if (item.type === PATTERN_TYPES.user) {
              return userPatternCategories?.length && (!item.wp_pattern_category?.length || !item.wp_pattern_category?.some(
                (catId) => userPatternCategories.find(
                  (cat) => cat.id === catId
                )
              ));
            }
            return !item.hasOwnProperty("categories");
          }
        });
      }
      return {
        patterns,
        isResolving: isResolvingThemePatterns || isResolvingUserPatterns
      };
    },
    (select4) => [
      selectThemePatterns(select4),
      selectUserPatterns(select4)
    ]
  );
  var selectUserPatterns = (0, import_data67.createSelector)(
    (select4, syncStatus, search = "") => {
      const {
        getEntityRecords,
        isResolving: isResolvingSelector,
        getUserPatternCategories
      } = select4(import_core_data44.store);
      const query = { per_page: -1 };
      const patternPosts = getEntityRecords(
        "postType",
        PATTERN_TYPES.user,
        query
      );
      const userPatternCategories = getUserPatternCategories();
      const categories = /* @__PURE__ */ new Map();
      userPatternCategories.forEach(
        (userCategory) => categories.set(userCategory.id, userCategory)
      );
      let patterns = patternPosts ?? EMPTY_PATTERN_LIST;
      const isResolving = isResolvingSelector("getEntityRecords", [
        "postType",
        PATTERN_TYPES.user,
        query
      ]);
      if (syncStatus) {
        patterns = patterns.filter(
          (pattern) => pattern.wp_pattern_sync_status || PATTERN_SYNC_TYPES.full === syncStatus
        );
      }
      patterns = searchItems(patterns, search, {
        // We exit user pattern retrieval early if we aren't in the
        // catch-all category for user created patterns, so it has
        // to be in the category.
        hasCategory: () => true
      });
      return {
        patterns,
        isResolving,
        categories: userPatternCategories
      };
    },
    (select4) => [
      select4(import_core_data44.store).getEntityRecords("postType", PATTERN_TYPES.user, {
        per_page: -1
      }),
      select4(import_core_data44.store).isResolving("getEntityRecords", [
        "postType",
        PATTERN_TYPES.user,
        { per_page: -1 }
      ]),
      select4(import_core_data44.store).getUserPatternCategories()
    ]
  );
  function useAugmentPatternsWithPermissions(patterns) {
    const idsAndTypes = (0, import_element172.useMemo)(
      () => patterns?.filter((record) => record.type !== PATTERN_TYPES.theme).map((record) => [record.type, record.id]) ?? [],
      [patterns]
    );
    const permissions = (0, import_data67.useSelect)(
      (select4) => {
        const { getEntityRecordPermissions } = unlock(
          select4(import_core_data44.store)
        );
        return idsAndTypes.reduce((acc, [type, id]) => {
          acc[id] = getEntityRecordPermissions("postType", type, id);
          return acc;
        }, {});
      },
      [idsAndTypes]
    );
    return (0, import_element172.useMemo)(
      () => patterns?.map((record) => ({
        ...record,
        permissions: permissions?.[record.id] ?? {}
      })) ?? [],
      [patterns, permissions]
    );
  }
  var usePatterns = (postType2, categoryId, { search = "", syncStatus } = {}) => {
    return (0, import_data67.useSelect)(
      (select4) => {
        if (postType2 === TEMPLATE_PART_POST_TYPE) {
          return selectTemplateParts(select4, categoryId, search);
        } else if (postType2 === PATTERN_TYPES.user && !!categoryId) {
          const appliedCategory = categoryId === "uncategorized" ? "" : categoryId;
          return selectPatterns(
            select4,
            appliedCategory,
            syncStatus,
            search
          );
        } else if (postType2 === PATTERN_TYPES.user) {
          return selectUserPatterns(select4, syncStatus, search);
        }
        return {
          patterns: EMPTY_PATTERN_LIST,
          isResolving: false
        };
      },
      [categoryId, postType2, search, syncStatus]
    );
  };
  var use_patterns_default = usePatterns;

  // packages/edit-site/build-module/components/sidebar-navigation-screen-patterns/use-pattern-categories.mjs
  function usePatternCategories() {
    const defaultCategories = useDefaultPatternCategories();
    defaultCategories.push({
      name: TEMPLATE_PART_AREA_DEFAULT_CATEGORY,
      label: (0, import_i18n133.__)("Uncategorized")
    });
    const themePatterns = useThemePatterns();
    const { patterns: userPatterns, categories: userPatternCategories } = use_patterns_default(PATTERN_TYPES.user);
    const patternCategories = (0, import_element173.useMemo)(() => {
      const categoryMap = {};
      const categoriesWithCounts = [];
      defaultCategories.forEach((category) => {
        if (!categoryMap[category.name]) {
          categoryMap[category.name] = { ...category, count: 0 };
        }
      });
      userPatternCategories.forEach((category) => {
        if (!categoryMap[category.name]) {
          categoryMap[category.name] = { ...category, count: 0 };
        }
      });
      themePatterns.forEach((pattern) => {
        pattern.categories?.forEach((category) => {
          if (categoryMap[category]) {
            categoryMap[category].count += 1;
          }
        });
        if (!pattern.categories?.length) {
          categoryMap.uncategorized.count += 1;
        }
      });
      userPatterns.forEach((pattern) => {
        pattern.wp_pattern_category?.forEach((catId) => {
          const category = userPatternCategories.find(
            (cat) => cat.id === catId
          )?.name;
          if (categoryMap[category]) {
            categoryMap[category].count += 1;
          }
        });
        if (!pattern.wp_pattern_category?.length || !pattern.wp_pattern_category?.some(
          (catId) => userPatternCategories.find((cat) => cat.id === catId)
        )) {
          categoryMap.uncategorized.count += 1;
        }
      });
      [...defaultCategories, ...userPatternCategories].forEach(
        (category) => {
          if (categoryMap[category.name].count && !categoriesWithCounts.find(
            (cat) => cat.name === category.name
          )) {
            categoriesWithCounts.push(categoryMap[category.name]);
          }
        }
      );
      const sortedCategories = categoriesWithCounts.sort(
        (a2, b2) => a2.label.localeCompare(b2.label)
      );
      sortedCategories.unshift({
        name: PATTERN_USER_CATEGORY,
        label: (0, import_i18n133.__)("My patterns"),
        count: userPatterns.length
      });
      sortedCategories.unshift({
        name: PATTERN_DEFAULT_CATEGORY,
        label: (0, import_i18n133.__)("All patterns"),
        description: (0, import_i18n133.__)("A list of all patterns from all sources."),
        count: themePatterns.length + userPatterns.length
      });
      return sortedCategories;
    }, [
      defaultCategories,
      themePatterns,
      userPatternCategories,
      userPatterns
    ]);
    return { patternCategories, hasPatterns: !!patternCategories.length };
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-patterns/use-template-part-areas.mjs
  var import_core_data45 = __toESM(require_core_data(), 1);
  var import_data68 = __toESM(require_data(), 1);
  var import_block_library3 = __toESM(require_block_library(), 1);
  var { NAVIGATION_OVERLAY_TEMPLATE_PART_AREA } = unlock(
    import_block_library3.privateApis
  );
  var useTemplatePartsGroupedByArea = (items) => {
    const allItems = items || [];
    const templatePartAreas = (0, import_data68.useSelect)(
      (select4) => select4(import_core_data45.store).getCurrentTheme()?.default_template_part_areas || [],
      []
    );
    const knownAreas = {
      header: {},
      footer: {},
      sidebar: {},
      uncategorized: {},
      [NAVIGATION_OVERLAY_TEMPLATE_PART_AREA]: {}
    };
    templatePartAreas.forEach(
      (templatePartArea) => knownAreas[templatePartArea.area] = {
        ...templatePartArea,
        templateParts: []
      }
    );
    const groupedByArea = allItems.reduce((accumulator, item) => {
      const key = accumulator[item.area] ? item.area : TEMPLATE_PART_AREA_DEFAULT_CATEGORY;
      accumulator[key]?.templateParts?.push(item);
      return accumulator;
    }, knownAreas);
    return groupedByArea;
  };
  function useTemplatePartAreas() {
    const { records: templateParts, isResolving: isLoading } = (0, import_core_data45.useEntityRecords)(
      "postType",
      TEMPLATE_PART_POST_TYPE,
      { per_page: -1 }
    );
    return {
      hasTemplateParts: templateParts ? !!templateParts.length : false,
      isLoading,
      templatePartAreas: useTemplatePartsGroupedByArea(templateParts)
    };
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-patterns/index.mjs
  var import_jsx_runtime302 = __toESM(require_jsx_runtime(), 1);
  var VIEW_CONFIG_FIELDS = ["view_list"];
  var { useLocation: useLocation23 } = unlock(import_router25.privateApis);
  function CategoriesGroup({
    templatePartViews,
    patternViews,
    templatePartCounts,
    patternCounts,
    currentCategory,
    currentType
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime302.jsxs)(import_components139.__experimentalItemGroup, { className: "edit-site-sidebar-navigation-screen-patterns__group", children: [
      templatePartViews?.map((view) => /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        CategoryItem,
        {
          count: templatePartCounts[view.slug],
          icon: (0, import_editor28.getTemplatePartIcon)(
            view.slug === TEMPLATE_PART_ALL_AREAS_CATEGORY ? void 0 : view.slug
          ),
          label: view.title,
          id: view.slug,
          type: TEMPLATE_PART_POST_TYPE,
          isActive: currentCategory === view.slug && currentType === TEMPLATE_PART_POST_TYPE
        },
        view.slug
      )),
      /* @__PURE__ */ (0, import_jsx_runtime302.jsx)("div", { className: "edit-site-sidebar-navigation-screen-patterns__divider" }),
      patternViews?.map((view) => /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        CategoryItem,
        {
          count: patternCounts[view.slug],
          label: view.title,
          icon: file_default,
          id: view.slug,
          type: PATTERN_TYPES.user,
          isActive: currentCategory === `${view.slug}` && currentType === PATTERN_TYPES.user
        },
        view.slug
      ))
    ] });
  }
  function SidebarNavigationScreenPatterns({ backPath }) {
    const {
      query: { postType: postType2 = "wp_block", categoryId }
    } = useLocation23();
    const currentCategory = categoryId || (postType2 === PATTERN_TYPES.user ? PATTERN_DEFAULT_CATEGORY : TEMPLATE_PART_ALL_AREAS_CATEGORY);
    const { view_list: templatePartViews } = useViewConfig({
      kind: "postType",
      name: TEMPLATE_PART_POST_TYPE,
      fields: VIEW_CONFIG_FIELDS
    });
    const { view_list: patternViews } = useViewConfig({
      kind: "postType",
      name: PATTERN_TYPES.user,
      fields: VIEW_CONFIG_FIELDS
    });
    const { templatePartAreas, isLoading, hasTemplateParts } = useTemplatePartAreas();
    const templatePartCounts = (0, import_element174.useMemo)(() => {
      const counts = { [TEMPLATE_PART_ALL_AREAS_CATEGORY]: 0 };
      Object.entries(templatePartAreas).forEach(
        ([area, { templateParts }]) => {
          const count = templateParts?.length || 0;
          counts[area] = count;
          counts[TEMPLATE_PART_ALL_AREAS_CATEGORY] += count;
        }
      );
      return counts;
    }, [templatePartAreas]);
    const { patternCategories } = usePatternCategories();
    const patternCounts = (0, import_element174.useMemo)(() => {
      const counts = {};
      patternCategories.forEach((cat) => {
        counts[cat.name] = cat.count;
      });
      return counts;
    }, [patternCategories]);
    const hasPatterns = patternCounts[PATTERN_DEFAULT_CATEGORY] > 0;
    return /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
      SidebarNavigationScreen,
      {
        title: (0, import_i18n134.__)("Patterns"),
        description: (0, import_i18n134.__)(
          "Manage what patterns are available when editing the site."
        ),
        isRoot: !backPath,
        backPath,
        content: /* @__PURE__ */ (0, import_jsx_runtime302.jsxs)(import_jsx_runtime302.Fragment, { children: [
          isLoading && (0, import_i18n134.__)("Loading items\u2026"),
          !isLoading && /* @__PURE__ */ (0, import_jsx_runtime302.jsxs)(import_jsx_runtime302.Fragment, { children: [
            !hasTemplateParts && !hasPatterns && /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(import_components139.__experimentalItemGroup, { className: "edit-site-sidebar-navigation-screen-patterns__group", children: /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(import_components139.__experimentalItem, { children: (0, import_i18n134.__)("No items found") }) }),
            /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
              CategoriesGroup,
              {
                templatePartViews,
                patternViews,
                templatePartCounts,
                patternCounts,
                currentCategory,
                currentType: postType2
              }
            )
          ] })
        ] })
      }
    );
  }

  // packages/edit-site/build-module/components/page-patterns/index.mjs
  var import_i18n141 = __toESM(require_i18n(), 1);
  var import_element181 = __toESM(require_element(), 1);
  var import_block_editor26 = __toESM(require_block_editor(), 1);
  var import_core_data50 = __toESM(require_core_data(), 1);
  var import_editor32 = __toESM(require_editor(), 1);
  var import_router29 = __toESM(require_router(), 1);
  var import_data73 = __toESM(require_data(), 1);
  var import_url16 = __toESM(require_url(), 1);

  // packages/edit-site/build-module/components/page-patterns/use-pattern-settings.mjs
  var import_core_data46 = __toESM(require_core_data(), 1);
  var import_data69 = __toESM(require_data(), 1);
  var import_element175 = __toESM(require_element(), 1);
  var import_block_editor24 = __toESM(require_block_editor(), 1);
  var import_editor29 = __toESM(require_editor(), 1);
  var { useGlobalStyles: useGlobalStyles4 } = unlock(import_editor29.privateApis);
  var { globalStylesDataKey } = unlock(import_block_editor24.privateApis);
  function usePatternSettings() {
    const { merged: mergedConfig } = useGlobalStyles4();
    const storedSettings = (0, import_data69.useSelect)((select4) => {
      const { getSettings: getSettings7 } = unlock(select4(store));
      return getSettings7();
    }, []);
    const settingsBlockPatterns = storedSettings.__experimentalAdditionalBlockPatterns ?? // WP 6.0
    storedSettings.__experimentalBlockPatterns;
    const restBlockPatterns = (0, import_data69.useSelect)(
      (select4) => select4(import_core_data46.store).getBlockPatterns(),
      []
    );
    const blockPatterns = (0, import_element175.useMemo)(
      () => [
        ...settingsBlockPatterns || [],
        ...restBlockPatterns || []
      ].filter(filterOutDuplicatesByName),
      [settingsBlockPatterns, restBlockPatterns]
    );
    const [globalStyles, globalSettings] = (0, import_element175.useMemo)(() => {
      return generateGlobalStyles(mergedConfig, [], {
        disableRootPadding: false
      });
    }, [mergedConfig]);
    const settings2 = (0, import_element175.useMemo)(() => {
      const {
        __experimentalAdditionalBlockPatterns,
        styles,
        __experimentalFeatures,
        ...restStoredSettings
      } = storedSettings;
      const nonGlobalStyles = (styles ?? []).filter(
        (style) => !style.isGlobalStyles
      );
      return {
        ...restStoredSettings,
        styles: [...nonGlobalStyles, ...globalStyles],
        __experimentalFeatures: globalSettings,
        [globalStylesDataKey]: mergedConfig.styles ?? {},
        __experimentalBlockPatterns: blockPatterns,
        isPreviewMode: true
      };
    }, [
      storedSettings,
      blockPatterns,
      globalStyles,
      globalSettings,
      mergedConfig
    ]);
    return settings2;
  }

  // packages/edit-site/build-module/components/page-patterns/actions.mjs
  var import_components143 = __toESM(require_components(), 1);
  var import_i18n138 = __toESM(require_i18n(), 1);

  // packages/edit-site/build-module/components/add-new-pattern/index.mjs
  var import_components140 = __toESM(require_components(), 1);
  var import_element176 = __toESM(require_element(), 1);
  var import_i18n135 = __toESM(require_i18n(), 1);
  var import_data70 = __toESM(require_data(), 1);
  var import_router26 = __toESM(require_router(), 1);
  var import_patterns2 = __toESM(require_patterns(), 1);
  var import_notices6 = __toESM(require_notices(), 1);
  var import_core_data47 = __toESM(require_core_data(), 1);
  var import_editor30 = __toESM(require_editor(), 1);
  var import_jsx_runtime303 = __toESM(require_jsx_runtime(), 1);
  var { useHistory: useHistory17, useLocation: useLocation24 } = unlock(import_router26.privateApis);
  var { CreatePatternModal, useAddPatternCategory } = unlock(
    import_patterns2.privateApis
  );
  var { CreateTemplatePartModal } = unlock(import_editor30.privateApis);
  function AddNewPattern() {
    const history = useHistory17();
    const location = useLocation24();
    const [showPatternModal, setShowPatternModal] = (0, import_element176.useState)(false);
    const [showTemplatePartModal, setShowTemplatePartModal] = (0, import_element176.useState)(false);
    const { createPatternFromFile } = unlock((0, import_data70.useDispatch)(import_patterns2.store));
    const { createSuccessNotice, createErrorNotice } = (0, import_data70.useDispatch)(import_notices6.store);
    const patternUploadInputRef = (0, import_element176.useRef)();
    const {
      isBlockBasedTheme,
      addNewPatternLabel,
      addNewTemplatePartLabel,
      canCreatePattern,
      canCreateTemplatePart
    } = (0, import_data70.useSelect)((select4) => {
      const { getCurrentTheme, getPostType: getPostType2, canUser } = select4(import_core_data47.store);
      return {
        isBlockBasedTheme: getCurrentTheme()?.is_block_theme,
        addNewPatternLabel: getPostType2(PATTERN_TYPES.user)?.labels?.add_new_item,
        addNewTemplatePartLabel: getPostType2(TEMPLATE_PART_POST_TYPE)?.labels?.add_new_item,
        // Blocks refers to the wp_block post type, this checks the ability to create a post of that type.
        canCreatePattern: canUser("create", {
          kind: "postType",
          name: PATTERN_TYPES.user
        }),
        canCreateTemplatePart: canUser("create", {
          kind: "postType",
          name: TEMPLATE_PART_POST_TYPE
        })
      };
    }, []);
    function handleCreatePattern({ pattern }) {
      setShowPatternModal(false);
      history.navigate(
        `/${PATTERN_TYPES.user}/${pattern.id}?canvas=edit`
      );
    }
    function handleCreateTemplatePart(templatePart) {
      setShowTemplatePartModal(false);
      history.navigate(
        `/${TEMPLATE_PART_POST_TYPE}/${templatePart.id}?canvas=edit`
      );
    }
    function handleError() {
      setShowPatternModal(false);
      setShowTemplatePartModal(false);
    }
    const controls = [];
    if (canCreatePattern) {
      controls.push({
        icon: symbol_default,
        onClick: () => setShowPatternModal(true),
        title: addNewPatternLabel
      });
    }
    if (isBlockBasedTheme && canCreateTemplatePart) {
      controls.push({
        icon: symbol_filled_default,
        onClick: () => setShowTemplatePartModal(true),
        title: addNewTemplatePartLabel
      });
    }
    if (canCreatePattern) {
      controls.push({
        icon: upload_default,
        onClick: () => {
          patternUploadInputRef.current.click();
        },
        title: (0, import_i18n135.__)("Import pattern from JSON")
      });
    }
    const { categoryMap, findOrCreateTerm } = useAddPatternCategory();
    if (controls.length === 0) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime303.jsxs)(import_jsx_runtime303.Fragment, { children: [
      addNewPatternLabel && /* @__PURE__ */ (0, import_jsx_runtime303.jsx)(
        import_components140.DropdownMenu,
        {
          controls,
          icon: null,
          toggleProps: {
            variant: "primary",
            showTooltip: false,
            size: "compact",
            __next40pxDefaultSize: true
          },
          text: addNewPatternLabel,
          label: addNewPatternLabel
        }
      ),
      showPatternModal && /* @__PURE__ */ (0, import_jsx_runtime303.jsx)(
        CreatePatternModal,
        {
          onClose: () => setShowPatternModal(false),
          onSuccess: handleCreatePattern,
          onError: handleError
        }
      ),
      showTemplatePartModal && /* @__PURE__ */ (0, import_jsx_runtime303.jsx)(
        CreateTemplatePartModal,
        {
          closeModal: () => setShowTemplatePartModal(false),
          blocks: [],
          onCreate: handleCreateTemplatePart,
          onError: handleError
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime303.jsx)(
        "input",
        {
          type: "file",
          accept: ".json",
          hidden: true,
          ref: patternUploadInputRef,
          onChange: async (event) => {
            const file = event.target.files?.[0];
            if (!file) {
              return;
            }
            try {
              let currentCategoryId;
              if (location.query.postType !== TEMPLATE_PART_POST_TYPE) {
                const currentCategory = Array.from(
                  categoryMap.values()
                ).find(
                  (term) => term.name === location.query.categoryId
                );
                if (currentCategory) {
                  currentCategoryId = currentCategory.id || await findOrCreateTerm(
                    currentCategory.label
                  );
                }
              }
              const pattern = await createPatternFromFile(
                file,
                currentCategoryId ? [currentCategoryId] : void 0
              );
              if (!currentCategoryId && location.query.categoryId !== "my-patterns") {
                history.navigate(
                  `/pattern?categoryId=${PATTERN_DEFAULT_CATEGORY}`
                );
              }
              createSuccessNotice(
                (0, import_i18n135.sprintf)(
                  // translators: %s: The imported pattern's title.
                  (0, import_i18n135.__)('Imported "%s" from JSON.'),
                  pattern.title.raw
                ),
                {
                  type: "snackbar",
                  id: "import-pattern-success"
                }
              );
            } catch (err) {
              createErrorNotice(err.message, {
                type: "snackbar",
                id: "import-pattern-error"
              });
            } finally {
              event.target.value = "";
            }
          }
        }
      )
    ] });
  }

  // packages/edit-site/build-module/components/page-patterns/rename-category-menu-item.mjs
  var import_components141 = __toESM(require_components(), 1);
  var import_element177 = __toESM(require_element(), 1);
  var import_i18n136 = __toESM(require_i18n(), 1);
  var import_patterns3 = __toESM(require_patterns(), 1);
  var import_jsx_runtime304 = __toESM(require_jsx_runtime(), 1);
  var { RenamePatternCategoryModal } = unlock(import_patterns3.privateApis);
  function RenameCategoryMenuItem({ category, onClose }) {
    const [isModalOpen, setIsModalOpen] = (0, import_element177.useState)(false);
    return /* @__PURE__ */ (0, import_jsx_runtime304.jsxs)(import_jsx_runtime304.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(import_components141.MenuItem, { onClick: () => setIsModalOpen(true), children: (0, import_i18n136.__)("Rename") }),
      isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(
        RenameModal2,
        {
          category,
          onClose: () => {
            setIsModalOpen(false);
            onClose();
          }
        }
      )
    ] });
  }
  function RenameModal2({ category, onClose }) {
    const normalizedCategory = {
      id: category.id,
      slug: category.slug,
      name: category.label
    };
    const existingCategories = usePatternCategories();
    return /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(
      RenamePatternCategoryModal,
      {
        category: normalizedCategory,
        existingCategories,
        onClose,
        overlayClassName: "edit-site-list__rename-modal",
        focusOnMount: "firstContentElement",
        size: "small"
      }
    );
  }

  // packages/edit-site/build-module/components/page-patterns/delete-category-menu-item.mjs
  var import_components142 = __toESM(require_components(), 1);
  var import_core_data48 = __toESM(require_core_data(), 1);
  var import_data71 = __toESM(require_data(), 1);
  var import_element178 = __toESM(require_element(), 1);
  var import_html_entities8 = __toESM(require_html_entities(), 1);
  var import_i18n137 = __toESM(require_i18n(), 1);
  var import_notices7 = __toESM(require_notices(), 1);
  var import_router27 = __toESM(require_router(), 1);
  var import_jsx_runtime305 = __toESM(require_jsx_runtime(), 1);
  var { useHistory: useHistory18 } = unlock(import_router27.privateApis);
  function DeleteCategoryMenuItem({ category, onClose }) {
    const [isModalOpen, setIsModalOpen] = (0, import_element178.useState)(false);
    const history = useHistory18();
    const { createSuccessNotice, createErrorNotice } = (0, import_data71.useDispatch)(import_notices7.store);
    const { deleteEntityRecord, invalidateResolution } = (0, import_data71.useDispatch)(import_core_data48.store);
    const onDelete = async () => {
      try {
        await deleteEntityRecord(
          "taxonomy",
          "wp_pattern_category",
          category.id,
          { force: true },
          { throwOnError: true }
        );
        invalidateResolution("getUserPatternCategories");
        invalidateResolution("getEntityRecords", [
          "postType",
          PATTERN_TYPES.user,
          { per_page: -1 }
        ]);
        createSuccessNotice(
          (0, import_i18n137.sprintf)(
            /* translators: %s: The pattern category's name */
            (0, import_i18n137._x)('"%s" deleted.', "pattern category"),
            category.label
          ),
          { type: "snackbar", id: "pattern-category-delete" }
        );
        onClose?.();
        history.navigate(
          `/pattern?categoryId=${PATTERN_DEFAULT_CATEGORY}`
        );
      } catch (error2) {
        const errorMessage = error2.message && error2.code !== "unknown_error" ? error2.message : (0, import_i18n137.__)(
          "An error occurred while deleting the pattern category."
        );
        createErrorNotice(errorMessage, {
          type: "snackbar",
          id: "pattern-category-delete"
        });
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime305.jsxs)(import_jsx_runtime305.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime305.jsx)(import_components142.MenuItem, { isDestructive: true, onClick: () => setIsModalOpen(true), children: (0, import_i18n137.__)("Delete") }),
      /* @__PURE__ */ (0, import_jsx_runtime305.jsx)(
        import_components142.__experimentalConfirmDialog,
        {
          isOpen: isModalOpen,
          onConfirm: onDelete,
          onCancel: () => setIsModalOpen(false),
          confirmButtonText: (0, import_i18n137.__)("Delete"),
          className: "edit-site-patterns__delete-modal",
          title: (0, import_i18n137.sprintf)(
            // translators: %s: The pattern category's name.
            (0, import_i18n137._x)('Delete "%s"?', "pattern category"),
            (0, import_html_entities8.decodeEntities)(category.label)
          ),
          size: "medium",
          __experimentalHideHeader: false,
          children: (0, import_i18n137.sprintf)(
            // translators: %s: The pattern category's name.
            (0, import_i18n137.__)(
              'Are you sure you want to delete the category "%s"? The patterns will not be deleted.'
            ),
            (0, import_html_entities8.decodeEntities)(category.label)
          )
        }
      )
    ] });
  }

  // packages/edit-site/build-module/components/page-patterns/actions.mjs
  var import_jsx_runtime306 = __toESM(require_jsx_runtime(), 1);
  function PatternsActions({ categoryId, type }) {
    const { patternCategories } = usePatternCategories();
    let patternCategory;
    if (type === PATTERN_TYPES.user && !!categoryId) {
      patternCategory = patternCategories.find(
        (category) => category.name === categoryId
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime306.jsxs)(import_jsx_runtime306.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(AddNewPattern, {}),
      !!patternCategory?.id && /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(
        import_components143.DropdownMenu,
        {
          icon: more_vertical_default,
          label: (0, import_i18n138.__)("Actions"),
          toggleProps: {
            className: "edit-site-patterns__button",
            size: "compact"
          },
          children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime306.jsxs)(import_components143.MenuGroup, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(
              RenameCategoryMenuItem,
              {
                category: patternCategory,
                onClose
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(
              DeleteCategoryMenuItem,
              {
                category: patternCategory,
                onClose
              }
            )
          ] })
        }
      )
    ] });
  }

  // packages/edit-site/build-module/components/dataviews-actions/index.mjs
  var import_i18n139 = __toESM(require_i18n(), 1);
  var import_element179 = __toESM(require_element(), 1);
  var import_router28 = __toESM(require_router(), 1);
  var import_data72 = __toESM(require_data(), 1);
  var import_core_data49 = __toESM(require_core_data(), 1);
  var import_url15 = __toESM(require_url(), 1);
  var { useLocation: useLocation25, useHistory: useHistory19 } = unlock(import_router28.privateApis);
  var useSetActiveTemplateAction = () => {
    const activeTheme = (0, import_data72.useSelect)(
      (select4) => select4(import_core_data49.store).getCurrentTheme()
    );
    const { getEntityRecord } = (0, import_data72.useSelect)(import_core_data49.store);
    const { editEntityRecord, saveEditedEntityRecord } = (0, import_data72.useDispatch)(import_core_data49.store);
    return (0, import_element179.useMemo)(
      () => ({
        id: "set-active-template",
        label(items) {
          return items.some((item) => item._isActive) ? (0, import_i18n139.__)("Deactivate") : (0, import_i18n139.__)("Activate");
        },
        isPrimary: true,
        icon: pencil_default,
        isEligible(item) {
          if (item.theme !== activeTheme.stylesheet) {
            return false;
          }
          if (typeof item.id !== "number") {
            return item._isActive === false;
          }
          return true;
        },
        async callback(items) {
          const deactivate = items.some((item) => item._isActive);
          const activeTemplates = {
            ...await getEntityRecord("root", "site").active_templates ?? {}
          };
          for (const item of items) {
            if (deactivate) {
              delete activeTemplates[item.slug];
            } else {
              activeTemplates[item.slug] = item.id;
            }
          }
          await editEntityRecord("root", "site", void 0, {
            active_templates: activeTemplates
          });
          await saveEditedEntityRecord("root", "site");
        }
      }),
      [
        editEntityRecord,
        saveEditedEntityRecord,
        getEntityRecord,
        activeTheme
      ]
    );
  };
  var useEditPostAction = () => {
    const history = useHistory19();
    return (0, import_element179.useMemo)(
      () => ({
        id: "edit-post",
        label: (0, import_i18n139.__)("Edit"),
        icon: pencil_default,
        isEligible(post2) {
          if (post2.status === "trash") {
            return false;
          }
          return post2.type !== PATTERN_TYPES.theme;
        },
        callback(items) {
          const post2 = items[0];
          history.navigate(`/${post2.type}/${post2.id}?canvas=edit`);
        }
      }),
      [history]
    );
  };
  var useQuickEditPostAction = () => {
    const history = useHistory19();
    const { path, query } = useLocation25();
    return (0, import_element179.useMemo)(
      () => ({
        id: "quick-edit",
        label: (0, import_i18n139.__)("Quick Edit"),
        icon: drawer_right_default,
        isPrimary: true,
        supportsBulk: true,
        isEligible(post2) {
          if (post2.status === "trash") {
            return false;
          }
          return post2.type === "page";
        },
        callback(items) {
          history.navigate(
            (0, import_url15.addQueryArgs)(path, {
              ...query,
              quickEdit: true,
              postId: items.map((item) => item.id).join(",")
            })
          );
        }
      }),
      [history, path, query]
    );
  };

  // packages/edit-site/build-module/components/page-patterns/fields.mjs
  var import_i18n140 = __toESM(require_i18n(), 1);
  var import_element180 = __toESM(require_element(), 1);
  var import_block_editor25 = __toESM(require_block_editor(), 1);
  var import_blocks12 = __toESM(require_blocks(), 1);
  var import_editor31 = __toESM(require_editor(), 1);
  var import_jsx_runtime307 = __toESM(require_jsx_runtime(), 1);
  var { useStyle: useStyle4 } = unlock(import_editor31.privateApis);
  function PreviewField({ item }) {
    const descriptionId = (0, import_element180.useId)();
    const description = item.description || item?.excerpt?.raw;
    const isTemplatePart2 = item.type === TEMPLATE_PART_POST_TYPE;
    const backgroundColor = useStyle4("color.background");
    const blocks = (0, import_element180.useMemo)(() => {
      return item.blocks ?? (0, import_blocks12.parse)(item.content.raw, {
        __unstableSkipMigrationLogs: true
      });
    }, [item?.content?.raw, item.blocks]);
    const isEmpty2 = !blocks?.length;
    return /* @__PURE__ */ (0, import_jsx_runtime307.jsxs)(
      "div",
      {
        className: "page-patterns-preview-field",
        style: { backgroundColor },
        "aria-describedby": !!description ? descriptionId : void 0,
        children: [
          isEmpty2 && isTemplatePart2 && (0, import_i18n140.__)("Empty template part"),
          isEmpty2 && !isTemplatePart2 && (0, import_i18n140.__)("Empty pattern"),
          !isEmpty2 && /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(import_block_editor25.BlockPreview.Async, { children: /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(
            import_block_editor25.BlockPreview,
            {
              blocks,
              viewportWidth: item.viewportWidth
            }
          ) }),
          !!description && /* @__PURE__ */ (0, import_jsx_runtime307.jsx)("div", { hidden: true, id: descriptionId, children: description })
        ]
      }
    );
  }
  var previewField = {
    label: (0, import_i18n140.__)("Preview"),
    id: "preview",
    render: PreviewField,
    enableSorting: false
  };

  // packages/edit-site/build-module/components/page-patterns/index.mjs
  var import_jsx_runtime308 = __toESM(require_jsx_runtime(), 1);
  var { ExperimentalBlockEditorProvider } = unlock(import_block_editor26.privateApis);
  var { usePostActions, usePostFields } = unlock(import_editor32.privateApis);
  var { useLocation: useLocation26, useHistory: useHistory20 } = unlock(import_router29.privateApis);
  var EMPTY_ARRAY12 = [];
  var VIEW_CONFIG_FIELDS2 = ["default_view", "default_layouts"];
  function usePagePatternsHeader(type, categoryId) {
    const { patternCategories } = usePatternCategories();
    const templatePartAreas = (0, import_data73.useSelect)(
      (select4) => select4(import_core_data50.store).getCurrentTheme()?.default_template_part_areas || [],
      []
    );
    let title, description, patternCategory;
    if (type === TEMPLATE_PART_POST_TYPE) {
      const templatePartArea = templatePartAreas.find(
        (area) => area.area === categoryId
      );
      title = templatePartArea?.label || (0, import_i18n141.__)("All Template Parts");
      description = templatePartArea?.description || (0, import_i18n141.__)("Includes every template part defined for any area.");
    } else if (type === PATTERN_TYPES.user && !!categoryId) {
      patternCategory = patternCategories.find(
        (category) => category.name === categoryId
      );
      title = patternCategory?.label;
      description = patternCategory?.description;
    }
    return { title, description };
  }
  function DataviewsPatterns() {
    const { path, query } = useLocation26();
    const { postType: postType2 = "wp_block", categoryId: categoryIdFromURL } = query;
    const history = useHistory20();
    const categoryId = categoryIdFromURL || PATTERN_DEFAULT_CATEGORY;
    const { default_view: defaultView, default_layouts: defaultLayouts2 } = useViewConfig({
      kind: "postType",
      name: postType2,
      fields: VIEW_CONFIG_FIELDS2
    });
    const { view, updateView, isModified, resetToDefault } = useView({
      kind: "postType",
      name: postType2,
      slug: "default",
      defaultView,
      defaultLayouts: defaultLayouts2,
      queryParams: {
        page: query.pageNumber,
        search: query.search
      },
      onChangeQueryParams: (params) => {
        history.navigate(
          (0, import_url16.addQueryArgs)(path, {
            ...query,
            pageNumber: params.page,
            search: params.search
          })
        );
      }
    });
    const viewSyncStatus = view.filters?.find(
      ({ field }) => field === "sync-status"
    )?.value;
    const { patterns, isResolving } = use_patterns_default(postType2, categoryId, {
      search: view.search,
      syncStatus: viewSyncStatus
    });
    const postTypeFields = usePostFields({ postType: postType2 });
    const fields2 = (0, import_element181.useMemo)(() => {
      return [previewField, ...postTypeFields || []];
    }, [postTypeFields]);
    const { data, paginationInfo } = (0, import_element181.useMemo)(() => {
      const viewWithoutFilters = { ...view };
      delete viewWithoutFilters.search;
      if (postType2 !== TEMPLATE_PART_POST_TYPE) {
        viewWithoutFilters.filters = [];
      }
      return filterSortAndPaginate(patterns, viewWithoutFilters, fields2);
    }, [patterns, view, fields2, postType2]);
    const dataWithPermissions = useAugmentPatternsWithPermissions(data);
    const templatePartActions = usePostActions({
      postType: TEMPLATE_PART_POST_TYPE,
      context: "list"
    });
    const patternActions = usePostActions({
      postType: PATTERN_TYPES.user,
      context: "list"
    });
    const editAction = useEditPostAction();
    const actions = (0, import_element181.useMemo)(() => {
      if (postType2 === TEMPLATE_PART_POST_TYPE) {
        return [editAction, ...templatePartActions].filter(Boolean);
      }
      return [editAction, ...patternActions].filter(Boolean);
    }, [editAction, postType2, templatePartActions, patternActions]);
    const settings2 = usePatternSettings();
    const { title, description } = usePagePatternsHeader(
      postType2,
      categoryId
    );
    return /* @__PURE__ */ (0, import_jsx_runtime308.jsx)(ExperimentalBlockEditorProvider, { settings: settings2, children: /* @__PURE__ */ (0, import_jsx_runtime308.jsx)(
      page_default2,
      {
        className: "edit-site-page-patterns-dataviews",
        title,
        headingLevel: 2,
        subTitle: description,
        actions: /* @__PURE__ */ (0, import_jsx_runtime308.jsx)(
          PatternsActions,
          {
            categoryId,
            type: postType2
          }
        ),
        children: /* @__PURE__ */ (0, import_jsx_runtime308.jsx)(
          dataviews_default,
          {
            paginationInfo,
            fields: fields2,
            actions,
            data: dataWithPermissions || EMPTY_ARRAY12,
            getItemId: (item) => item.name ?? item.id,
            isLoading: isResolving,
            isItemClickable: (item) => item.type !== PATTERN_TYPES.theme,
            onClickItem: (item) => {
              history.navigate(
                `/${item.type}/${[
                  PATTERN_TYPES.user,
                  TEMPLATE_PART_POST_TYPE
                ].includes(item.type) ? item.id : item.name}?canvas=edit`
              );
            },
            view,
            onChangeView: updateView,
            defaultLayouts: defaultLayouts2,
            onReset: isModified ? resetToDefault : false
          },
          categoryId + postType2
        )
      }
    ) });
  }

  // packages/edit-site/build-module/components/site-editor-routes/patterns.mjs
  var import_jsx_runtime309 = __toESM(require_jsx_runtime(), 1);
  var patternsRoute = {
    name: "patterns",
    path: "/pattern",
    areas: {
      sidebar({ siteData }) {
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        const backPath = isBlockTheme || isClassicThemeWithStyleBookSupport(siteData) ? "/" : void 0;
        return /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(SidebarNavigationScreenPatterns, { backPath });
      },
      content: /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(DataviewsPatterns, {}),
      mobileSidebar({ siteData, query }) {
        if (query.categoryId) {
          return void 0;
        }
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        const backPath = isBlockTheme || isClassicThemeWithStyleBookSupport(siteData) ? "/" : void 0;
        return /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(SidebarNavigationScreenPatterns, { backPath });
      },
      mobileContent({ query }) {
        return query.categoryId ? /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(DataviewsPatterns, {}) : void 0;
      }
    }
  };

  // packages/edit-site/build-module/components/site-editor-routes/pattern-item.mjs
  var import_jsx_runtime310 = __toESM(require_jsx_runtime(), 1);
  var patternItemRoute = {
    name: "pattern-item",
    path: "/wp_block/:postId",
    areas: {
      sidebar({ siteData }) {
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        const backPath = isBlockTheme || isClassicThemeWithStyleBookSupport(siteData) ? "/" : void 0;
        return /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(SidebarNavigationScreenPatterns, { backPath });
      },
      // Also rendered on mobile, where this route is only reached at canvas=edit.
      preview: /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(EditSiteEditor, {})
    }
  };

  // packages/edit-site/build-module/components/site-editor-routes/template-part-item.mjs
  var import_jsx_runtime311 = __toESM(require_jsx_runtime(), 1);
  var templatePartItemRoute = {
    name: "template-part-item",
    path: "/wp_template_part/*postId",
    areas: {
      sidebar: /* @__PURE__ */ (0, import_jsx_runtime311.jsx)(SidebarNavigationScreenPatterns, { backPath: "/" }),
      // Also rendered on mobile, where this route is only reached at canvas=edit.
      preview: /* @__PURE__ */ (0, import_jsx_runtime311.jsx)(EditSiteEditor, {})
    }
  };

  // packages/edit-site/build-module/components/site-editor-routes/templates.mjs
  var import_data82 = __toESM(require_data(), 1);
  var import_core_data63 = __toESM(require_core_data(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-templates-browse/index.mjs
  var import_i18n143 = __toESM(require_i18n(), 1);

  // packages/edit-site/build-module/components/sidebar-navigation-screen-templates-browse/content.mjs
  var import_core_data52 = __toESM(require_core_data(), 1);
  var import_element182 = __toESM(require_element(), 1);
  var import_components144 = __toESM(require_components(), 1);
  var import_i18n142 = __toESM(require_i18n(), 1);
  var import_router30 = __toESM(require_router(), 1);
  var import_url17 = __toESM(require_url(), 1);

  // packages/edit-site/build-module/components/page-templates/hooks.mjs
  var import_core_data51 = __toESM(require_core_data(), 1);
  var import_data74 = __toESM(require_data(), 1);
  function useAddedBy(postType2, postId) {
    return (0, import_data74.useSelect)(
      (select4) => {
        const { getEntityRecord, getUser, getEditedEntityRecord } = select4(import_core_data51.store);
        const template = getEditedEntityRecord(
          "postType",
          postType2,
          postId
        );
        const originalSource = template?.original_source;
        const authorText = template?.author_text;
        switch (originalSource) {
          case "theme": {
            return {
              type: originalSource,
              icon: layout_default,
              text: authorText,
              isCustomized: template.source === TEMPLATE_ORIGINS.custom
            };
          }
          case "plugin": {
            return {
              type: originalSource,
              icon: plugins_default,
              text: authorText,
              isCustomized: template.source === TEMPLATE_ORIGINS.custom
            };
          }
          case "site": {
            const siteData = getEntityRecord(
              "root",
              "__unstableBase"
            );
            return {
              type: originalSource,
              icon: globe_default,
              imageUrl: siteData?.site_logo ? getEntityRecord(
                "postType",
                "attachment",
                siteData.site_logo
              )?.source_url : void 0,
              text: authorText,
              isCustomized: false
            };
          }
          default: {
            const user = getUser(template.author);
            return {
              type: "user",
              icon: comment_author_avatar_default,
              imageUrl: user?.avatar_urls?.[48],
              text: authorText ?? user?.name,
              isCustomized: false
            };
          }
        }
      },
      [postType2, postId]
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-templates-browse/content.mjs
  var import_jsx_runtime312 = __toESM(require_jsx_runtime(), 1);
  var { useLocation: useLocation27 } = unlock(import_router30.privateApis);
  var EMPTY_ARRAY13 = [];
  function TemplateDataviewItem({ template, isActive }) {
    const { text, icon } = useAddedBy(template.type, template.id);
    return /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
      SidebarNavigationItem,
      {
        to: (0, import_url17.addQueryArgs)("/template", { activeView: text }),
        icon,
        "aria-current": isActive,
        children: text
      }
    );
  }
  function DataviewsTemplatesSidebarContent() {
    const {
      query: { activeView = "active" }
    } = useLocation27();
    const { records } = (0, import_core_data52.useEntityRecords)("root", "registeredTemplate", {
      // This should not be needed, the endpoint returns all registered
      // templates, but it's not possible right now to turn off pagination for
      // entity configs.
      per_page: -1
    });
    const firstItemPerAuthorText = (0, import_element182.useMemo)(() => {
      const firstItemPerAuthor = records?.reduce((acc, template) => {
        const author = template.author_text;
        if (author && !acc[author]) {
          acc[author] = template;
        }
        return acc;
      }, {});
      return (firstItemPerAuthor && Object.values(firstItemPerAuthor)) ?? EMPTY_ARRAY13;
    }, [records]);
    return /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_components144.__experimentalItemGroup, { className: "edit-site-sidebar-navigation-screen-templates-browse", children: [
      /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
        SidebarNavigationItem,
        {
          to: "/template",
          icon: published_default,
          "aria-current": activeView === "active",
          children: (0, import_i18n142.__)("Active templates")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
        SidebarNavigationItem,
        {
          to: (0, import_url17.addQueryArgs)("/template", { activeView: "user" }),
          icon: comment_author_avatar_default,
          "aria-current": activeView === "user",
          // Let's avoid calling them "custom templates" to avoid
          // confusion. "Created" is closest to meaning database
          // templates, created by users.
          // https://developer.wordpress.org/themes/classic-themes/templates/page-template-files/#creating-custom-page-templates-for-global-use
          children: (0, import_i18n142.__)("Created templates")
        }
      ),
      firstItemPerAuthorText.map((template) => {
        return /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
          TemplateDataviewItem,
          {
            template,
            isActive: activeView === template.author_text
          },
          template.author_text
        );
      })
    ] });
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-templates-browse/content-legacy.mjs
  var import_core_data53 = __toESM(require_core_data(), 1);
  var import_data75 = __toESM(require_data(), 1);

  // packages/edit-site/build-module/components/sidebar-dataviews/index.mjs
  var import_components145 = __toESM(require_components(), 1);
  var import_router31 = __toESM(require_router(), 1);
  var import_url18 = __toESM(require_url(), 1);
  var import_jsx_runtime313 = __toESM(require_jsx_runtime(), 1);
  var { useLocation: useLocation28 } = unlock(import_router31.privateApis);
  var VIEW_CONFIG_FIELDS3 = ["view_list"];
  var SLUG_TO_ICON = {
    all: pages_default,
    published: published_default,
    future: scheduled_default,
    drafts: drafts_default,
    pending: pending_default,
    private: not_allowed_default,
    trash: trash_default
  };
  var defaultResolveIcon = (view) => {
    return SLUG_TO_ICON[view.slug];
  };
  function DataViewsSidebarContent({
    postType: postType2,
    resolveIcon = defaultResolveIcon
  }) {
    const {
      path,
      query: { activeView = "all" }
    } = useLocation28();
    const { view_list: viewList } = useViewConfig({
      kind: "postType",
      name: postType2,
      fields: VIEW_CONFIG_FIELDS3
    });
    if (!postType2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(import_jsx_runtime313.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(import_components145.__experimentalItemGroup, { className: "edit-site-sidebar-dataviews", children: viewList?.map((view) => {
      const isActive = view.slug === activeView;
      const slug = view.slug === "all" ? void 0 : view.slug;
      const icon = resolveIcon(view);
      return /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
        SidebarNavigationItem,
        {
          icon,
          to: (0, import_url18.addQueryArgs)(path, {
            activeView: slug
          }),
          "aria-current": isActive ? "true" : void 0,
          children: view.title
        },
        view.slug
      );
    }) }) });
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-templates-browse/content-legacy.mjs
  var import_jsx_runtime314 = __toESM(require_jsx_runtime(), 1);
  var SOURCE_TO_ICON = {
    user: comment_author_avatar_default,
    theme: layout_default,
    plugin: plugins_default,
    site: globe_default
  };
  function DataviewsTemplatesSidebarContent2() {
    const authorSourceMap = (0, import_data75.useSelect)((select4) => {
      const templates = select4(import_core_data53.store).getEntityRecords(
        "postType",
        TEMPLATE_POST_TYPE,
        { per_page: -1 }
      );
      if (!templates) {
        return {};
      }
      const map = {};
      for (const template of templates) {
        if (template.author_text && template.original_source && !map[template.author_text]) {
          map[template.author_text] = template.original_source;
        }
      }
      return map;
    }, []);
    const resolveIcon = (view) => {
      const source = authorSourceMap[view.slug];
      return SOURCE_TO_ICON[source] ?? layout_default;
    };
    return /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
      DataViewsSidebarContent,
      {
        postType: TEMPLATE_POST_TYPE,
        resolveIcon
      }
    );
  }

  // packages/edit-site/build-module/components/sidebar-navigation-screen-templates-browse/index.mjs
  var import_jsx_runtime315 = __toESM(require_jsx_runtime(), 1);
  function SidebarNavigationScreenTemplatesBrowse({ backPath }) {
    return /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
      SidebarNavigationScreen,
      {
        title: (0, import_i18n143.__)("Templates"),
        description: (0, import_i18n143.__)(
          "Create new templates, or reset any customizations made to the templates supplied by your theme."
        ),
        backPath,
        content: window?.__experimentalTemplateActivate ? /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(DataviewsTemplatesSidebarContent, {}) : /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(DataviewsTemplatesSidebarContent2, {})
      }
    );
  }

  // packages/edit-site/build-module/components/page-templates/index.mjs
  var import_i18n149 = __toESM(require_i18n(), 1);
  var import_html_entities13 = __toESM(require_html_entities(), 1);
  var import_element188 = __toESM(require_element(), 1);
  var import_core_data58 = __toESM(require_core_data(), 1);
  var import_router33 = __toESM(require_router(), 1);
  var import_editor36 = __toESM(require_editor(), 1);
  var import_url21 = __toESM(require_url(), 1);
  var import_data79 = __toESM(require_data(), 1);
  var import_compose31 = __toESM(require_compose(), 1);
  var import_components150 = __toESM(require_components(), 1);
  var import_notices9 = __toESM(require_notices(), 1);

  // packages/edit-site/build-module/components/add-new-template/index.mjs
  var import_components148 = __toESM(require_components(), 1);
  var import_html_entities11 = __toESM(require_html_entities(), 1);
  var import_element186 = __toESM(require_element(), 1);
  var import_data77 = __toESM(require_data(), 1);
  var import_core_data56 = __toESM(require_core_data(), 1);
  var import_compose30 = __toESM(require_compose(), 1);
  var import_i18n147 = __toESM(require_i18n(), 1);
  var import_notices8 = __toESM(require_notices(), 1);
  var import_router32 = __toESM(require_router(), 1);
  var import_dom26 = __toESM(require_dom(), 1);

  // packages/edit-site/build-module/components/add-new-template/add-custom-template-modal-content.mjs
  var import_element184 = __toESM(require_element(), 1);
  var import_i18n145 = __toESM(require_i18n(), 1);
  var import_components146 = __toESM(require_components(), 1);
  var import_core_data55 = __toESM(require_core_data(), 1);
  var import_html_entities10 = __toESM(require_html_entities(), 1);
  var import_compose29 = __toESM(require_compose(), 1);
  var import_dom25 = __toESM(require_dom(), 1);
  var import_url20 = __toESM(require_url(), 1);

  // packages/edit-site/build-module/components/add-new-template/utils.mjs
  var import_data76 = __toESM(require_data(), 1);
  var import_core_data54 = __toESM(require_core_data(), 1);
  var import_html_entities9 = __toESM(require_html_entities(), 1);
  var import_element183 = __toESM(require_element(), 1);
  var import_i18n144 = __toESM(require_i18n(), 1);
  var import_url19 = __toESM(require_url(), 1);
  var EMPTY_OBJECT2 = {};
  var getValueFromObjectPath2 = (object, path) => {
    let value = object;
    path.split(".").forEach((fieldName) => {
      value = value?.[fieldName];
    });
    return value;
  };
  function prefixSlug(prefix2, slug) {
    return `${prefix2}-${(0, import_url19.safeDecodeURI)(slug)}`;
  }
  var mapToIHasNameAndId = (entities, path) => {
    return (entities || []).map((entity) => ({
      ...entity,
      name: (0, import_html_entities9.decodeEntities)(getValueFromObjectPath2(entity, path))
    }));
  };
  var useExistingTemplates = () => {
    return (0, import_data76.useSelect)(
      (select4) => select4(import_core_data54.store).getEntityRecords(
        "postType",
        TEMPLATE_POST_TYPE,
        {
          per_page: -1
        }
      ),
      []
    );
  };
  var useDefaultTemplateTypes = () => {
    return (0, import_data76.useSelect)(
      (select4) => select4(import_core_data54.store).getCurrentTheme()?.default_template_types || [],
      []
    );
  };
  var usePublicPostTypes = () => {
    const postTypes = (0, import_data76.useSelect)(
      (select4) => select4(import_core_data54.store).getPostTypes({ per_page: -1 }),
      []
    );
    return (0, import_element183.useMemo)(() => {
      const excludedPostTypes = ["attachment"];
      return postTypes?.filter(
        ({ viewable, slug }) => viewable && !excludedPostTypes.includes(slug)
      ).sort((a2, b2) => {
        if (a2.slug === "post" || b2.slug === "post") {
          return 0;
        }
        return a2.name.localeCompare(b2.name);
      });
    }, [postTypes]);
  };
  var usePublicTaxonomies = () => {
    const taxonomies = (0, import_data76.useSelect)(
      (select4) => select4(import_core_data54.store).getTaxonomies({ per_page: -1 }),
      []
    );
    return (0, import_element183.useMemo)(() => {
      return taxonomies?.filter(
        ({ visibility }) => visibility?.publicly_queryable
      );
    }, [taxonomies]);
  };
  function usePostTypeArchiveMenuItems() {
    const publicPostTypes = usePublicPostTypes();
    const postTypesWithArchives = (0, import_element183.useMemo)(
      () => publicPostTypes?.filter((postType2) => postType2.has_archive),
      [publicPostTypes]
    );
    const existingTemplates = useExistingTemplates();
    const postTypeLabels = (0, import_element183.useMemo)(
      () => publicPostTypes?.reduce((accumulator, { labels }) => {
        const singularName = labels.singular_name.toLowerCase();
        accumulator[singularName] = (accumulator[singularName] || 0) + 1;
        return accumulator;
      }, {}),
      [publicPostTypes]
    );
    const needsUniqueIdentifier = (0, import_element183.useCallback)(
      ({ labels, slug }) => {
        const singularName = labels.singular_name.toLowerCase();
        return postTypeLabels[singularName] > 1 && singularName !== slug;
      },
      [postTypeLabels]
    );
    return (0, import_element183.useMemo)(
      () => postTypesWithArchives?.filter(
        (postType2) => !(existingTemplates || []).some(
          (existingTemplate) => existingTemplate.slug === "archive-" + postType2.slug
        )
      ).map((postType2) => {
        let title;
        if (needsUniqueIdentifier(postType2)) {
          title = (0, import_i18n144.sprintf)(
            // translators: %1s: Name of the post type e.g: "Post"; %2s: Slug of the post type e.g: "book".
            (0, import_i18n144.__)("Archive: %1$s (%2$s)"),
            postType2.labels.singular_name,
            postType2.slug
          );
        } else {
          title = (0, import_i18n144.sprintf)(
            // translators: %s: Name of the post type e.g: "Post".
            (0, import_i18n144.__)("Archive: %s"),
            postType2.labels.singular_name
          );
        }
        return {
          slug: "archive-" + postType2.slug,
          description: (0, import_i18n144.sprintf)(
            // translators: %s: Name of the post type e.g: "Post".
            (0, import_i18n144.__)(
              "Displays an archive with the latest posts of type: %s."
            ),
            postType2.labels.singular_name
          ),
          title,
          // `icon` is the `menu_icon` property of a post type. We
          // only handle `dashicons` for now, even if the `menu_icon`
          // also supports urls and svg as values.
          icon: typeof postType2.icon === "string" && postType2.icon.startsWith("dashicons-") ? postType2.icon.slice(10) : archive_default,
          templatePrefix: "archive"
        };
      }) || [],
      [postTypesWithArchives, existingTemplates, needsUniqueIdentifier]
    );
  }
  var usePostTypeMenuItems = (onClickMenuItem) => {
    const publicPostTypes = usePublicPostTypes();
    const defaultTemplateTypes = useDefaultTemplateTypes();
    const templateLabels = (0, import_element183.useMemo)(
      () => publicPostTypes?.reduce((accumulator, { labels }) => {
        const templateName = (labels.template_name || labels.singular_name).toLowerCase();
        accumulator[templateName] = (accumulator[templateName] || 0) + 1;
        return accumulator;
      }, {}),
      [publicPostTypes]
    );
    const needsUniqueIdentifier = (0, import_element183.useCallback)(
      ({ labels, slug }) => {
        const templateName = (labels.template_name || labels.singular_name).toLowerCase();
        return templateLabels[templateName] > 1 && templateName !== slug;
      },
      [templateLabels]
    );
    const templatePrefixes = (0, import_element183.useMemo)(
      () => publicPostTypes?.reduce((accumulator, { slug }) => {
        let suffix = slug;
        if (slug !== "page") {
          suffix = `single-${suffix}`;
        }
        accumulator[slug] = suffix;
        return accumulator;
      }, {}),
      [publicPostTypes]
    );
    const postTypesInfo = useEntitiesInfo("postType", templatePrefixes);
    const menuItems = (publicPostTypes || []).reduce(
      (accumulator, postType2) => {
        const { slug, labels, icon } = postType2;
        const generalTemplateSlug = templatePrefixes[slug];
        const defaultTemplateType = defaultTemplateTypes?.find(
          ({ slug: _slug }) => _slug === generalTemplateSlug
        );
        const _needsUniqueIdentifier = needsUniqueIdentifier(postType2);
        let menuItemTitle = labels.template_name || (0, import_i18n144.sprintf)(
          // translators: %s: Name of the post type e.g: "Post".
          (0, import_i18n144.__)("Single item: %s"),
          labels.singular_name
        );
        if (_needsUniqueIdentifier) {
          menuItemTitle = labels.template_name ? (0, import_i18n144.sprintf)(
            // translators: 1: Name of the template e.g: "Single Item: Post". 2: Slug of the post type e.g: "book".
            (0, import_i18n144._x)("%1$s (%2$s)", "post type menu label"),
            labels.template_name,
            slug
          ) : (0, import_i18n144.sprintf)(
            // translators: 1: Name of the post type e.g: "Post". 2: Slug of the post type e.g: "book".
            (0, import_i18n144._x)(
              "Single item: %1$s (%2$s)",
              "post type menu label"
            ),
            labels.singular_name,
            slug
          );
        }
        const menuItem = defaultTemplateType ? {
          ...defaultTemplateType,
          templatePrefix: templatePrefixes[slug]
        } : {
          slug: generalTemplateSlug,
          title: menuItemTitle,
          description: (0, import_i18n144.sprintf)(
            // translators: %s: Name of the post type e.g: "Post".
            (0, import_i18n144.__)("Displays a single item: %s."),
            labels.singular_name
          ),
          // `icon` is the `menu_icon` property of a post type. We
          // only handle `dashicons` for now, even if the `menu_icon`
          // also supports urls and svg as values.
          icon: typeof icon === "string" && icon.startsWith("dashicons-") ? icon.slice(10) : post_default,
          templatePrefix: templatePrefixes[slug]
        };
        const hasEntities = postTypesInfo?.[slug]?.hasEntities;
        if (hasEntities) {
          menuItem.onClick = (template) => {
            onClickMenuItem({
              type: "postType",
              slug,
              config: {
                recordNamePath: "title.rendered",
                queryArgs: ({ search }) => {
                  return {
                    _fields: "id,title,slug,link",
                    orderBy: search ? "relevance" : "modified",
                    exclude: postTypesInfo[slug].existingEntitiesIds
                  };
                },
                getSpecificTemplate: (suggestion) => {
                  const templateSlug = prefixSlug(
                    templatePrefixes[slug],
                    suggestion.slug
                  );
                  return {
                    title: templateSlug,
                    slug: templateSlug,
                    templatePrefix: templatePrefixes[slug]
                  };
                }
              },
              labels,
              template
            });
          };
        }
        if (hasEntities) {
          accumulator.push(menuItem);
        }
        return accumulator;
      },
      []
    );
    const postTypesMenuItems = (0, import_element183.useMemo)(
      () => menuItems.reduce(
        (accumulator, postType2) => {
          const { slug } = postType2;
          let key = "postTypesMenuItems";
          if (slug === "page") {
            key = "defaultPostTypesMenuItems";
          }
          accumulator[key].push(postType2);
          return accumulator;
        },
        { defaultPostTypesMenuItems: [], postTypesMenuItems: [] }
      ),
      [menuItems]
    );
    return postTypesMenuItems;
  };
  var useTaxonomiesMenuItems = (onClickMenuItem) => {
    const publicTaxonomies = usePublicTaxonomies();
    const existingTemplates = useExistingTemplates();
    const defaultTemplateTypes = useDefaultTemplateTypes();
    const templatePrefixes = (0, import_element183.useMemo)(
      () => publicTaxonomies?.reduce((accumulator, { slug }) => {
        let suffix = slug;
        if (!["category", "post_tag"].includes(slug)) {
          suffix = `taxonomy-${suffix}`;
        }
        if (slug === "post_tag") {
          suffix = `tag`;
        }
        accumulator[slug] = suffix;
        return accumulator;
      }, {}),
      [publicTaxonomies]
    );
    const taxonomyLabels = publicTaxonomies?.reduce(
      (accumulator, { labels }) => {
        const templateName = (labels.template_name || labels.singular_name).toLowerCase();
        accumulator[templateName] = (accumulator[templateName] || 0) + 1;
        return accumulator;
      },
      {}
    );
    const needsUniqueIdentifier = (labels, slug) => {
      if (["category", "post_tag"].includes(slug)) {
        return false;
      }
      const templateName = (labels.template_name || labels.singular_name).toLowerCase();
      return taxonomyLabels[templateName] > 1 && templateName !== slug;
    };
    const taxonomiesInfo = useEntitiesInfo("taxonomy", templatePrefixes);
    const existingTemplateSlugs = (existingTemplates || []).map(
      ({ slug }) => slug
    );
    const menuItems = (publicTaxonomies || []).reduce(
      (accumulator, taxonomy) => {
        const { slug, labels } = taxonomy;
        const generalTemplateSlug = templatePrefixes[slug];
        const defaultTemplateType = defaultTemplateTypes?.find(
          ({ slug: _slug }) => _slug === generalTemplateSlug
        );
        const hasGeneralTemplate = existingTemplateSlugs?.includes(generalTemplateSlug);
        const _needsUniqueIdentifier = needsUniqueIdentifier(
          labels,
          slug
        );
        let menuItemTitle = labels.template_name || labels.singular_name;
        if (_needsUniqueIdentifier) {
          menuItemTitle = labels.template_name ? (0, import_i18n144.sprintf)(
            // translators: 1: Name of the template e.g: "Products by Category". 2: Slug of the taxonomy e.g: "product_cat".
            (0, import_i18n144._x)("%1$s (%2$s)", "taxonomy template menu label"),
            labels.template_name,
            slug
          ) : (0, import_i18n144.sprintf)(
            // translators: 1: Name of the taxonomy e.g: "Category". 2: Slug of the taxonomy e.g: "product_cat".
            (0, import_i18n144._x)("%1$s (%2$s)", "taxonomy menu label"),
            labels.singular_name,
            slug
          );
        }
        const menuItem = defaultTemplateType ? {
          ...defaultTemplateType,
          templatePrefix: templatePrefixes[slug]
        } : {
          slug: generalTemplateSlug,
          title: menuItemTitle,
          description: (0, import_i18n144.sprintf)(
            // translators: %s: Name of the taxonomy e.g: "Product Categories".
            (0, import_i18n144.__)("Displays taxonomy: %s."),
            labels.singular_name
          ),
          icon: block_meta_default,
          templatePrefix: templatePrefixes[slug]
        };
        const hasEntities = taxonomiesInfo?.[slug]?.hasEntities;
        if (hasEntities) {
          menuItem.onClick = (template) => {
            onClickMenuItem({
              type: "taxonomy",
              slug,
              config: {
                queryArgs: ({ search }) => {
                  return {
                    _fields: "id,name,slug,link",
                    orderBy: search ? "name" : "count",
                    exclude: taxonomiesInfo[slug].existingEntitiesIds
                  };
                },
                getSpecificTemplate: (suggestion) => {
                  const templateSlug = prefixSlug(
                    templatePrefixes[slug],
                    suggestion.slug
                  );
                  return {
                    title: templateSlug,
                    slug: templateSlug,
                    templatePrefix: templatePrefixes[slug]
                  };
                }
              },
              labels,
              hasGeneralTemplate,
              template
            });
          };
        }
        if (!hasGeneralTemplate || hasEntities) {
          accumulator.push(menuItem);
        }
        return accumulator;
      },
      []
    );
    const taxonomiesMenuItems = (0, import_element183.useMemo)(
      () => menuItems.reduce(
        (accumulator, taxonomy) => {
          const { slug } = taxonomy;
          let key = "taxonomiesMenuItems";
          if (["category", "tag"].includes(slug)) {
            key = "defaultTaxonomiesMenuItems";
          }
          accumulator[key].push(taxonomy);
          return accumulator;
        },
        { defaultTaxonomiesMenuItems: [], taxonomiesMenuItems: [] }
      ),
      [menuItems]
    );
    return taxonomiesMenuItems;
  };
  var USE_AUTHOR_MENU_ITEM_TEMPLATE_PREFIX = { user: "author" };
  var USE_AUTHOR_MENU_ITEM_QUERY_PARAMETERS = { user: { who: "authors" } };
  function useAuthorMenuItem(onClickMenuItem) {
    const existingTemplates = useExistingTemplates();
    const defaultTemplateTypes = useDefaultTemplateTypes();
    const authorInfo = useEntitiesInfo(
      "root",
      USE_AUTHOR_MENU_ITEM_TEMPLATE_PREFIX,
      USE_AUTHOR_MENU_ITEM_QUERY_PARAMETERS
    );
    let authorMenuItem = defaultTemplateTypes?.find(
      ({ slug }) => slug === "author"
    );
    if (!authorMenuItem) {
      authorMenuItem = {
        description: (0, import_i18n144.__)(
          "Displays latest posts written by a single author."
        ),
        slug: "author",
        title: "Author"
      };
    }
    const hasGeneralTemplate = !!existingTemplates?.find(
      ({ slug }) => slug === "author"
    );
    if (authorInfo.user?.hasEntities) {
      authorMenuItem = { ...authorMenuItem, templatePrefix: "author" };
      authorMenuItem.onClick = (template) => {
        onClickMenuItem({
          type: "root",
          slug: "user",
          config: {
            queryArgs: ({ search }) => {
              return {
                _fields: "id,name,slug,link",
                orderBy: search ? "name" : "registered_date",
                exclude: authorInfo.user.existingEntitiesIds,
                who: "authors"
              };
            },
            getSpecificTemplate: (suggestion) => {
              const templateSlug = prefixSlug(
                "author",
                suggestion.slug
              );
              return {
                title: (0, import_i18n144.sprintf)(
                  // translators: %s: Name of the author e.g: "Admin".
                  (0, import_i18n144.__)("Author: %s"),
                  suggestion.name
                ),
                slug: templateSlug,
                templatePrefix: "author"
              };
            }
          },
          labels: {
            singular_name: (0, import_i18n144.__)("Author"),
            search_items: (0, import_i18n144.__)("Search Authors"),
            not_found: (0, import_i18n144.__)("No authors found."),
            all_items: (0, import_i18n144.__)("All Authors")
          },
          hasGeneralTemplate,
          template
        });
      };
    }
    if (!hasGeneralTemplate || authorInfo.user?.hasEntities) {
      return authorMenuItem;
    }
  }
  var useEntitiesInfo = (entityName, templatePrefixes, additionalQueryParameters = EMPTY_OBJECT2) => {
    const entitiesHasRecords = (0, import_data76.useSelect)(
      (select4) => {
        return Object.keys(templatePrefixes || {}).reduce(
          (accumulator, slug) => {
            const records = select4(import_core_data54.store).getEntityRecords(
              entityName,
              slug,
              {
                per_page: 1,
                _fields: "id",
                context: "view",
                ...additionalQueryParameters[slug]
              }
            );
            accumulator[slug] = records === null || records.length > 0;
            return accumulator;
          },
          {}
        );
      },
      [templatePrefixes, entityName, additionalQueryParameters]
    );
    const entitiesInfo = (0, import_element183.useMemo)(() => {
      return Object.keys(templatePrefixes || {}).reduce(
        (accumulator, slug) => {
          accumulator[slug] = {
            hasEntities: entitiesHasRecords[slug]
          };
          return accumulator;
        },
        {}
      );
    }, [templatePrefixes, entitiesHasRecords]);
    return entitiesInfo;
  };

  // packages/edit-site/build-module/components/add-new-template/add-custom-template-modal-content.mjs
  var import_jsx_runtime316 = __toESM(require_jsx_runtime(), 1);
  var EMPTY_ARRAY14 = [];
  function SuggestionListItem({
    suggestion,
    search,
    onSelect,
    entityForSuggestions
  }) {
    const baseCssClass = "edit-site-custom-template-modal__suggestions_list__list-item";
    return /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(
      import_components146.Composite.Item,
      {
        render: /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
          import_components146.Button,
          {
            __next40pxDefaultSize: true,
            role: "option",
            className: baseCssClass,
            onClick: () => onSelect(
              entityForSuggestions.config.getSpecificTemplate(
                suggestion
              )
            )
          }
        ),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
            import_components146.__experimentalText,
            {
              size: "body",
              lineHeight: 1.53846153846,
              weight: "var(--wpds-typography-font-weight-emphasis, 600)",
              className: `${baseCssClass}__title`,
              children: /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
                import_components146.TextHighlight,
                {
                  text: (0, import_html_entities10.decodeEntities)(suggestion.name),
                  highlight: search
                }
              )
            }
          ),
          suggestion.link && /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
            import_components146.__experimentalText,
            {
              size: "body",
              lineHeight: 1.53846153846,
              className: `${baseCssClass}__info`,
              children: (0, import_url20.safeDecodeURI)(suggestion.link)
            }
          )
        ]
      }
    );
  }
  function useSearchSuggestions(entityForSuggestions, search) {
    const { config: config2 } = entityForSuggestions;
    const query = (0, import_element184.useMemo)(
      () => ({
        order: "asc",
        context: "view",
        search,
        per_page: search ? 20 : 10,
        ...config2.queryArgs(search)
      }),
      [search, config2]
    );
    const { records: searchResults, hasResolved: searchHasResolved } = (0, import_core_data55.useEntityRecords)(
      entityForSuggestions.type,
      entityForSuggestions.slug,
      query
    );
    const [suggestions, setSuggestions] = (0, import_element184.useState)(EMPTY_ARRAY14);
    (0, import_element184.useEffect)(() => {
      if (!searchHasResolved) {
        return;
      }
      let newSuggestions = EMPTY_ARRAY14;
      if (searchResults?.length) {
        newSuggestions = searchResults;
        if (config2.recordNamePath) {
          newSuggestions = mapToIHasNameAndId(
            newSuggestions,
            config2.recordNamePath
          );
        }
      }
      setSuggestions(newSuggestions);
    }, [searchResults, searchHasResolved]);
    return suggestions;
  }
  function SuggestionList({ entityForSuggestions, onSelect }) {
    const [search, setSearch, debouncedSearch] = (0, import_compose29.useDebouncedInput)();
    const suggestions = useSearchSuggestions(
      entityForSuggestions,
      debouncedSearch
    );
    const { labels } = entityForSuggestions;
    const [showSearchControl, setShowSearchControl] = (0, import_element184.useState)(false);
    if (!showSearchControl && suggestions?.length > 9) {
      setShowSearchControl(true);
    }
    return /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(import_jsx_runtime316.Fragment, { children: [
      showSearchControl && /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
        import_components146.SearchControl,
        {
          onChange: setSearch,
          value: search,
          label: labels.search_items,
          placeholder: labels.search_items
        }
      ),
      !!suggestions?.length && /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
        import_components146.Composite,
        {
          orientation: "vertical",
          role: "listbox",
          className: "edit-site-custom-template-modal__suggestions_list",
          "aria-label": (0, import_i18n145.__)("Suggestions list"),
          children: suggestions.map((suggestion) => /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
            SuggestionListItem,
            {
              suggestion,
              search: debouncedSearch,
              onSelect,
              entityForSuggestions
            },
            suggestion.slug
          ))
        }
      ),
      debouncedSearch && !suggestions?.length && /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
        import_components146.__experimentalText,
        {
          as: "p",
          className: "edit-site-custom-template-modal__no-results",
          children: labels.not_found
        }
      )
    ] });
  }
  function AddCustomTemplateModalContent({
    onSelect,
    entityForSuggestions,
    onBack,
    containerRef
  }) {
    const [showSearchEntities, setShowSearchEntities] = (0, import_element184.useState)();
    (0, import_element184.useEffect)(() => {
      if (containerRef.current) {
        const [firstFocusable] = import_dom25.focus.focusable.find(
          containerRef.current
        );
        firstFocusable?.focus();
      }
    }, [showSearchEntities]);
    return /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(
      import_components146.__experimentalVStack,
      {
        spacing: 4,
        className: "edit-site-custom-template-modal__contents-wrapper",
        alignment: "left",
        children: [
          !showSearchEntities && /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(import_jsx_runtime316.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(import_components146.__experimentalText, { as: "p", children: (0, import_i18n145.__)(
              "Select whether to create a single template for all items or a specific one."
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(
              import_components146.Flex,
              {
                className: "edit-site-custom-template-modal__contents",
                gap: "4",
                align: "initial",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(
                    import_components146.FlexItem,
                    {
                      isBlock: true,
                      as: import_components146.Button,
                      onClick: () => {
                        const {
                          slug,
                          title,
                          description,
                          templatePrefix
                        } = entityForSuggestions.template;
                        onSelect({
                          slug,
                          title,
                          description,
                          templatePrefix
                        });
                      },
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
                          import_components146.__experimentalText,
                          {
                            as: "span",
                            weight: "var(--wpds-typography-font-weight-emphasis, 600)",
                            lineHeight: 1.53846153846,
                            children: entityForSuggestions.labels.all_items
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
                          import_components146.__experimentalText,
                          {
                            as: "span",
                            lineHeight: 1.53846153846,
                            // translators: The user is given the choice to set up a template for all items of a post type or taxonomy, or just a specific one.
                            children: (0, import_i18n145.__)("For all items")
                          }
                        )
                      ]
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(
                    import_components146.FlexItem,
                    {
                      isBlock: true,
                      as: import_components146.Button,
                      onClick: () => {
                        setShowSearchEntities(true);
                      },
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
                          import_components146.__experimentalText,
                          {
                            as: "span",
                            weight: "var(--wpds-typography-font-weight-emphasis, 600)",
                            lineHeight: 1.53846153846,
                            children: entityForSuggestions.labels.singular_name
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
                          import_components146.__experimentalText,
                          {
                            as: "span",
                            lineHeight: 1.53846153846,
                            // translators: The user is given the choice to set up a template for all items of a post type or taxonomy, or just a specific one.
                            children: (0, import_i18n145.__)("For a specific item")
                          }
                        )
                      ]
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(import_components146.Flex, { justify: "right", children: /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
              import_components146.Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: onBack,
                children: (0, import_i18n145.__)("Back")
              }
            ) })
          ] }),
          showSearchEntities && /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(import_jsx_runtime316.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(import_components146.__experimentalText, { as: "p", children: (0, import_i18n145.__)(
              "This template will be used only for the specific item chosen."
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
              SuggestionList,
              {
                entityForSuggestions,
                onSelect
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(import_components146.Flex, { justify: "right", children: /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
              import_components146.Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: () => {
                  if (entityForSuggestions.hasGeneralTemplate) {
                    onBack();
                  } else {
                    setShowSearchEntities(false);
                  }
                },
                children: (0, import_i18n145.__)("Back")
              }
            ) })
          ] })
        ]
      }
    );
  }
  var add_custom_template_modal_content_default = AddCustomTemplateModalContent;

  // packages/edit-site/build-module/components/add-new-template/add-custom-generic-template-modal-content.mjs
  var import_element185 = __toESM(require_element(), 1);
  var import_i18n146 = __toESM(require_i18n(), 1);
  var import_components147 = __toESM(require_components(), 1);
  var import_jsx_runtime317 = __toESM(require_jsx_runtime(), 1);
  function AddCustomGenericTemplateModalContent({ createTemplate, onBack }) {
    const [title, setTitle] = (0, import_element185.useState)("");
    const defaultTitle = (0, import_i18n146.__)("Custom Template");
    const [isBusy, setIsBusy] = (0, import_element185.useState)(false);
    const inputRef = (0, import_element185.useRef)();
    (0, import_element185.useEffect)(() => {
      if (inputRef.current) {
        inputRef.current.focus();
      }
    }, []);
    async function onCreateTemplate(event) {
      event.preventDefault();
      if (isBusy) {
        return;
      }
      setIsBusy(true);
      try {
        await createTemplate(
          {
            slug: paramCase(title || defaultTitle) || "wp-custom-template",
            title: title || defaultTitle
          },
          false
        );
      } finally {
        setIsBusy(false);
      }
    }
    return /* @__PURE__ */ (0, import_jsx_runtime317.jsx)("form", { onSubmit: onCreateTemplate, children: /* @__PURE__ */ (0, import_jsx_runtime317.jsxs)(import_components147.__experimentalVStack, { spacing: 6, children: [
      /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(
        import_components147.TextControl,
        {
          label: (0, import_i18n146.__)("Name"),
          value: title,
          onChange: setTitle,
          placeholder: defaultTitle,
          disabled: isBusy,
          ref: inputRef,
          help: (0, import_i18n146.__)(
            // eslint-disable-next-line no-restricted-syntax -- 'sidebar' is a common web design term for layouts
            'Describe the template, e.g. "Post with sidebar". A custom template can be manually applied to any post or page.'
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime317.jsxs)(
        import_components147.__experimentalHStack,
        {
          className: "edit-site-custom-generic-template__modal-actions",
          justify: "right",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(
              import_components147.Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: onBack,
                children: (0, import_i18n146.__)("Back")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(
              import_components147.Button,
              {
                __next40pxDefaultSize: true,
                variant: "primary",
                type: "submit",
                isBusy,
                "aria-disabled": isBusy,
                children: (0, import_i18n146.__)("Create")
              }
            )
          ]
        }
      )
    ] }) });
  }
  var add_custom_generic_template_modal_content_default = AddCustomGenericTemplateModalContent;

  // packages/edit-site/build-module/components/add-new-template/index.mjs
  var import_jsx_runtime318 = __toESM(require_jsx_runtime(), 1);
  var { useHistory: useHistory21 } = unlock(import_router32.privateApis);
  var DEFAULT_TEMPLATE_SLUGS = [
    "front-page",
    "home",
    "single",
    "page",
    "index",
    "archive",
    "author",
    "category",
    "date",
    "tag",
    "search",
    "404"
  ];
  var TEMPLATE_ICONS = {
    "front-page": home_default,
    home: verse_default,
    single: pin_default,
    page: page_default,
    archive: archive_default,
    search: search_default,
    404: not_found_default,
    index: list_default,
    category: category_default,
    author: comment_author_avatar_default,
    taxonomy: block_meta_default,
    date: calendar_default,
    tag: tag_default,
    attachment: media_default
  };
  function TemplateListItem({
    title,
    direction,
    className,
    description,
    icon,
    onClick,
    children
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
      import_components148.Button,
      {
        __next40pxDefaultSize: true,
        className,
        onClick,
        label: description,
        showTooltip: !!description,
        children: /* @__PURE__ */ (0, import_jsx_runtime318.jsxs)(
          import_components148.Flex,
          {
            as: "span",
            spacing: 2,
            align: "center",
            justify: "center",
            style: { width: "100%" },
            direction,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime318.jsx)("div", { className: "edit-site-add-new-template__template-icon", children: /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(import_components148.Icon, { icon }) }),
              /* @__PURE__ */ (0, import_jsx_runtime318.jsxs)(
                import_components148.__experimentalVStack,
                {
                  className: "edit-site-add-new-template__template-name",
                  alignment: "center",
                  spacing: 0,
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
                      import_components148.__experimentalText,
                      {
                        align: "center",
                        weight: "var(--wpds-typography-font-weight-emphasis, 600)",
                        lineHeight: 1.53846153846,
                        children: title
                      }
                    ),
                    children
                  ]
                }
              )
            ]
          }
        )
      }
    );
  }
  var modalContentMap = {
    templatesList: 1,
    customTemplate: 2,
    customGenericTemplate: 3
  };
  function NewTemplateModal({ onClose }) {
    const [modalContent, setModalContent] = (0, import_element186.useState)(
      modalContentMap.templatesList
    );
    const [entityForSuggestions, setEntityForSuggestions] = (0, import_element186.useState)({});
    const [isSubmitting, setIsSubmitting] = (0, import_element186.useState)(false);
    const missingTemplates = useMissingTemplates(
      setEntityForSuggestions,
      () => setModalContent(modalContentMap.customTemplate)
    );
    const history = useHistory21();
    const { saveEntityRecord } = (0, import_data77.useDispatch)(import_core_data56.store);
    const { createErrorNotice, createSuccessNotice } = (0, import_data77.useDispatch)(import_notices8.store);
    const containerRef = (0, import_element186.useRef)(null);
    const isMobile = (0, import_compose30.useViewportMatch)("medium", "<");
    const homeUrl = (0, import_data77.useSelect)((select4) => {
      return select4(import_core_data56.store).getEntityRecord("root", "__unstableBase")?.home;
    }, []);
    const TEMPLATE_SHORT_DESCRIPTIONS = {
      "front-page": homeUrl,
      date: (0, import_i18n147.sprintf)(
        // translators: %s: The homepage url.
        (0, import_i18n147.__)("E.g. %s"),
        homeUrl + "/" + (/* @__PURE__ */ new Date()).getFullYear()
      )
    };
    (0, import_element186.useEffect)(() => {
      if (containerRef.current && modalContent === modalContentMap.templatesList) {
        const [firstFocusable] = import_dom26.focus.focusable.find(
          containerRef.current
        );
        firstFocusable?.focus();
      }
    }, [modalContent]);
    async function createTemplate(template, isWPSuggestion = true) {
      if (isSubmitting) {
        return;
      }
      setIsSubmitting(true);
      try {
        const { title, description, slug } = template;
        const newTemplate = await saveEntityRecord(
          "postType",
          TEMPLATE_POST_TYPE,
          {
            description,
            // Slugs need to be strings, so this is for template `404`
            slug: slug.toString(),
            status: "publish",
            title,
            // This adds a post meta field in template that is part of `is_custom` value calculation.
            meta: {
              is_wp_suggestion: isWPSuggestion
            }
          },
          { throwOnError: true }
        );
        history.navigate(
          `/${TEMPLATE_POST_TYPE}/${newTemplate.id}?canvas=edit`
        );
        createSuccessNotice(
          (0, import_i18n147.sprintf)(
            // translators: %s: Title of the created post or template, e.g: "Hello world".
            (0, import_i18n147.__)('"%s" successfully created.'),
            (0, import_html_entities11.decodeEntities)(newTemplate.title?.rendered || title) || (0, import_i18n147.__)("(no title)")
          ),
          {
            type: "snackbar"
          }
        );
      } catch (error2) {
        const errorMessage = error2.message && error2.code !== "unknown_error" ? error2.message : (0, import_i18n147.__)("An error occurred while creating the template.");
        createErrorNotice(errorMessage, {
          type: "snackbar"
        });
      } finally {
        setIsSubmitting(false);
      }
    }
    const onModalClose = () => {
      onClose();
      setModalContent(modalContentMap.templatesList);
    };
    let modalTitle = (0, import_i18n147.__)("Add template");
    if (modalContent === modalContentMap.customTemplate) {
      modalTitle = (0, import_i18n147.sprintf)(
        // translators: %s: Name of the post type e.g: "Post".
        (0, import_i18n147.__)("Add template: %s"),
        entityForSuggestions.labels.singular_name
      );
    } else if (modalContent === modalContentMap.customGenericTemplate) {
      modalTitle = (0, import_i18n147.__)("Create custom template");
    }
    return /* @__PURE__ */ (0, import_jsx_runtime318.jsxs)(
      import_components148.Modal,
      {
        title: modalTitle,
        className: clsx_default("edit-site-add-new-template__modal", {
          "edit-site-add-new-template__modal_template_list": modalContent === modalContentMap.templatesList,
          "edit-site-custom-template-modal": modalContent === modalContentMap.customTemplate
        }),
        onRequestClose: onModalClose,
        overlayClassName: modalContent === modalContentMap.customGenericTemplate ? "edit-site-custom-generic-template__modal" : void 0,
        ref: containerRef,
        children: [
          modalContent === modalContentMap.templatesList && /* @__PURE__ */ (0, import_jsx_runtime318.jsxs)(
            import_components148.__experimentalGrid,
            {
              columns: isMobile ? 2 : 3,
              gap: 4,
              align: "flex-start",
              justify: "center",
              className: "edit-site-add-new-template__template-list__contents",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(import_components148.Flex, { className: "edit-site-add-new-template__template-list__prompt", children: (0, import_i18n147.__)(
                  "Select what the new template should apply to:"
                ) }),
                missingTemplates.map((template) => {
                  const { title, slug, onClick } = template;
                  return /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
                    TemplateListItem,
                    {
                      title,
                      direction: "column",
                      className: "edit-site-add-new-template__template-button",
                      description: TEMPLATE_SHORT_DESCRIPTIONS[slug],
                      icon: TEMPLATE_ICONS[slug] || layout_default,
                      onClick: () => onClick ? onClick(template) : createTemplate(template)
                    },
                    slug
                  );
                }),
                /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
                  TemplateListItem,
                  {
                    title: (0, import_i18n147.__)("Custom template"),
                    direction: "row",
                    className: "edit-site-add-new-template__custom-template-button",
                    icon: pencil_default,
                    onClick: () => setModalContent(
                      modalContentMap.customGenericTemplate
                    ),
                    children: /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
                      import_components148.__experimentalText,
                      {
                        lineHeight: 1.53846153846,
                        children: (0, import_i18n147.__)(
                          "A custom template can be manually applied to any post or page."
                        )
                      }
                    )
                  }
                )
              ]
            }
          ),
          modalContent === modalContentMap.customTemplate && /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
            add_custom_template_modal_content_default,
            {
              onSelect: createTemplate,
              entityForSuggestions,
              onBack: () => setModalContent(modalContentMap.templatesList),
              containerRef
            }
          ),
          modalContent === modalContentMap.customGenericTemplate && /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
            add_custom_generic_template_modal_content_default,
            {
              createTemplate,
              onBack: () => setModalContent(modalContentMap.templatesList)
            }
          )
        ]
      }
    );
  }
  function NewTemplate() {
    const [showModal, setShowModal] = (0, import_element186.useState)(false);
    const { postType: postType2 } = (0, import_data77.useSelect)((select4) => {
      const { getPostType: getPostType2 } = select4(import_core_data56.store);
      return {
        postType: getPostType2(TEMPLATE_POST_TYPE)
      };
    }, []);
    if (!postType2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime318.jsxs)(import_jsx_runtime318.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(
        import_components148.Button,
        {
          variant: "primary",
          onClick: () => setShowModal(true),
          label: postType2.labels.add_new_item,
          size: "compact",
          __next40pxDefaultSize: true,
          children: postType2.labels.add_new_item
        }
      ),
      showModal && /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(NewTemplateModal, { onClose: () => setShowModal(false) })
    ] });
  }
  function useMissingTemplates(setEntityForSuggestions, onClick) {
    const defaultTemplateTypes = useDefaultTemplateTypes();
    const missingDefaultTemplates = (defaultTemplateTypes || []).filter(
      (template) => DEFAULT_TEMPLATE_SLUGS.includes(template.slug)
    );
    const onClickMenuItem = (_entityForSuggestions) => {
      onClick?.();
      setEntityForSuggestions(_entityForSuggestions);
    };
    const enhancedMissingDefaultTemplateTypes = [...missingDefaultTemplates];
    const { defaultTaxonomiesMenuItems, taxonomiesMenuItems } = useTaxonomiesMenuItems(onClickMenuItem);
    const { defaultPostTypesMenuItems, postTypesMenuItems } = usePostTypeMenuItems(onClickMenuItem);
    const authorMenuItem = useAuthorMenuItem(onClickMenuItem);
    [
      ...defaultTaxonomiesMenuItems,
      ...defaultPostTypesMenuItems,
      authorMenuItem
    ].forEach((menuItem) => {
      if (!menuItem) {
        return;
      }
      const matchIndex = enhancedMissingDefaultTemplateTypes.findIndex(
        (template) => template.slug === menuItem.slug
      );
      if (matchIndex > -1) {
        enhancedMissingDefaultTemplateTypes[matchIndex] = menuItem;
      } else {
        enhancedMissingDefaultTemplateTypes.push(menuItem);
      }
    });
    enhancedMissingDefaultTemplateTypes?.sort((template1, template2) => {
      return DEFAULT_TEMPLATE_SLUGS.indexOf(template1.slug) - DEFAULT_TEMPLATE_SLUGS.indexOf(template2.slug);
    });
    const missingTemplates = [
      ...enhancedMissingDefaultTemplateTypes,
      ...usePostTypeArchiveMenuItems(),
      ...postTypesMenuItems,
      ...taxonomiesMenuItems
    ];
    return missingTemplates;
  }
  var add_new_template_default = (0, import_element186.memo)(NewTemplate);

  // packages/edit-site/build-module/components/page-templates/fields.mjs
  var import_components149 = __toESM(require_components(), 1);
  var import_i18n148 = __toESM(require_i18n(), 1);
  var import_element187 = __toESM(require_element(), 1);
  var import_html_entities12 = __toESM(require_html_entities(), 1);
  var import_blocks13 = __toESM(require_blocks(), 1);
  var import_block_editor27 = __toESM(require_block_editor(), 1);
  var import_editor35 = __toESM(require_editor(), 1);
  var import_core_data57 = __toESM(require_core_data(), 1);
  var import_data78 = __toESM(require_data(), 1);
  var import_jsx_runtime319 = __toESM(require_jsx_runtime(), 1);
  var { Badge: WCBadge4 } = unlock(import_components149.privateApis);
  var { useEntityRecordsWithPermissions } = unlock(import_core_data57.privateApis);
  var { useStyle: useStyle5 } = unlock(import_editor35.privateApis);
  function useAllDefaultTemplateTypes() {
    const defaultTemplateTypes = useDefaultTemplateTypes();
    const { records: staticRecords } = useEntityRecordsWithPermissions(
      "root",
      "registeredTemplate"
    );
    return [
      ...defaultTemplateTypes,
      ...staticRecords?.filter((record) => !record.is_custom).map((record) => {
        return {
          slug: record.slug,
          title: record.title.rendered,
          description: record.description
        };
      })
    ];
  }
  function PreviewField2({ item }) {
    const settings2 = usePatternSettings();
    const backgroundColor = useStyle5("color.background") ?? "white";
    const blocks = (0, import_element187.useMemo)(() => {
      return (0, import_blocks13.parse)(item.content.raw);
    }, [item.content.raw]);
    const isEmpty2 = !blocks?.length;
    return /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(import_editor35.EditorProvider, { post: item, settings: settings2, children: /* @__PURE__ */ (0, import_jsx_runtime319.jsxs)(
      "div",
      {
        className: "page-templates-preview-field",
        style: { backgroundColor },
        children: [
          isEmpty2 && (0, import_i18n148.__)("Empty template"),
          !isEmpty2 && /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(import_block_editor27.BlockPreview.Async, { children: /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(import_block_editor27.BlockPreview, { blocks }) })
        ]
      }
    ) });
  }
  var previewField2 = {
    label: (0, import_i18n148.__)("Preview"),
    id: "preview",
    render: PreviewField2,
    enableSorting: false
  };
  var descriptionField = {
    label: (0, import_i18n148.__)("Description"),
    id: "description",
    render: window?.__experimentalTemplateActivate ? function RenderDescription({ item }) {
      const defaultTemplateTypes = useAllDefaultTemplateTypes();
      const defaultTemplateType = defaultTemplateTypes.find(
        (type) => type.slug === item.slug
      );
      return item.description ? (0, import_html_entities12.decodeEntities)(item.description) : defaultTemplateType?.description;
    } : ({ item }) => {
      return item.description && (0, import_html_entities12.decodeEntities)(item.description);
    },
    enableSorting: false,
    enableGlobalSearch: true
  };
  function AuthorField({ item }) {
    const [isImageLoaded, setIsImageLoaded] = (0, import_element187.useState)(false);
    const { text, icon, imageUrl } = useAddedBy(item.type, item.id);
    return /* @__PURE__ */ (0, import_jsx_runtime319.jsxs)(import_components149.__experimentalHStack, { alignment: "left", spacing: 0, children: [
      imageUrl && /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(
        "div",
        {
          className: clsx_default("fields-controls__author-avatar", {
            "is-loaded": isImageLoaded
          }),
          children: /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(
            "img",
            {
              onLoad: () => setIsImageLoaded(true),
              alt: "",
              src: imageUrl
            }
          )
        }
      ),
      !imageUrl && /* @__PURE__ */ (0, import_jsx_runtime319.jsx)("div", { className: "fields-controls__author-icon", children: /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(import_components149.Icon, { icon }) }),
      /* @__PURE__ */ (0, import_jsx_runtime319.jsx)("span", { className: "fields-controls__author-name", children: text })
    ] });
  }
  var authorField = {
    label: (0, import_i18n148.__)("Author"),
    id: "author",
    getValue: ({ item }) => item.author_text ?? item.author,
    render: AuthorField
  };
  var activeField = {
    label: (0, import_i18n148.__)("Status"),
    id: "active",
    type: "boolean",
    getValue: ({ item }) => item._isActive,
    render: function Render({ item }) {
      const activeLabel = item._isCustom ? (0, import_i18n148._x)("Active when used", "template") : (0, import_i18n148._x)("Active", "template");
      const activeIntent = item._isCustom ? "info" : "success";
      const isActive = item._isActive;
      return /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(WCBadge4, { intent: isActive ? activeIntent : "default", children: isActive ? activeLabel : (0, import_i18n148._x)("Inactive", "template") });
    }
  };
  var useThemeField = () => {
    const activeTheme = (0, import_data78.useSelect)(
      (select4) => select4(import_core_data57.store).getCurrentTheme()
    );
    return (0, import_element187.useMemo)(
      () => ({
        label: (0, import_i18n148.__)("Compatible Theme"),
        id: "theme",
        getValue: ({ item }) => item.theme,
        render: function Render3({ item }) {
          if (item.theme === activeTheme.stylesheet) {
            return /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(WCBadge4, { intent: "success", children: item.theme });
          }
          return /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(WCBadge4, { intent: "error", children: item.theme });
        }
      }),
      [activeTheme]
    );
  };
  var slugField = {
    label: (0, import_i18n148.__)("Template Type"),
    id: "slug",
    getValue: ({ item }) => item.slug,
    render: function Render2({ item }) {
      const defaultTemplateTypes = useAllDefaultTemplateTypes();
      const defaultTemplateType = defaultTemplateTypes.find(
        (type) => type.slug === item.slug
      );
      return defaultTemplateType?.title || (0, import_i18n148._x)("Custom", "template type");
    }
  };

  // packages/edit-site/build-module/components/page-templates/view-utils.mjs
  var defaultLayouts = {
    table: {
      showMedia: false
    },
    grid: {
      showMedia: true
    },
    list: {
      showMedia: false
    }
  };
  var DEFAULT_VIEW = {
    type: "grid",
    perPage: 20,
    sort: {
      field: "title",
      direction: "asc"
    },
    titleField: "title",
    descriptionField: "description",
    mediaField: "preview",
    fields: ["author", "active", "slug", "theme"],
    filters: [],
    ...defaultLayouts.grid
  };
  function getActiveViewOverridesForTab(activeView) {
    if (activeView === "user") {
      return {
        sort: { field: "date", direction: "desc" }
      };
    }
    if (activeView === "active") {
      return {};
    }
    return {
      filters: [
        {
          field: "author",
          operator: "is",
          value: activeView,
          isLocked: true
        }
      ]
    };
  }

  // packages/edit-site/build-module/components/page-templates/index.mjs
  var import_jsx_runtime320 = __toESM(require_jsx_runtime(), 1);
  var { usePostActions: usePostActions2, usePostFields: usePostFields2, templateTitleField } = unlock(import_editor36.privateApis);
  var { useHistory: useHistory22, useLocation: useLocation29 } = unlock(import_router33.privateApis);
  var { useEntityRecordsWithPermissions: useEntityRecordsWithPermissions2 } = unlock(import_core_data58.privateApis);
  function PageTemplates() {
    const { path, query } = useLocation29();
    const { activeView = "active", postId } = query;
    const [selection, setSelection] = (0, import_element188.useState)([postId]);
    const [selectedRegisteredTemplate, setSelectedRegisteredTemplate] = (0, import_element188.useState)(false);
    const defaultView = DEFAULT_VIEW;
    const activeViewOverrides = (0, import_element188.useMemo)(
      () => getActiveViewOverridesForTab(activeView),
      [activeView]
    );
    const { view, updateView, isModified, resetToDefault } = useView({
      kind: "postType",
      name: TEMPLATE_POST_TYPE,
      slug: "default",
      defaultView,
      activeViewOverrides,
      queryParams: {
        page: query.pageNumber,
        search: query.search
      },
      onChangeQueryParams: (newQueryParams) => {
        history.navigate(
          (0, import_url21.addQueryArgs)(path, {
            ...query,
            pageNumber: newQueryParams.page,
            search: newQueryParams.search || void 0
          })
        );
      }
    });
    const { activeTemplatesOption, activeTheme, defaultTemplateTypes } = (0, import_data79.useSelect)((select4) => {
      const { getEntityRecord, getCurrentTheme } = select4(import_core_data58.store);
      return {
        activeTemplatesOption: getEntityRecord("root", "site")?.active_templates,
        activeTheme: getCurrentTheme(),
        defaultTemplateTypes: select4(import_core_data58.store).getCurrentTheme()?.default_template_types
      };
    });
    const { records: userRecords, isResolving: isLoadingUserRecords } = useEntityRecordsWithPermissions2("postType", TEMPLATE_POST_TYPE, {
      per_page: -1,
      combinedTemplates: false
    });
    const { records: staticRecords, isResolving: isLoadingStaticData } = useEntityRecordsWithPermissions2("root", "registeredTemplate", {
      // This should not be needed, the endpoint returns all registered
      // templates, but it's not possible right now to turn off pagination
      // for entity configs.
      per_page: -1
    });
    const activeTemplates = (0, import_element188.useMemo)(() => {
      const _active = [...staticRecords];
      if (activeTemplatesOption) {
        for (const activeSlug in activeTemplatesOption) {
          const activeId = activeTemplatesOption[activeSlug];
          const template = userRecords.find(
            (userRecord) => userRecord.id === activeId && userRecord.theme === activeTheme.stylesheet
          );
          if (template) {
            const index2 = _active.findIndex(
              ({ slug }) => slug === template.slug
            );
            if (index2 !== -1) {
              _active[index2] = template;
            } else {
              _active.push(template);
            }
          }
        }
      }
      return _active;
    }, [userRecords, staticRecords, activeTemplatesOption, activeTheme]);
    let isLoadingData;
    if (activeView === "active") {
      isLoadingData = isLoadingUserRecords || isLoadingStaticData;
    } else if (activeView === "user") {
      isLoadingData = isLoadingUserRecords;
    } else {
      isLoadingData = isLoadingStaticData;
    }
    const records = (0, import_element188.useMemo)(() => {
      function isCustom(record) {
        return record.is_custom ?? // For user templates it's custom if the is_wp_suggestion meta
        // field is not set and the slug is not found in the default
        // template types.
        (!record.meta?.is_wp_suggestion && !defaultTemplateTypes.some(
          (type) => type.slug === record.slug
        ));
      }
      let _records;
      if (activeView === "active") {
        _records = activeTemplates.filter(
          (record) => !isCustom(record)
        );
      } else if (activeView === "user") {
        _records = userRecords;
      } else {
        _records = staticRecords;
      }
      return _records.map((record) => ({
        ...record,
        _isActive: activeTemplates.some(
          (template) => template.id === record.id
        ),
        _isCustom: isCustom(record)
      }));
    }, [
      activeTemplates,
      defaultTemplateTypes,
      userRecords,
      staticRecords,
      activeView
    ]);
    const users = (0, import_data79.useSelect)(
      (select4) => {
        const { getUser } = select4(import_core_data58.store);
        return records.reduce((acc, record) => {
          if (record.author_text) {
            if (!acc[record.author_text]) {
              acc[record.author_text] = record.author_text;
            }
          } else if (record.author) {
            if (!acc[record.author]) {
              acc[record.author] = getUser(record.author);
            }
          }
          return acc;
        }, {});
      },
      [records]
    );
    const history = useHistory22();
    const onChangeSelection = (0, import_element188.useCallback)(
      (items) => {
        setSelection(items);
        if (view?.type === "list") {
          history.navigate(
            (0, import_url21.addQueryArgs)(path, {
              postId: items.length === 1 ? items[0] : void 0
            })
          );
        }
      },
      [history, path, view?.type]
    );
    const postTypeFields = usePostFields2({
      postType: TEMPLATE_POST_TYPE
    });
    const dateField = postTypeFields.find((field) => field.id === "date");
    const themeField = useThemeField();
    const fields2 = (0, import_element188.useMemo)(() => {
      const _fields = [
        previewField2,
        templateTitleField,
        descriptionField,
        activeField,
        slugField
      ];
      if (activeView === "user") {
        _fields.push(themeField);
        if (dateField) {
          _fields.push(dateField);
        }
      }
      const elements2 = [];
      for (const author in users) {
        elements2.push({
          value: users[author]?.id ?? author,
          label: users[author]?.name ?? author
        });
      }
      _fields.push({
        ...authorField,
        elements: elements2
      });
      return _fields;
    }, [users, activeView, themeField, dateField]);
    const { data, paginationInfo } = (0, import_element188.useMemo)(() => {
      return filterSortAndPaginate(records, view, fields2);
    }, [records, view, fields2]);
    const { createSuccessNotice } = (0, import_data79.useDispatch)(import_notices9.store);
    const onActionPerformed = (0, import_element188.useCallback)(
      (actionId, items) => {
        switch (actionId) {
          case "duplicate-post":
            {
              const newItem = items[0];
              const _title = typeof newItem.title === "string" ? newItem.title : newItem.title?.rendered;
              history.navigate(`/template?activeView=user`);
              createSuccessNotice(
                (0, import_i18n149.sprintf)(
                  // translators: %s: Title of the created post or template, e.g: "Hello world".
                  (0, import_i18n149.__)('"%s" successfully created.'),
                  (0, import_html_entities13.decodeEntities)(_title) || (0, import_i18n149.__)("(no title)")
                ),
                {
                  type: "snackbar",
                  id: "duplicate-post-action",
                  actions: [
                    {
                      label: (0, import_i18n149.__)("Edit"),
                      onClick: () => {
                        history.navigate(
                          `/${newItem.type}/${newItem.id}?canvas=edit`
                        );
                      }
                    }
                  ]
                }
              );
            }
            break;
        }
      },
      [history, createSuccessNotice]
    );
    const postTypeActions = usePostActions2({
      postType: TEMPLATE_POST_TYPE,
      context: "list",
      onActionPerformed
    });
    const editAction = useEditPostAction();
    const setActiveTemplateAction = useSetActiveTemplateAction();
    const actions = (0, import_element188.useMemo)(
      () => activeView === "user" ? [setActiveTemplateAction, editAction, ...postTypeActions] : [setActiveTemplateAction, ...postTypeActions],
      [postTypeActions, setActiveTemplateAction, editAction, activeView]
    );
    const onChangeView = (0, import_compose31.useEvent)((newView) => {
      updateView(newView);
      if (newView.type !== view.type) {
        history.invalidate();
      }
    });
    const duplicateAction = actions.find(
      (action) => action.id === "duplicate-post"
    );
    return /* @__PURE__ */ (0, import_jsx_runtime320.jsxs)(
      page_default2,
      {
        className: "edit-site-page-templates",
        title: (0, import_i18n149.__)("Templates"),
        headingLevel: 2,
        actions: /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(add_new_template_default, {}),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(
            dataviews_default,
            {
              paginationInfo,
              fields: fields2,
              actions,
              data,
              isLoading: isLoadingData,
              view,
              onChangeView,
              onChangeSelection,
              isItemClickable: () => true,
              onClickItem: (item) => {
                if (typeof item.id === "string") {
                  setSelectedRegisteredTemplate(item);
                } else {
                  history.navigate(
                    `/${item.type}/${item.id}?canvas=edit`
                  );
                }
              },
              selection,
              defaultLayouts,
              onReset: isModified ? () => {
                resetToDefault();
                history.invalidate();
              } : false
            },
            activeView
          ),
          selectedRegisteredTemplate && duplicateAction && /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(
            import_components150.Modal,
            {
              title: (0, import_i18n149.__)("Duplicate"),
              onRequestClose: () => setSelectedRegisteredTemplate(),
              size: "small",
              children: /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(
                duplicateAction.RenderModal,
                {
                  items: [selectedRegisteredTemplate],
                  closeModal: () => setSelectedRegisteredTemplate()
                }
              )
            }
          )
        ]
      }
    );
  }

  // packages/edit-site/build-module/components/page-templates/index-legacy.mjs
  var import_i18n154 = __toESM(require_i18n(), 1);
  var import_element193 = __toESM(require_element(), 1);
  var import_core_data62 = __toESM(require_core_data(), 1);
  var import_router35 = __toESM(require_router(), 1);
  var import_editor37 = __toESM(require_editor(), 1);
  var import_url24 = __toESM(require_url(), 1);
  var import_compose34 = __toESM(require_compose(), 1);

  // packages/edit-site/build-module/components/add-new-template-legacy/index.mjs
  var import_components153 = __toESM(require_components(), 1);
  var import_html_entities16 = __toESM(require_html_entities(), 1);
  var import_element192 = __toESM(require_element(), 1);
  var import_data81 = __toESM(require_data(), 1);
  var import_core_data61 = __toESM(require_core_data(), 1);
  var import_compose33 = __toESM(require_compose(), 1);
  var import_i18n153 = __toESM(require_i18n(), 1);
  var import_notices10 = __toESM(require_notices(), 1);
  var import_router34 = __toESM(require_router(), 1);
  var import_dom28 = __toESM(require_dom(), 1);

  // packages/edit-site/build-module/components/add-new-template-legacy/add-custom-template-modal-content.mjs
  var import_element190 = __toESM(require_element(), 1);
  var import_i18n151 = __toESM(require_i18n(), 1);
  var import_components151 = __toESM(require_components(), 1);
  var import_core_data60 = __toESM(require_core_data(), 1);
  var import_html_entities15 = __toESM(require_html_entities(), 1);
  var import_compose32 = __toESM(require_compose(), 1);
  var import_dom27 = __toESM(require_dom(), 1);
  var import_url23 = __toESM(require_url(), 1);

  // packages/edit-site/build-module/components/add-new-template-legacy/utils.mjs
  var import_data80 = __toESM(require_data(), 1);
  var import_core_data59 = __toESM(require_core_data(), 1);
  var import_html_entities14 = __toESM(require_html_entities(), 1);
  var import_element189 = __toESM(require_element(), 1);
  var import_i18n150 = __toESM(require_i18n(), 1);
  var import_url22 = __toESM(require_url(), 1);
  var EMPTY_OBJECT3 = {};
  var getValueFromObjectPath3 = (object, path) => {
    let value = object;
    path.split(".").forEach((fieldName) => {
      value = value?.[fieldName];
    });
    return value;
  };
  function prefixSlug2(prefix2, slug) {
    return `${prefix2}-${(0, import_url22.safeDecodeURI)(slug)}`;
  }
  var mapToIHasNameAndId2 = (entities, path) => {
    return (entities || []).map((entity) => ({
      ...entity,
      name: (0, import_html_entities14.decodeEntities)(getValueFromObjectPath3(entity, path))
    }));
  };
  var useExistingTemplates2 = () => {
    return (0, import_data80.useSelect)(
      (select4) => select4(import_core_data59.store).getEntityRecords(
        "postType",
        TEMPLATE_POST_TYPE,
        {
          per_page: -1
        }
      ),
      []
    );
  };
  var useDefaultTemplateTypes2 = () => {
    return (0, import_data80.useSelect)(
      (select4) => select4(import_core_data59.store).getCurrentTheme()?.default_template_types || [],
      []
    );
  };
  var usePublicPostTypes2 = () => {
    const postTypes = (0, import_data80.useSelect)(
      (select4) => select4(import_core_data59.store).getPostTypes({ per_page: -1 }),
      []
    );
    return (0, import_element189.useMemo)(() => {
      const excludedPostTypes = ["attachment"];
      return postTypes?.filter(
        ({ viewable, slug }) => viewable && !excludedPostTypes.includes(slug)
      ).sort((a2, b2) => {
        if (a2.slug === "post" || b2.slug === "post") {
          return 0;
        }
        return a2.name.localeCompare(b2.name);
      });
    }, [postTypes]);
  };
  var usePublicTaxonomies2 = () => {
    const taxonomies = (0, import_data80.useSelect)(
      (select4) => select4(import_core_data59.store).getTaxonomies({ per_page: -1 }),
      []
    );
    return (0, import_element189.useMemo)(() => {
      return taxonomies?.filter(
        ({ visibility }) => visibility?.publicly_queryable
      );
    }, [taxonomies]);
  };
  function usePostTypeArchiveMenuItems2() {
    const publicPostTypes = usePublicPostTypes2();
    const postTypesWithArchives = (0, import_element189.useMemo)(
      () => publicPostTypes?.filter((postType2) => postType2.has_archive),
      [publicPostTypes]
    );
    const existingTemplates = useExistingTemplates2();
    const postTypeLabels = (0, import_element189.useMemo)(
      () => publicPostTypes?.reduce((accumulator, { labels }) => {
        const singularName = labels.singular_name.toLowerCase();
        accumulator[singularName] = (accumulator[singularName] || 0) + 1;
        return accumulator;
      }, {}),
      [publicPostTypes]
    );
    const needsUniqueIdentifier = (0, import_element189.useCallback)(
      ({ labels, slug }) => {
        const singularName = labels.singular_name.toLowerCase();
        return postTypeLabels[singularName] > 1 && singularName !== slug;
      },
      [postTypeLabels]
    );
    return (0, import_element189.useMemo)(
      () => postTypesWithArchives?.filter(
        (postType2) => !(existingTemplates || []).some(
          (existingTemplate) => existingTemplate.slug === "archive-" + postType2.slug
        )
      ).map((postType2) => {
        let title;
        if (needsUniqueIdentifier(postType2)) {
          title = (0, import_i18n150.sprintf)(
            // translators: %1s: Name of the post type e.g: "Post"; %2s: Slug of the post type e.g: "book".
            (0, import_i18n150.__)("Archive: %1$s (%2$s)"),
            postType2.labels.singular_name,
            postType2.slug
          );
        } else {
          title = (0, import_i18n150.sprintf)(
            // translators: %s: Name of the post type e.g: "Post".
            (0, import_i18n150.__)("Archive: %s"),
            postType2.labels.singular_name
          );
        }
        return {
          slug: "archive-" + postType2.slug,
          description: (0, import_i18n150.sprintf)(
            // translators: %s: Name of the post type e.g: "Post".
            (0, import_i18n150.__)(
              "Displays an archive with the latest posts of type: %s."
            ),
            postType2.labels.singular_name
          ),
          title,
          // `icon` is the `menu_icon` property of a post type. We
          // only handle `dashicons` for now, even if the `menu_icon`
          // also supports urls and svg as values.
          icon: typeof postType2.icon === "string" && postType2.icon.startsWith("dashicons-") ? postType2.icon.slice(10) : archive_default,
          templatePrefix: "archive"
        };
      }) || [],
      [postTypesWithArchives, existingTemplates, needsUniqueIdentifier]
    );
  }
  var usePostTypeMenuItems2 = (onClickMenuItem) => {
    const publicPostTypes = usePublicPostTypes2();
    const existingTemplates = useExistingTemplates2();
    const defaultTemplateTypes = useDefaultTemplateTypes2();
    const templateLabels = (0, import_element189.useMemo)(
      () => publicPostTypes?.reduce((accumulator, { labels }) => {
        const templateName = (labels.template_name || labels.singular_name).toLowerCase();
        accumulator[templateName] = (accumulator[templateName] || 0) + 1;
        return accumulator;
      }, {}),
      [publicPostTypes]
    );
    const needsUniqueIdentifier = (0, import_element189.useCallback)(
      ({ labels, slug }) => {
        const templateName = (labels.template_name || labels.singular_name).toLowerCase();
        return templateLabels[templateName] > 1 && templateName !== slug;
      },
      [templateLabels]
    );
    const templatePrefixes = (0, import_element189.useMemo)(
      () => publicPostTypes?.reduce((accumulator, { slug }) => {
        let suffix = slug;
        if (slug !== "page") {
          suffix = `single-${suffix}`;
        }
        accumulator[slug] = suffix;
        return accumulator;
      }, {}),
      [publicPostTypes]
    );
    const postTypesInfo = useEntitiesInfo2("postType", templatePrefixes);
    const existingTemplateSlugs = (existingTemplates || []).map(
      ({ slug }) => slug
    );
    const menuItems = (publicPostTypes || []).reduce(
      (accumulator, postType2) => {
        const { slug, labels, icon } = postType2;
        const generalTemplateSlug = templatePrefixes[slug];
        const defaultTemplateType = defaultTemplateTypes?.find(
          ({ slug: _slug }) => _slug === generalTemplateSlug
        );
        const hasGeneralTemplate = existingTemplateSlugs?.includes(generalTemplateSlug);
        const _needsUniqueIdentifier = needsUniqueIdentifier(postType2);
        let menuItemTitle = labels.template_name || (0, import_i18n150.sprintf)(
          // translators: %s: Name of the post type e.g: "Post".
          (0, import_i18n150.__)("Single item: %s"),
          labels.singular_name
        );
        if (_needsUniqueIdentifier) {
          menuItemTitle = labels.template_name ? (0, import_i18n150.sprintf)(
            // translators: 1: Name of the template e.g: "Single Item: Post". 2: Slug of the post type e.g: "book".
            (0, import_i18n150._x)("%1$s (%2$s)", "post type menu label"),
            labels.template_name,
            slug
          ) : (0, import_i18n150.sprintf)(
            // translators: 1: Name of the post type e.g: "Post". 2: Slug of the post type e.g: "book".
            (0, import_i18n150._x)(
              "Single item: %1$s (%2$s)",
              "post type menu label"
            ),
            labels.singular_name,
            slug
          );
        }
        const menuItem = defaultTemplateType ? {
          ...defaultTemplateType,
          templatePrefix: templatePrefixes[slug]
        } : {
          slug: generalTemplateSlug,
          title: menuItemTitle,
          description: (0, import_i18n150.sprintf)(
            // translators: %s: Name of the post type e.g: "Post".
            (0, import_i18n150.__)("Displays a single item: %s."),
            labels.singular_name
          ),
          // `icon` is the `menu_icon` property of a post type. We
          // only handle `dashicons` for now, even if the `menu_icon`
          // also supports urls and svg as values.
          icon: typeof icon === "string" && icon.startsWith("dashicons-") ? icon.slice(10) : post_default,
          templatePrefix: templatePrefixes[slug]
        };
        const hasEntities = postTypesInfo?.[slug]?.hasEntities;
        if (hasEntities) {
          menuItem.onClick = (template) => {
            onClickMenuItem({
              type: "postType",
              slug,
              config: {
                recordNamePath: "title.rendered",
                queryArgs: ({ search }) => {
                  return {
                    _fields: "id,title,slug,link",
                    orderBy: search ? "relevance" : "modified",
                    exclude: postTypesInfo[slug].existingEntitiesIds
                  };
                },
                getSpecificTemplate: (suggestion) => {
                  const templateSlug = prefixSlug2(
                    templatePrefixes[slug],
                    suggestion.slug
                  );
                  return {
                    title: templateSlug,
                    slug: templateSlug,
                    templatePrefix: templatePrefixes[slug]
                  };
                }
              },
              labels,
              hasGeneralTemplate,
              template
            });
          };
        }
        if (!hasGeneralTemplate || hasEntities) {
          accumulator.push(menuItem);
        }
        return accumulator;
      },
      []
    );
    const postTypesMenuItems = (0, import_element189.useMemo)(
      () => menuItems.reduce(
        (accumulator, postType2) => {
          const { slug } = postType2;
          let key = "postTypesMenuItems";
          if (slug === "page") {
            key = "defaultPostTypesMenuItems";
          }
          accumulator[key].push(postType2);
          return accumulator;
        },
        { defaultPostTypesMenuItems: [], postTypesMenuItems: [] }
      ),
      [menuItems]
    );
    return postTypesMenuItems;
  };
  var useTaxonomiesMenuItems2 = (onClickMenuItem) => {
    const publicTaxonomies = usePublicTaxonomies2();
    const existingTemplates = useExistingTemplates2();
    const defaultTemplateTypes = useDefaultTemplateTypes2();
    const templatePrefixes = (0, import_element189.useMemo)(
      () => publicTaxonomies?.reduce((accumulator, { slug }) => {
        let suffix = slug;
        if (!["category", "post_tag"].includes(slug)) {
          suffix = `taxonomy-${suffix}`;
        }
        if (slug === "post_tag") {
          suffix = `tag`;
        }
        accumulator[slug] = suffix;
        return accumulator;
      }, {}),
      [publicTaxonomies]
    );
    const taxonomyLabels = publicTaxonomies?.reduce(
      (accumulator, { labels }) => {
        const templateName = (labels.template_name || labels.singular_name).toLowerCase();
        accumulator[templateName] = (accumulator[templateName] || 0) + 1;
        return accumulator;
      },
      {}
    );
    const needsUniqueIdentifier = (labels, slug) => {
      if (["category", "post_tag"].includes(slug)) {
        return false;
      }
      const templateName = (labels.template_name || labels.singular_name).toLowerCase();
      return taxonomyLabels[templateName] > 1 && templateName !== slug;
    };
    const taxonomiesInfo = useEntitiesInfo2("taxonomy", templatePrefixes);
    const existingTemplateSlugs = (existingTemplates || []).map(
      ({ slug }) => slug
    );
    const menuItems = (publicTaxonomies || []).reduce(
      (accumulator, taxonomy) => {
        const { slug, labels } = taxonomy;
        const generalTemplateSlug = templatePrefixes[slug];
        const defaultTemplateType = defaultTemplateTypes?.find(
          ({ slug: _slug }) => _slug === generalTemplateSlug
        );
        const hasGeneralTemplate = existingTemplateSlugs?.includes(generalTemplateSlug);
        const _needsUniqueIdentifier = needsUniqueIdentifier(
          labels,
          slug
        );
        let menuItemTitle = labels.template_name || labels.singular_name;
        if (_needsUniqueIdentifier) {
          menuItemTitle = labels.template_name ? (0, import_i18n150.sprintf)(
            // translators: 1: Name of the template e.g: "Products by Category". 2: Slug of the taxonomy e.g: "product_cat".
            (0, import_i18n150._x)("%1$s (%2$s)", "taxonomy template menu label"),
            labels.template_name,
            slug
          ) : (0, import_i18n150.sprintf)(
            // translators: 1: Name of the taxonomy e.g: "Category". 2: Slug of the taxonomy e.g: "product_cat".
            (0, import_i18n150._x)("%1$s (%2$s)", "taxonomy menu label"),
            labels.singular_name,
            slug
          );
        }
        const menuItem = defaultTemplateType ? {
          ...defaultTemplateType,
          templatePrefix: templatePrefixes[slug]
        } : {
          slug: generalTemplateSlug,
          title: menuItemTitle,
          description: (0, import_i18n150.sprintf)(
            // translators: %s: Name of the taxonomy e.g: "Product Categories".
            (0, import_i18n150.__)("Displays taxonomy: %s."),
            labels.singular_name
          ),
          icon: block_meta_default,
          templatePrefix: templatePrefixes[slug]
        };
        const hasEntities = taxonomiesInfo?.[slug]?.hasEntities;
        if (hasEntities) {
          menuItem.onClick = (template) => {
            onClickMenuItem({
              type: "taxonomy",
              slug,
              config: {
                queryArgs: ({ search }) => {
                  return {
                    _fields: "id,name,slug,link",
                    orderBy: search ? "name" : "count",
                    exclude: taxonomiesInfo[slug].existingEntitiesIds
                  };
                },
                getSpecificTemplate: (suggestion) => {
                  const templateSlug = prefixSlug2(
                    templatePrefixes[slug],
                    suggestion.slug
                  );
                  return {
                    title: templateSlug,
                    slug: templateSlug,
                    templatePrefix: templatePrefixes[slug]
                  };
                }
              },
              labels,
              hasGeneralTemplate,
              template
            });
          };
        }
        if (!hasGeneralTemplate || hasEntities) {
          accumulator.push(menuItem);
        }
        return accumulator;
      },
      []
    );
    const taxonomiesMenuItems = (0, import_element189.useMemo)(
      () => menuItems.reduce(
        (accumulator, taxonomy) => {
          const { slug } = taxonomy;
          let key = "taxonomiesMenuItems";
          if (["category", "tag"].includes(slug)) {
            key = "defaultTaxonomiesMenuItems";
          }
          accumulator[key].push(taxonomy);
          return accumulator;
        },
        { defaultTaxonomiesMenuItems: [], taxonomiesMenuItems: [] }
      ),
      [menuItems]
    );
    return taxonomiesMenuItems;
  };
  var USE_AUTHOR_MENU_ITEM_TEMPLATE_PREFIX2 = { user: "author" };
  var USE_AUTHOR_MENU_ITEM_QUERY_PARAMETERS2 = { user: { who: "authors" } };
  function useAuthorMenuItem2(onClickMenuItem) {
    const existingTemplates = useExistingTemplates2();
    const defaultTemplateTypes = useDefaultTemplateTypes2();
    const authorInfo = useEntitiesInfo2(
      "root",
      USE_AUTHOR_MENU_ITEM_TEMPLATE_PREFIX2,
      USE_AUTHOR_MENU_ITEM_QUERY_PARAMETERS2
    );
    let authorMenuItem = defaultTemplateTypes?.find(
      ({ slug }) => slug === "author"
    );
    if (!authorMenuItem) {
      authorMenuItem = {
        description: (0, import_i18n150.__)(
          "Displays latest posts written by a single author."
        ),
        slug: "author",
        title: "Author"
      };
    }
    const hasGeneralTemplate = !!existingTemplates?.find(
      ({ slug }) => slug === "author"
    );
    if (authorInfo.user?.hasEntities) {
      authorMenuItem = { ...authorMenuItem, templatePrefix: "author" };
      authorMenuItem.onClick = (template) => {
        onClickMenuItem({
          type: "root",
          slug: "user",
          config: {
            queryArgs: ({ search }) => {
              return {
                _fields: "id,name,slug,link",
                orderBy: search ? "name" : "registered_date",
                exclude: authorInfo.user.existingEntitiesIds,
                who: "authors"
              };
            },
            getSpecificTemplate: (suggestion) => {
              const templateSlug = prefixSlug2(
                "author",
                suggestion.slug
              );
              return {
                title: templateSlug,
                slug: templateSlug,
                templatePrefix: "author"
              };
            }
          },
          labels: {
            singular_name: (0, import_i18n150.__)("Author"),
            search_items: (0, import_i18n150.__)("Search Authors"),
            not_found: (0, import_i18n150.__)("No authors found."),
            all_items: (0, import_i18n150.__)("All Authors")
          },
          hasGeneralTemplate,
          template
        });
      };
    }
    if (!hasGeneralTemplate || authorInfo.user?.hasEntities) {
      return authorMenuItem;
    }
  }
  var useExistingTemplateSlugs = (templatePrefixes) => {
    const existingTemplates = useExistingTemplates2();
    const existingSlugs = (0, import_element189.useMemo)(() => {
      return Object.entries(templatePrefixes || {}).reduce(
        (accumulator, [slug, prefix2]) => {
          const slugsWithTemplates = (existingTemplates || []).reduce(
            (_accumulator, existingTemplate) => {
              const _prefix = `${prefix2}-`;
              if (existingTemplate.slug.startsWith(_prefix)) {
                _accumulator.push(
                  existingTemplate.slug.substring(
                    _prefix.length
                  )
                );
              }
              return _accumulator;
            },
            []
          );
          if (slugsWithTemplates.length) {
            accumulator[slug] = slugsWithTemplates;
          }
          return accumulator;
        },
        {}
      );
    }, [templatePrefixes, existingTemplates]);
    return existingSlugs;
  };
  var useTemplatesToExclude = (entityName, templatePrefixes, additionalQueryParameters = {}) => {
    const slugsToExcludePerEntity = useExistingTemplateSlugs(templatePrefixes);
    const recordsToExcludePerEntity = (0, import_data80.useSelect)(
      (select4) => {
        return Object.entries(slugsToExcludePerEntity || {}).reduce(
          (accumulator, [slug, slugsWithTemplates]) => {
            const entitiesWithTemplates = select4(
              import_core_data59.store
            ).getEntityRecords(entityName, slug, {
              _fields: "id",
              context: "view",
              slug: slugsWithTemplates,
              ...additionalQueryParameters[slug]
            });
            if (entitiesWithTemplates?.length) {
              accumulator[slug] = entitiesWithTemplates;
            }
            return accumulator;
          },
          {}
        );
      },
      [slugsToExcludePerEntity]
    );
    return recordsToExcludePerEntity;
  };
  var useEntitiesInfo2 = (entityName, templatePrefixes, additionalQueryParameters = EMPTY_OBJECT3) => {
    const recordsToExcludePerEntity = useTemplatesToExclude(
      entityName,
      templatePrefixes,
      additionalQueryParameters
    );
    const entitiesHasRecords = (0, import_data80.useSelect)(
      (select4) => {
        return Object.keys(templatePrefixes || {}).reduce(
          (accumulator, slug) => {
            const existingEntitiesIds = recordsToExcludePerEntity?.[slug]?.map(
              ({ id }) => id
            ) || [];
            const records = select4(import_core_data59.store).getEntityRecords(
              entityName,
              slug,
              {
                per_page: 1,
                _fields: "id",
                context: "view",
                exclude: existingEntitiesIds,
                ...additionalQueryParameters[slug]
              }
            );
            accumulator[slug] = records === null || records.length > 0;
            return accumulator;
          },
          {}
        );
      },
      [
        templatePrefixes,
        recordsToExcludePerEntity,
        entityName,
        additionalQueryParameters
      ]
    );
    const entitiesInfo = (0, import_element189.useMemo)(() => {
      return Object.keys(templatePrefixes || {}).reduce(
        (accumulator, slug) => {
          const existingEntitiesIds = recordsToExcludePerEntity?.[slug]?.map(
            ({ id }) => id
          ) || [];
          accumulator[slug] = {
            hasEntities: entitiesHasRecords[slug],
            existingEntitiesIds
          };
          return accumulator;
        },
        {}
      );
    }, [templatePrefixes, recordsToExcludePerEntity, entitiesHasRecords]);
    return entitiesInfo;
  };

  // packages/edit-site/build-module/components/add-new-template-legacy/add-custom-template-modal-content.mjs
  var import_jsx_runtime321 = __toESM(require_jsx_runtime(), 1);
  var EMPTY_ARRAY15 = [];
  function SuggestionListItem2({
    suggestion,
    search,
    onSelect,
    entityForSuggestions
  }) {
    const baseCssClass = "edit-site-custom-template-modal__suggestions_list__list-item";
    return /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(
      import_components151.Composite.Item,
      {
        render: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
          import_components151.Button,
          {
            __next40pxDefaultSize: true,
            role: "option",
            className: baseCssClass,
            onClick: () => onSelect(
              entityForSuggestions.config.getSpecificTemplate(
                suggestion
              )
            )
          }
        ),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
            import_components151.__experimentalText,
            {
              size: "body",
              lineHeight: 1.53846153846,
              weight: "var(--wpds-typography-font-weight-emphasis, 600)",
              className: `${baseCssClass}__title`,
              children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
                import_components151.TextHighlight,
                {
                  text: (0, import_html_entities15.decodeEntities)(suggestion.name),
                  highlight: search
                }
              )
            }
          ),
          suggestion.link && /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
            import_components151.__experimentalText,
            {
              size: "body",
              lineHeight: 1.53846153846,
              className: `${baseCssClass}__info`,
              children: (0, import_url23.safeDecodeURI)(suggestion.link)
            }
          )
        ]
      }
    );
  }
  function useSearchSuggestions2(entityForSuggestions, search) {
    const { config: config2 } = entityForSuggestions;
    const query = (0, import_element190.useMemo)(
      () => ({
        order: "asc",
        context: "view",
        search,
        per_page: search ? 20 : 10,
        ...config2.queryArgs(search)
      }),
      [search, config2]
    );
    const { records: searchResults, hasResolved: searchHasResolved } = (0, import_core_data60.useEntityRecords)(
      entityForSuggestions.type,
      entityForSuggestions.slug,
      query
    );
    const [suggestions, setSuggestions] = (0, import_element190.useState)(EMPTY_ARRAY15);
    (0, import_element190.useEffect)(() => {
      if (!searchHasResolved) {
        return;
      }
      let newSuggestions = EMPTY_ARRAY15;
      if (searchResults?.length) {
        newSuggestions = searchResults;
        if (config2.recordNamePath) {
          newSuggestions = mapToIHasNameAndId2(
            newSuggestions,
            config2.recordNamePath
          );
        }
      }
      setSuggestions(newSuggestions);
    }, [searchResults, searchHasResolved]);
    return suggestions;
  }
  function SuggestionList2({ entityForSuggestions, onSelect }) {
    const [search, setSearch, debouncedSearch] = (0, import_compose32.useDebouncedInput)();
    const suggestions = useSearchSuggestions2(
      entityForSuggestions,
      debouncedSearch
    );
    const { labels } = entityForSuggestions;
    const [showSearchControl, setShowSearchControl] = (0, import_element190.useState)(false);
    if (!showSearchControl && suggestions?.length > 9) {
      setShowSearchControl(true);
    }
    return /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(import_jsx_runtime321.Fragment, { children: [
      showSearchControl && /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
        import_components151.SearchControl,
        {
          onChange: setSearch,
          value: search,
          label: labels.search_items,
          placeholder: labels.search_items
        }
      ),
      !!suggestions?.length && /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
        import_components151.Composite,
        {
          orientation: "vertical",
          role: "listbox",
          className: "edit-site-custom-template-modal__suggestions_list",
          "aria-label": (0, import_i18n151.__)("Suggestions list"),
          children: suggestions.map((suggestion) => /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
            SuggestionListItem2,
            {
              suggestion,
              search: debouncedSearch,
              onSelect,
              entityForSuggestions
            },
            suggestion.slug
          ))
        }
      ),
      debouncedSearch && !suggestions?.length && /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
        import_components151.__experimentalText,
        {
          as: "p",
          className: "edit-site-custom-template-modal__no-results",
          children: labels.not_found
        }
      )
    ] });
  }
  function AddCustomTemplateModalContent2({
    onSelect,
    entityForSuggestions,
    onBack,
    containerRef
  }) {
    const [showSearchEntities, setShowSearchEntities] = (0, import_element190.useState)(
      entityForSuggestions.hasGeneralTemplate
    );
    (0, import_element190.useEffect)(() => {
      if (containerRef.current) {
        const [firstFocusable] = import_dom27.focus.focusable.find(
          containerRef.current
        );
        firstFocusable?.focus();
      }
    }, [showSearchEntities]);
    return /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(
      import_components151.__experimentalVStack,
      {
        spacing: 4,
        className: "edit-site-custom-template-modal__contents-wrapper",
        alignment: "left",
        children: [
          !showSearchEntities && /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(import_jsx_runtime321.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(import_components151.__experimentalText, { as: "p", children: (0, import_i18n151.__)(
              "Select whether to create a single template for all items or a specific one."
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(
              import_components151.Flex,
              {
                className: "edit-site-custom-template-modal__contents",
                gap: "4",
                align: "initial",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(
                    import_components151.FlexItem,
                    {
                      isBlock: true,
                      as: import_components151.Button,
                      onClick: () => {
                        const {
                          slug,
                          title,
                          description,
                          templatePrefix
                        } = entityForSuggestions.template;
                        onSelect({
                          slug,
                          title,
                          description,
                          templatePrefix
                        });
                      },
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
                          import_components151.__experimentalText,
                          {
                            as: "span",
                            weight: "var(--wpds-typography-font-weight-emphasis, 600)",
                            lineHeight: 1.53846153846,
                            children: entityForSuggestions.labels.all_items
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
                          import_components151.__experimentalText,
                          {
                            as: "span",
                            lineHeight: 1.53846153846,
                            // translators: The user is given the choice to set up a template for all items of a post type or taxonomy, or just a specific one.
                            children: (0, import_i18n151.__)("For all items")
                          }
                        )
                      ]
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(
                    import_components151.FlexItem,
                    {
                      isBlock: true,
                      as: import_components151.Button,
                      onClick: () => {
                        setShowSearchEntities(true);
                      },
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
                          import_components151.__experimentalText,
                          {
                            as: "span",
                            weight: "var(--wpds-typography-font-weight-emphasis, 600)",
                            lineHeight: 1.53846153846,
                            children: entityForSuggestions.labels.singular_name
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
                          import_components151.__experimentalText,
                          {
                            as: "span",
                            lineHeight: 1.53846153846,
                            // translators: The user is given the choice to set up a template for all items of a post type or taxonomy, or just a specific one.
                            children: (0, import_i18n151.__)("For a specific item")
                          }
                        )
                      ]
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(import_components151.Flex, { justify: "right", children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
              import_components151.Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: onBack,
                children: (0, import_i18n151.__)("Back")
              }
            ) })
          ] }),
          showSearchEntities && /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(import_jsx_runtime321.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(import_components151.__experimentalText, { as: "p", children: (0, import_i18n151.__)(
              "This template will be used only for the specific item chosen."
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
              SuggestionList2,
              {
                entityForSuggestions,
                onSelect
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(import_components151.Flex, { justify: "right", children: /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
              import_components151.Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: () => {
                  if (entityForSuggestions.hasGeneralTemplate) {
                    onBack();
                  } else {
                    setShowSearchEntities(false);
                  }
                },
                children: (0, import_i18n151.__)("Back")
              }
            ) })
          ] })
        ]
      }
    );
  }
  var add_custom_template_modal_content_default2 = AddCustomTemplateModalContent2;

  // packages/edit-site/build-module/components/add-new-template-legacy/add-custom-generic-template-modal-content.mjs
  var import_element191 = __toESM(require_element(), 1);
  var import_i18n152 = __toESM(require_i18n(), 1);
  var import_components152 = __toESM(require_components(), 1);
  var import_jsx_runtime322 = __toESM(require_jsx_runtime(), 1);
  function AddCustomGenericTemplateModalContent2({ createTemplate, onBack }) {
    const [title, setTitle] = (0, import_element191.useState)("");
    const defaultTitle = (0, import_i18n152.__)("Custom Template");
    const [isBusy, setIsBusy] = (0, import_element191.useState)(false);
    const inputRef = (0, import_element191.useRef)();
    (0, import_element191.useEffect)(() => {
      if (inputRef.current) {
        inputRef.current.focus();
      }
    }, []);
    async function onCreateTemplate(event) {
      event.preventDefault();
      if (isBusy) {
        return;
      }
      setIsBusy(true);
      try {
        await createTemplate(
          {
            slug: paramCase(title || defaultTitle) || "wp-custom-template",
            title: title || defaultTitle
          },
          false
        );
      } finally {
        setIsBusy(false);
      }
    }
    return /* @__PURE__ */ (0, import_jsx_runtime322.jsx)("form", { onSubmit: onCreateTemplate, children: /* @__PURE__ */ (0, import_jsx_runtime322.jsxs)(import_components152.__experimentalVStack, { spacing: 6, children: [
      /* @__PURE__ */ (0, import_jsx_runtime322.jsx)(
        import_components152.TextControl,
        {
          label: (0, import_i18n152.__)("Name"),
          value: title,
          onChange: setTitle,
          placeholder: defaultTitle,
          disabled: isBusy,
          ref: inputRef,
          help: (0, import_i18n152.__)(
            // eslint-disable-next-line no-restricted-syntax -- 'sidebar' is a common web design term for layouts
            'Describe the template, e.g. "Post with sidebar". A custom template can be manually applied to any post or page.'
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime322.jsxs)(
        import_components152.__experimentalHStack,
        {
          className: "edit-site-custom-generic-template__modal-actions",
          justify: "right",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime322.jsx)(
              import_components152.Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: onBack,
                children: (0, import_i18n152.__)("Back")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime322.jsx)(
              import_components152.Button,
              {
                __next40pxDefaultSize: true,
                variant: "primary",
                type: "submit",
                isBusy,
                "aria-disabled": isBusy,
                children: (0, import_i18n152.__)("Create")
              }
            )
          ]
        }
      )
    ] }) });
  }
  var add_custom_generic_template_modal_content_default2 = AddCustomGenericTemplateModalContent2;

  // packages/edit-site/build-module/components/add-new-template-legacy/index.mjs
  var import_jsx_runtime323 = __toESM(require_jsx_runtime(), 1);
  var { useHistory: useHistory23 } = unlock(import_router34.privateApis);
  var DEFAULT_TEMPLATE_SLUGS2 = [
    "front-page",
    "home",
    "single",
    "page",
    "index",
    "archive",
    "author",
    "category",
    "date",
    "tag",
    "search",
    "404"
  ];
  var TEMPLATE_ICONS2 = {
    "front-page": home_default,
    home: verse_default,
    single: pin_default,
    page: page_default,
    archive: archive_default,
    search: search_default,
    404: not_found_default,
    index: list_default,
    category: category_default,
    author: comment_author_avatar_default,
    taxonomy: block_meta_default,
    date: calendar_default,
    tag: tag_default,
    attachment: media_default
  };
  function TemplateListItem2({
    title,
    direction,
    className,
    description,
    icon,
    onClick,
    children
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
      import_components153.Button,
      {
        __next40pxDefaultSize: true,
        className,
        onClick,
        label: description,
        showTooltip: !!description,
        children: /* @__PURE__ */ (0, import_jsx_runtime323.jsxs)(
          import_components153.Flex,
          {
            as: "span",
            spacing: 2,
            align: "center",
            justify: "center",
            style: { width: "100%" },
            direction,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime323.jsx)("div", { className: "edit-site-add-new-template__template-icon", children: /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(import_components153.Icon, { icon }) }),
              /* @__PURE__ */ (0, import_jsx_runtime323.jsxs)(
                import_components153.__experimentalVStack,
                {
                  className: "edit-site-add-new-template__template-name",
                  alignment: "center",
                  spacing: 0,
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
                      import_components153.__experimentalText,
                      {
                        align: "center",
                        weight: "var(--wpds-typography-font-weight-emphasis, 600)",
                        lineHeight: 1.53846153846,
                        children: title
                      }
                    ),
                    children
                  ]
                }
              )
            ]
          }
        )
      }
    );
  }
  var modalContentMap2 = {
    templatesList: 1,
    customTemplate: 2,
    customGenericTemplate: 3
  };
  function NewTemplateModal2({ onClose }) {
    const [modalContent, setModalContent] = (0, import_element192.useState)(
      modalContentMap2.templatesList
    );
    const [entityForSuggestions, setEntityForSuggestions] = (0, import_element192.useState)({});
    const [isSubmitting, setIsSubmitting] = (0, import_element192.useState)(false);
    const missingTemplates = useMissingTemplates2(
      setEntityForSuggestions,
      () => setModalContent(modalContentMap2.customTemplate)
    );
    const history = useHistory23();
    const { saveEntityRecord } = (0, import_data81.useDispatch)(import_core_data61.store);
    const { createErrorNotice, createSuccessNotice } = (0, import_data81.useDispatch)(import_notices10.store);
    const containerRef = (0, import_element192.useRef)(null);
    const isMobile = (0, import_compose33.useViewportMatch)("medium", "<");
    const homeUrl = (0, import_data81.useSelect)((select4) => {
      return select4(import_core_data61.store).getEntityRecord("root", "__unstableBase")?.home;
    }, []);
    const TEMPLATE_SHORT_DESCRIPTIONS = {
      "front-page": homeUrl,
      date: (0, import_i18n153.sprintf)(
        // translators: %s: The homepage url.
        (0, import_i18n153.__)("E.g. %s"),
        homeUrl + "/" + (/* @__PURE__ */ new Date()).getFullYear()
      )
    };
    (0, import_element192.useEffect)(() => {
      if (containerRef.current && modalContent === modalContentMap2.templatesList) {
        const [firstFocusable] = import_dom28.focus.focusable.find(
          containerRef.current
        );
        firstFocusable?.focus();
      }
    }, [modalContent]);
    async function createTemplate(template, isWPSuggestion = true) {
      if (isSubmitting) {
        return;
      }
      setIsSubmitting(true);
      try {
        const { title, description, slug } = template;
        const newTemplate = await saveEntityRecord(
          "postType",
          TEMPLATE_POST_TYPE,
          {
            description,
            // Slugs need to be strings, so this is for template `404`
            slug: slug.toString(),
            status: "publish",
            title,
            // This adds a post meta field in template that is part of `is_custom` value calculation.
            is_wp_suggestion: isWPSuggestion
          },
          { throwOnError: true }
        );
        history.navigate(
          `/${TEMPLATE_POST_TYPE}/${newTemplate.id}?canvas=edit`
        );
        createSuccessNotice(
          (0, import_i18n153.sprintf)(
            // translators: %s: Title of the created post or template, e.g: "Hello world".
            (0, import_i18n153.__)('"%s" successfully created.'),
            (0, import_html_entities16.decodeEntities)(newTemplate.title?.rendered || title) || (0, import_i18n153.__)("(no title)")
          ),
          {
            type: "snackbar"
          }
        );
      } catch (error2) {
        const errorMessage = error2.message && error2.code !== "unknown_error" ? error2.message : (0, import_i18n153.__)("An error occurred while creating the template.");
        createErrorNotice(errorMessage, {
          type: "snackbar"
        });
      } finally {
        setIsSubmitting(false);
      }
    }
    const onModalClose = () => {
      onClose();
      setModalContent(modalContentMap2.templatesList);
    };
    let modalTitle = (0, import_i18n153.__)("Add template");
    if (modalContent === modalContentMap2.customTemplate) {
      modalTitle = (0, import_i18n153.sprintf)(
        // translators: %s: Name of the post type e.g: "Post".
        (0, import_i18n153.__)("Add template: %s"),
        entityForSuggestions.labels.singular_name
      );
    } else if (modalContent === modalContentMap2.customGenericTemplate) {
      modalTitle = (0, import_i18n153.__)("Create custom template");
    }
    return /* @__PURE__ */ (0, import_jsx_runtime323.jsxs)(
      import_components153.Modal,
      {
        title: modalTitle,
        className: clsx_default("edit-site-add-new-template__modal", {
          "edit-site-add-new-template__modal_template_list": modalContent === modalContentMap2.templatesList,
          "edit-site-custom-template-modal": modalContent === modalContentMap2.customTemplate
        }),
        onRequestClose: onModalClose,
        overlayClassName: modalContent === modalContentMap2.customGenericTemplate ? "edit-site-custom-generic-template__modal" : void 0,
        ref: containerRef,
        children: [
          modalContent === modalContentMap2.templatesList && /* @__PURE__ */ (0, import_jsx_runtime323.jsxs)(
            import_components153.__experimentalGrid,
            {
              columns: isMobile ? 2 : 3,
              gap: 4,
              align: "flex-start",
              justify: "center",
              className: "edit-site-add-new-template__template-list__contents",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(import_components153.Flex, { className: "edit-site-add-new-template__template-list__prompt", children: (0, import_i18n153.__)(
                  "Select what the new template should apply to:"
                ) }),
                missingTemplates.map((template) => {
                  const { title, slug, onClick } = template;
                  return /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
                    TemplateListItem2,
                    {
                      title,
                      direction: "column",
                      className: "edit-site-add-new-template__template-button",
                      description: TEMPLATE_SHORT_DESCRIPTIONS[slug],
                      icon: TEMPLATE_ICONS2[slug] || layout_default,
                      onClick: () => onClick ? onClick(template) : createTemplate(template)
                    },
                    slug
                  );
                }),
                /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
                  TemplateListItem2,
                  {
                    title: (0, import_i18n153.__)("Custom template"),
                    direction: "row",
                    className: "edit-site-add-new-template__custom-template-button",
                    icon: pencil_default,
                    onClick: () => setModalContent(
                      modalContentMap2.customGenericTemplate
                    ),
                    children: /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
                      import_components153.__experimentalText,
                      {
                        lineHeight: 1.53846153846,
                        children: (0, import_i18n153.__)(
                          "A custom template can be manually applied to any post or page."
                        )
                      }
                    )
                  }
                )
              ]
            }
          ),
          modalContent === modalContentMap2.customTemplate && /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
            add_custom_template_modal_content_default2,
            {
              onSelect: createTemplate,
              entityForSuggestions,
              onBack: () => setModalContent(modalContentMap2.templatesList),
              containerRef
            }
          ),
          modalContent === modalContentMap2.customGenericTemplate && /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
            add_custom_generic_template_modal_content_default2,
            {
              createTemplate,
              onBack: () => setModalContent(modalContentMap2.templatesList)
            }
          )
        ]
      }
    );
  }
  function NewTemplate2() {
    const [showModal, setShowModal] = (0, import_element192.useState)(false);
    const { postType: postType2 } = (0, import_data81.useSelect)((select4) => {
      const { getPostType: getPostType2 } = select4(import_core_data61.store);
      return {
        postType: getPostType2(TEMPLATE_POST_TYPE)
      };
    }, []);
    if (!postType2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime323.jsxs)(import_jsx_runtime323.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
        import_components153.Button,
        {
          variant: "primary",
          onClick: () => setShowModal(true),
          label: postType2.labels.add_new_item,
          size: "compact",
          __next40pxDefaultSize: true,
          children: postType2.labels.add_new_item
        }
      ),
      showModal && /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(NewTemplateModal2, { onClose: () => setShowModal(false) })
    ] });
  }
  function useMissingTemplates2(setEntityForSuggestions, onClick) {
    const existingTemplates = useExistingTemplates2();
    const defaultTemplateTypes = useDefaultTemplateTypes2();
    const existingTemplateSlugs = (existingTemplates || []).map(
      ({ slug }) => slug
    );
    const missingDefaultTemplates = (defaultTemplateTypes || []).filter(
      (template) => DEFAULT_TEMPLATE_SLUGS2.includes(template.slug) && !existingTemplateSlugs.includes(template.slug)
    );
    const onClickMenuItem = (_entityForSuggestions) => {
      onClick?.();
      setEntityForSuggestions(_entityForSuggestions);
    };
    const enhancedMissingDefaultTemplateTypes = [...missingDefaultTemplates];
    const { defaultTaxonomiesMenuItems, taxonomiesMenuItems } = useTaxonomiesMenuItems2(onClickMenuItem);
    const { defaultPostTypesMenuItems, postTypesMenuItems } = usePostTypeMenuItems2(onClickMenuItem);
    const authorMenuItem = useAuthorMenuItem2(onClickMenuItem);
    [
      ...defaultTaxonomiesMenuItems,
      ...defaultPostTypesMenuItems,
      authorMenuItem
    ].forEach((menuItem) => {
      if (!menuItem) {
        return;
      }
      const matchIndex = enhancedMissingDefaultTemplateTypes.findIndex(
        (template) => template.slug === menuItem.slug
      );
      if (matchIndex > -1) {
        enhancedMissingDefaultTemplateTypes[matchIndex] = menuItem;
      } else {
        enhancedMissingDefaultTemplateTypes.push(menuItem);
      }
    });
    enhancedMissingDefaultTemplateTypes?.sort((template1, template2) => {
      return DEFAULT_TEMPLATE_SLUGS2.indexOf(template1.slug) - DEFAULT_TEMPLATE_SLUGS2.indexOf(template2.slug);
    });
    const missingTemplates = [
      ...enhancedMissingDefaultTemplateTypes,
      ...usePostTypeArchiveMenuItems2(),
      ...postTypesMenuItems,
      ...taxonomiesMenuItems
    ];
    return missingTemplates;
  }
  var add_new_template_legacy_default = (0, import_element192.memo)(NewTemplate2);

  // packages/edit-site/build-module/components/page-templates/index-legacy.mjs
  var import_jsx_runtime324 = __toESM(require_jsx_runtime(), 1);
  var { usePostActions: usePostActions3, usePostFields: usePostFields3 } = unlock(import_editor37.privateApis);
  var { useHistory: useHistory24, useLocation: useLocation30 } = unlock(import_router35.privateApis);
  var { useEntityRecordsWithPermissions: useEntityRecordsWithPermissions3 } = unlock(import_core_data62.privateApis);
  var VIEW_CONFIG_FIELDS4 = ["default_view", "default_layouts", "view_list"];
  function PageTemplates2() {
    const { path, query } = useLocation30();
    const { activeView = "all", postId } = query;
    const [selection, setSelection] = (0, import_element193.useState)([postId]);
    const {
      default_view: defaultView,
      default_layouts: defaultLayouts2,
      view_list: viewList
    } = useViewConfig({
      kind: "postType",
      name: TEMPLATE_POST_TYPE,
      fields: VIEW_CONFIG_FIELDS4
    });
    const activeViewOverrides = (0, import_element193.useMemo)(
      () => viewList?.find((v2) => v2.slug === activeView)?.view ?? {},
      [viewList, activeView]
    );
    const { view, updateView, isModified, resetToDefault } = useView({
      kind: "postType",
      name: TEMPLATE_POST_TYPE,
      slug: "default",
      defaultView,
      activeViewOverrides,
      defaultLayouts: defaultLayouts2,
      queryParams: {
        page: query.pageNumber,
        search: query.search
      },
      onChangeQueryParams: (newQueryParams) => {
        history.navigate(
          (0, import_url24.addQueryArgs)(path, {
            ...query,
            pageNumber: newQueryParams.page,
            search: newQueryParams.search || void 0
          })
        );
      }
    });
    const { records, isResolving: isLoadingData } = useEntityRecordsWithPermissions3("postType", TEMPLATE_POST_TYPE, {
      per_page: -1
    });
    const history = useHistory24();
    const onChangeSelection = (0, import_element193.useCallback)(
      (items) => {
        setSelection(items);
        if (view?.type === "list") {
          history.navigate(
            (0, import_url24.addQueryArgs)(path, {
              postId: items.length === 1 ? items[0] : void 0
            })
          );
        }
      },
      [history, path, view?.type]
    );
    const postFields = usePostFields3({ postType: TEMPLATE_POST_TYPE });
    const fields2 = (0, import_element193.useMemo)(() => {
      return [previewField2, ...postFields || []];
    }, [postFields]);
    const { data, paginationInfo } = (0, import_element193.useMemo)(() => {
      return filterSortAndPaginate(records, view, fields2);
    }, [records, view, fields2]);
    const postTypeActions = usePostActions3({
      postType: TEMPLATE_POST_TYPE,
      context: "list"
    });
    const editAction = useEditPostAction();
    const actions = (0, import_element193.useMemo)(
      () => [editAction, ...postTypeActions],
      [postTypeActions, editAction]
    );
    const onChangeView = (0, import_compose34.useEvent)((newView) => {
      updateView(newView);
      if (newView.type !== view.type) {
        history.invalidate();
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
      page_default2,
      {
        className: "edit-site-page-templates",
        title: (0, import_i18n154.__)("Templates"),
        headingLevel: 2,
        actions: /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(add_new_template_legacy_default, {}),
        children: /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
          dataviews_default,
          {
            paginationInfo,
            fields: fields2,
            actions,
            data,
            isLoading: isLoadingData,
            view,
            onChangeView,
            onChangeSelection,
            isItemClickable: () => true,
            onClickItem: ({ id }) => {
              history.navigate(`/wp_template/${id}?canvas=edit`);
            },
            selection,
            defaultLayouts: defaultLayouts2,
            onReset: isModified ? () => {
              resetToDefault();
              history.invalidate();
            } : false
          },
          activeView
        )
      }
    );
  }

  // packages/edit-site/build-module/components/site-editor-routes/templates.mjs
  var import_jsx_runtime325 = __toESM(require_jsx_runtime(), 1);
  async function isTemplateListView(query) {
    const { activeView = "active" } = query;
    const config2 = await unlock((0, import_data82.resolveSelect)(import_core_data63.store)).getViewConfig(
      "postType",
      "wp_template"
    );
    const defaultView = config2?.default_view;
    const activeViewOverrides = config2?.view_list?.find((v2) => v2.slug === activeView)?.view ?? {};
    const view = await loadView({
      kind: "postType",
      name: "wp_template",
      slug: "default",
      defaultView,
      activeViewOverrides
    });
    return view.type === "list";
  }
  var templatesRoute = {
    name: "templates",
    path: "/template",
    areas: {
      sidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return null;
        }
        return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(SidebarNavigationScreenTemplatesBrowse, { backPath: "/" }) : /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(SidebarNavigationScreenUnsupported, {});
      },
      content({ siteData }) {
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        if (!isBlockTheme) {
          return void 0;
        }
        return window?.__experimentalTemplateActivate ? /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(PageTemplates, {}) : /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(PageTemplates2, {});
      },
      async preview({ query, siteData }) {
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        if (!isBlockTheme) {
          return void 0;
        }
        const isListView2 = await isTemplateListView(query);
        return isListView2 ? /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(EditSiteEditor, {}) : void 0;
      },
      mobileSidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(import_jsx_runtime325.Fragment, {});
        }
        if (!siteData.currentTheme.is_block_theme) {
          return /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(SidebarNavigationScreenUnsupported, {});
        }
        return void 0;
      },
      mobileContent({ siteData }) {
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        if (!isBlockTheme) {
          return void 0;
        }
        const isTemplateActivateEnabled = typeof window !== "undefined" && window.__experimentalTemplateActivate;
        return isTemplateActivateEnabled ? /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(PageTemplates, {}) : /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(PageTemplates2, {});
      }
    },
    widths: {
      async content({ query }) {
        const isListView2 = await isTemplateListView(query);
        return isListView2 ? 380 : void 0;
      }
    }
  };

  // packages/edit-site/build-module/components/site-editor-routes/template-item.mjs
  var import_jsx_runtime326 = __toESM(require_jsx_runtime(), 1);
  var areas = {
    sidebar({ siteData }) {
      if (!isThemeDataLoaded(siteData)) {
        return null;
      }
      return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(SidebarNavigationScreenTemplatesBrowse, { backPath: "/" }) : /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(SidebarNavigationScreenUnsupported, {});
    },
    // Also rendered on mobile, where this route is only reached at canvas=edit.
    preview({ siteData }) {
      if (!isThemeDataLoaded(siteData)) {
        return null;
      }
      return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(EditSiteEditor, {}) : /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(SidebarNavigationScreenUnsupported, {});
    }
  };
  var templateItemRoute = {
    name: "template-item",
    path: "/wp_template/*postId",
    areas
  };

  // packages/edit-site/build-module/components/site-editor-routes/pages.mjs
  var import_i18n157 = __toESM(require_i18n(), 1);
  var import_data86 = __toESM(require_data(), 1);
  var import_core_data68 = __toESM(require_core_data(), 1);

  // packages/edit-site/build-module/components/post-list/index.mjs
  var import_components156 = __toESM(require_components(), 1);
  var import_core_data67 = __toESM(require_core_data(), 1);
  var import_element197 = __toESM(require_element(), 1);
  var import_router36 = __toESM(require_router(), 1);
  var import_data85 = __toESM(require_data(), 1);
  var import_editor41 = __toESM(require_editor(), 1);
  var import_compose35 = __toESM(require_compose(), 1);
  var import_url25 = __toESM(require_url(), 1);

  // packages/edit-site/build-module/components/add-new-post/index.mjs
  var import_components154 = __toESM(require_components(), 1);
  var import_i18n155 = __toESM(require_i18n(), 1);
  var import_data83 = __toESM(require_data(), 1);
  var import_element194 = __toESM(require_element(), 1);
  var import_core_data64 = __toESM(require_core_data(), 1);
  var import_notices11 = __toESM(require_notices(), 1);
  var import_html_entities17 = __toESM(require_html_entities(), 1);
  var import_blocks14 = __toESM(require_blocks(), 1);
  var import_jsx_runtime327 = __toESM(require_jsx_runtime(), 1);
  function AddNewPostModal({ postType: postType2, onSave, onClose }) {
    const labels = (0, import_data83.useSelect)(
      (select4) => select4(import_core_data64.store).getPostType(postType2)?.labels,
      [postType2]
    );
    const [isCreatingPost, setIsCreatingPost] = (0, import_element194.useState)(false);
    const [title, setTitle] = (0, import_element194.useState)("");
    const { saveEntityRecord } = (0, import_data83.useDispatch)(import_core_data64.store);
    const { createErrorNotice, createSuccessNotice } = (0, import_data83.useDispatch)(import_notices11.store);
    const { resolveSelect: resolveSelect4 } = (0, import_data83.useRegistry)();
    async function createPost(event) {
      event.preventDefault();
      if (isCreatingPost) {
        return;
      }
      setIsCreatingPost(true);
      try {
        const postTypeObject = await resolveSelect4(import_core_data64.store).getPostType(postType2);
        const newPage = await saveEntityRecord(
          "postType",
          postType2,
          {
            status: "draft",
            title,
            slug: title ?? void 0,
            content: !!postTypeObject.template && postTypeObject.template.length ? (0, import_blocks14.serialize)(
              (0, import_blocks14.synchronizeBlocksWithTemplate)(
                [],
                postTypeObject.template
              )
            ) : void 0
          },
          { throwOnError: true }
        );
        onSave(newPage);
        createSuccessNotice(
          (0, import_i18n155.sprintf)(
            // translators: %s: Title of the created post or template, e.g: "Hello world".
            (0, import_i18n155.__)('"%s" successfully created.'),
            (0, import_html_entities17.decodeEntities)(newPage.title?.rendered || title) || (0, import_i18n155.__)("(no title)")
          ),
          { type: "snackbar" }
        );
      } catch (error2) {
        const errorMessage = error2.message && error2.code !== "unknown_error" ? error2.message : (0, import_i18n155.__)("An error occurred while creating the item.");
        createErrorNotice(errorMessage, {
          type: "snackbar"
        });
      } finally {
        setIsCreatingPost(false);
      }
    }
    return /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
      import_components154.Modal,
      {
        title: (
          // translators: %s: post type singular_name label e.g: "Page".
          (0, import_i18n155.sprintf)((0, import_i18n155.__)("Draft new: %s"), labels?.singular_name)
        ),
        onRequestClose: onClose,
        focusOnMount: "firstContentElement",
        size: "small",
        children: /* @__PURE__ */ (0, import_jsx_runtime327.jsx)("form", { onSubmit: createPost, children: /* @__PURE__ */ (0, import_jsx_runtime327.jsxs)(import_components154.__experimentalVStack, { spacing: 4, children: [
          /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
            import_components154.TextControl,
            {
              label: (0, import_i18n155.__)("Title"),
              onChange: setTitle,
              placeholder: (0, import_i18n155.__)("No title"),
              value: title
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime327.jsxs)(import_components154.__experimentalHStack, { spacing: 2, justify: "end", children: [
            /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
              import_components154.Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: onClose,
                children: (0, import_i18n155.__)("Cancel")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
              import_components154.Button,
              {
                __next40pxDefaultSize: true,
                variant: "primary",
                type: "submit",
                isBusy: isCreatingPost,
                "aria-disabled": isCreatingPost,
                children: (0, import_i18n155.__)("Create draft")
              }
            )
          ] })
        ] }) })
      }
    );
  }

  // packages/edit-site/build-module/components/post-list/use-notes-count.mjs
  var import_element195 = __toESM(require_element(), 1);
  var import_core_data65 = __toESM(require_core_data(), 1);
  function useNotesCount(postIds) {
    const { records: notes, isResolving } = (0, import_core_data65.useEntityRecords)(
      "root",
      "comment",
      {
        post: postIds,
        type: "note",
        status: "all",
        per_page: -1,
        _fields: "id,post"
      },
      {
        enabled: postIds?.length > 0
      }
    );
    const notesCount = (0, import_element195.useMemo)(() => {
      if (!notes || notes.length === 0) {
        return {};
      }
      const counts = {};
      notes.forEach((note) => {
        const postId = note.post;
        counts[postId] = (counts[postId] || 0) + 1;
      });
      return counts;
    }, [notes]);
    return { notesCount, isResolving };
  }

  // packages/edit-site/build-module/components/post-list/quick-edit-modal.mjs
  var import_i18n156 = __toESM(require_i18n(), 1);
  var import_data84 = __toESM(require_data(), 1);
  var import_core_data66 = __toESM(require_core_data(), 1);
  var import_components155 = __toESM(require_components(), 1);
  var import_element196 = __toESM(require_element(), 1);
  var import_editor40 = __toESM(require_editor(), 1);
  var import_jsx_runtime328 = __toESM(require_jsx_runtime(), 1);
  var { usePostFields: usePostFields4, PostCardPanel } = unlock(import_editor40.privateApis);
  var fieldsWithBulkEditSupport = ["status", "date", "author", "discussion"];
  function QuickEditModal({
    postType: postType2,
    postId,
    closeModal,
    quickEditForm
  }) {
    const isBulk = postId.length > 1;
    const [localEdits, setLocalEdits] = (0, import_element196.useState)({});
    const { record, hasFinishedResolution, canSwitchTemplate } = (0, import_data84.useSelect)(
      (select4) => {
        const {
          getEditedEntityRecord,
          hasFinishedResolution: hasFinished
        } = select4(import_core_data66.store);
        if (isBulk) {
          return {
            record: null,
            hasFinishedResolution: true
          };
        }
        const args = ["postType", postType2, postId[0]];
        const { getHomePage, getPostsPageId } = unlock(
          select4(import_core_data66.store)
        );
        const singlePostId = String(postId[0]);
        const isPostsPage = singlePostId !== void 0 && getPostsPageId() === singlePostId;
        const isFrontPage = singlePostId !== void 0 && postType2 === "page" && getHomePage()?.postId === singlePostId;
        return {
          record: getEditedEntityRecord(...args),
          hasFinishedResolution: hasFinished(
            "getEditedEntityRecord",
            args
          ),
          canSwitchTemplate: !isPostsPage && !isFrontPage
        };
      },
      [postType2, postId, isBulk]
    );
    const { editEntityRecord, saveEditedEntityRecord } = (0, import_data84.useDispatch)(import_core_data66.store);
    const _fields = usePostFields4({ postType: postType2 });
    const fields2 = (0, import_element196.useMemo)(
      () => _fields?.map((field) => {
        if (field.id === "status") {
          return {
            ...field,
            elements: field.elements.filter(
              (element) => element.value !== "trash"
            )
          };
        }
        if (field.id === "template") {
          return {
            ...field,
            readOnly: !canSwitchTemplate
          };
        }
        return field;
      }),
      [_fields, canSwitchTemplate]
    );
    const form2 = (0, import_element196.useMemo)(() => {
      if (!quickEditForm) {
        return { layout: { type: "panel" }, fields: [] };
      }
      if (!isBulk) {
        return quickEditForm;
      }
      return {
        ...quickEditForm,
        fields: (quickEditForm.fields ?? []).filter(
          (field) => fieldsWithBulkEditSupport.includes(
            typeof field === "string" ? field : field.id
          )
        )
      };
    }, [isBulk, quickEditForm]);
    const onChange = (edits) => {
      const currentData = { ...record, ...localEdits };
      if (edits.status && edits.status !== "future" && currentData?.status === "future" && new Date(currentData.date) > /* @__PURE__ */ new Date()) {
        edits.date = null;
      }
      if (edits.status && edits.status === "private" && currentData?.password) {
        edits.password = "";
      }
      setLocalEdits((prev) => ({ ...prev, ...edits }));
    };
    (0, import_element196.useEffect)(() => {
      setLocalEdits({});
    }, [postId]);
    const onSave = async () => {
      for (const id of postId) {
        editEntityRecord("postType", postType2, id, localEdits);
      }
      if (isBulk) {
        await Promise.allSettled(
          postId.map(
            (id) => saveEditedEntityRecord("postType", postType2, id)
          )
        );
      } else {
        await saveEditedEntityRecord("postType", postType2, postId[0]);
      }
      closeModal?.();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime328.jsxs)(
      import_components155.Modal,
      {
        overlayClassName: "dataviews-action-modal__quick-edit",
        __experimentalHideHeader: true,
        onRequestClose: closeModal,
        focusOnMount: "firstElement",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime328.jsx)("div", { className: "dataviews-action-modal__quick-edit-header", children: /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
            PostCardPanel,
            {
              postType: postType2,
              postId,
              hideActions: true
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime328.jsx)("div", { className: "dataviews-action-modal__quick-edit-content", children: hasFinishedResolution && /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
            DataForm,
            {
              data: { ...record, ...localEdits },
              fields: fields2,
              form: form2,
              onChange
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime328.jsxs)(import_components155.__experimentalHStack, { className: "dataviews-action-modal__quick-edit-footer", children: [
            /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
              import_components155.Button,
              {
                __next40pxDefaultSize: true,
                variant: "secondary",
                onClick: closeModal,
                children: (0, import_i18n156.__)("Cancel")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime328.jsx)(
              import_components155.Button,
              {
                __next40pxDefaultSize: true,
                variant: "primary",
                onClick: onSave,
                children: (0, import_i18n156.__)("Done")
              }
            )
          ] })
        ]
      }
    );
  }

  // packages/edit-site/build-module/components/post-list/index.mjs
  var import_jsx_runtime329 = __toESM(require_jsx_runtime(), 1);
  var { usePostActions: usePostActions4, usePostFields: usePostFields5 } = unlock(import_editor41.privateApis);
  var { useLocation: useLocation31, useHistory: useHistory25 } = unlock(import_router36.privateApis);
  var { useEntityRecordsWithPermissions: useEntityRecordsWithPermissions4 } = unlock(import_core_data67.privateApis);
  var EMPTY_ARRAY16 = [];
  var DEFAULT_STATUSES = "draft,future,pending,private,publish";
  function getItemId(item) {
    return item.id.toString();
  }
  function getItemLevel(item) {
    return item.level;
  }
  function PostList({ postType: postType2 }) {
    const { path, query } = useLocation31();
    const { activeView = "all", postId, quickEdit = false } = query;
    const history = useHistory25();
    const {
      default_view: defaultView,
      default_layouts: defaultLayouts2,
      view_list: viewList,
      form: quickEditForm
    } = useViewConfig({
      kind: "postType",
      name: postType2
    });
    const activeViewOverrides = (0, import_element197.useMemo)(
      () => viewList?.find((v2) => v2.slug === activeView)?.view ?? {},
      [viewList, activeView]
    );
    const { view, updateView, isModified, resetToDefault } = useView({
      kind: "postType",
      name: postType2,
      slug: "default",
      defaultView,
      defaultLayouts: defaultLayouts2,
      activeViewOverrides,
      queryParams: {
        page: query.pageNumber,
        search: query.search
      },
      onChangeQueryParams: (newQueryParams) => {
        history.navigate(
          (0, import_url25.addQueryArgs)(path, {
            ...query,
            pageNumber: newQueryParams.page,
            search: newQueryParams.search || void 0
          })
        );
      }
    });
    const onChangeView = (0, import_compose35.useEvent)((newView) => {
      updateView(newView);
      if (newView.type !== view.type) {
        history.invalidate();
      }
    });
    const [selection, setSelection] = (0, import_element197.useState)(postId?.split(",") ?? []);
    const onChangeSelection = (0, import_element197.useCallback)(
      (items) => {
        setSelection(items);
        history.navigate(
          (0, import_url25.addQueryArgs)(path, {
            postId: items.join(",")
          })
        );
      },
      [path, history]
    );
    (0, import_element197.useEffect)(() => {
      const newSelection = postId?.split(",") ?? [];
      setSelection(newSelection);
    }, [postId]);
    const fields2 = usePostFields5({
      postType: postType2
    });
    const queryArgs = (0, import_element197.useMemo)(() => {
      const filters = {};
      view.filters?.forEach((filter) => {
        if (filter.field === "status" && filter.operator === OPERATOR_IS_ANY) {
          filters.status = filter.value;
        }
        if (filter.field === "author" && filter.operator === OPERATOR_IS_ANY) {
          filters.author = filter.value;
        } else if (filter.field === "author" && filter.operator === OPERATOR_IS_NONE) {
          filters.author_exclude = filter.value;
        }
        if (filter.field === "date") {
          if (!filter.value) {
            return;
          }
          if (filter.operator === OPERATOR_BEFORE) {
            filters.before = filter.value;
          } else if (filter.operator === OPERATOR_AFTER) {
            filters.after = filter.value;
          }
        }
      });
      if (!filters.status || filters.status === "") {
        filters.status = DEFAULT_STATUSES;
      }
      return {
        per_page: view.perPage,
        page: view.page,
        _embed: "author,wp:featuredmedia",
        order: view.sort?.direction,
        orderby: view.sort?.field,
        orderby_hierarchy: !!view.showLevels,
        search: view.search,
        ...filters
      };
    }, [view]);
    const {
      records,
      isResolving: isLoadingData,
      totalItems,
      totalPages,
      hasResolved
    } = useEntityRecordsWithPermissions4("postType", postType2, queryArgs);
    const postIds = (0, import_element197.useMemo)(
      () => records?.map((record) => record.id) ?? [],
      [records]
    );
    const { notesCount, isLoading: isLoadingNotesCount } = useNotesCount(postIds);
    const data = (0, import_element197.useMemo)(() => {
      let processedRecords = records;
      if (view?.sort?.field === "author") {
        processedRecords = filterSortAndPaginate(
          records,
          { sort: { ...view.sort } },
          fields2
        ).data;
      }
      if (processedRecords) {
        return processedRecords.map((record) => ({
          ...record,
          notesCount: notesCount[record.id] ?? 0
        }));
      }
      return processedRecords;
    }, [records, fields2, view?.sort, notesCount]);
    const ids = data?.map((record) => getItemId(record)) ?? [];
    const prevIds = (0, import_compose35.usePrevious)(ids) ?? [];
    const deletedIds = prevIds.filter((id) => !ids.includes(id));
    const postIdWasDeleted = deletedIds.includes(postId);
    (0, import_element197.useEffect)(() => {
      if (postIdWasDeleted) {
        history.navigate(
          (0, import_url25.addQueryArgs)(path, {
            postId: void 0
          })
        );
      }
    }, [history, postIdWasDeleted, path]);
    const paginationInfo = (0, import_element197.useMemo)(
      () => ({
        totalItems,
        totalPages
      }),
      [totalItems, totalPages]
    );
    const { labels, canCreateRecord } = (0, import_data85.useSelect)(
      (select4) => {
        const { getPostType: getPostType2, canUser } = select4(import_core_data67.store);
        return {
          labels: getPostType2(postType2)?.labels,
          canCreateRecord: canUser("create", {
            kind: "postType",
            name: postType2
          })
        };
      },
      [postType2]
    );
    const postTypeActions = usePostActions4({
      postType: postType2,
      context: "list"
    });
    const editAction = useEditPostAction();
    const quickEditAction = useQuickEditPostAction();
    const actions = (0, import_element197.useMemo)(() => {
      if (view.type === LAYOUT_LIST) {
        const editActionPrimary = { ...editAction, isPrimary: true };
        return [editActionPrimary, ...postTypeActions];
      }
      return [editAction, quickEditAction, ...postTypeActions];
    }, [view.type, editAction, quickEditAction, postTypeActions]);
    const [showAddPostModal, setShowAddPostModal] = (0, import_element197.useState)(false);
    const openModal = () => setShowAddPostModal(true);
    const closeModal = () => setShowAddPostModal(false);
    const handleNewPage = ({ type, id }) => {
      history.navigate(`/${type}/${id}?canvas=edit`);
      closeModal();
    };
    const closeQuickEditModal = () => {
      history.navigate(
        (0, import_url25.addQueryArgs)(path, {
          ...query,
          quickEdit: void 0
        })
      );
    };
    return /* @__PURE__ */ (0, import_jsx_runtime329.jsxs)(
      page_default2,
      {
        title: labels?.name,
        headingLevel: 2,
        actions: /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(import_jsx_runtime329.Fragment, { children: labels?.add_new_item && canCreateRecord && /* @__PURE__ */ (0, import_jsx_runtime329.jsxs)(import_jsx_runtime329.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
            import_components156.Button,
            {
              variant: "primary",
              onClick: openModal,
              size: "compact",
              __next40pxDefaultSize: true,
              children: labels.add_new_item
            }
          ),
          showAddPostModal && /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
            AddNewPostModal,
            {
              postType: postType2,
              onSave: handleNewPage,
              onClose: closeModal
            }
          )
        ] }) }),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
            dataviews_default,
            {
              paginationInfo,
              fields: fields2,
              actions,
              data: data || EMPTY_ARRAY16,
              isLoading: isLoadingData || isLoadingNotesCount || !hasResolved,
              view,
              onChangeView,
              selection,
              onChangeSelection,
              isItemClickable: (item) => item.status !== "trash",
              onClickItem: ({ id }) => {
                history.navigate(`/${postType2}/${id}?canvas=edit`);
              },
              getItemId,
              getItemLevel,
              defaultLayouts: defaultLayouts2,
              onReset: isModified ? () => {
                resetToDefault();
                history.invalidate();
              } : false
            },
            activeView
          ),
          quickEdit && !isLoadingData && selection.length > 0 && view.type !== LAYOUT_LIST && /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
            QuickEditModal,
            {
              postType: postType2,
              postId: selection,
              closeModal: closeQuickEditModal,
              quickEditForm
            }
          )
        ]
      }
    );
  }

  // packages/edit-site/build-module/components/site-editor-routes/pages.mjs
  var import_jsx_runtime330 = __toESM(require_jsx_runtime(), 1);
  async function isListView(query) {
    const { activeView = "all" } = query;
    const config2 = await unlock((0, import_data86.resolveSelect)(import_core_data68.store)).getViewConfig(
      "postType",
      "page"
    );
    const defaultView = config2?.default_view;
    const defaultLayouts2 = config2?.default_layouts;
    const viewEntry = config2?.view_list?.find((v2) => v2.slug === activeView);
    const view = await loadView({
      kind: "postType",
      name: "page",
      slug: "default",
      defaultView,
      defaultLayouts: defaultLayouts2,
      activeViewOverrides: viewEntry?.view ?? {}
    });
    return view.type === "list";
  }
  var pagesRoute = {
    name: "pages",
    path: "/page",
    areas: {
      sidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return null;
        }
        return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(
          SidebarNavigationScreen,
          {
            title: (0, import_i18n157.__)("Pages"),
            backPath: "/",
            content: /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(DataViewsSidebarContent, { postType: "page" })
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(SidebarNavigationScreenUnsupported, {});
      },
      content({ siteData }) {
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        return isBlockTheme ? /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(PostList, { postType: "page" }) : void 0;
      },
      async preview({ query, siteData }) {
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        if (!isBlockTheme) {
          return void 0;
        }
        const isList = await isListView(query);
        return isList ? /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(EditSiteEditor, {}) : void 0;
      },
      mobileSidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(import_jsx_runtime330.Fragment, {});
        }
        return siteData.currentTheme.is_block_theme ? void 0 : /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(SidebarNavigationScreenUnsupported, {});
      },
      mobileContent({ siteData }) {
        const isBlockTheme = siteData.currentTheme?.is_block_theme;
        return isBlockTheme ? /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(PostList, { postType: "page" }) : void 0;
      }
    },
    widths: {
      async content({ query }) {
        const isList = await isListView(query);
        return isList ? 380 : void 0;
      }
    }
  };

  // packages/edit-site/build-module/components/site-editor-routes/page-item.mjs
  var import_i18n158 = __toESM(require_i18n(), 1);
  var import_jsx_runtime331 = __toESM(require_jsx_runtime(), 1);
  var pageItemRoute = {
    name: "page-item",
    path: "/page/:postId",
    areas: {
      sidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return null;
        }
        return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
          SidebarNavigationScreen,
          {
            title: (0, import_i18n158.__)("Pages"),
            backPath: "/",
            content: /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(DataViewsSidebarContent, { postType: "page" })
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(SidebarNavigationScreenUnsupported, {});
      },
      // Also rendered on mobile, where this route is only reached at canvas=edit.
      preview({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return null;
        }
        return siteData.currentTheme.is_block_theme ? /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(EditSiteEditor, {}) : /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(SidebarNavigationScreenUnsupported, {});
      }
    }
  };

  // packages/edit-site/build-module/components/site-editor-routes/stylebook.mjs
  var import_i18n159 = __toESM(require_i18n(), 1);
  var import_editor44 = __toESM(require_editor(), 1);
  var import_jsx_runtime332 = __toESM(require_jsx_runtime(), 1);
  var { StyleBookPreview: StyleBookPreview2 } = unlock(import_editor44.privateApis);
  var stylebookRoute = {
    name: "stylebook",
    path: "/stylebook",
    areas: {
      sidebar({ siteData }) {
        if (!isThemeDataLoaded(siteData)) {
          return null;
        }
        return isClassicThemeWithStyleBookSupport(siteData) ? /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(
          SidebarNavigationScreen,
          {
            title: (0, import_i18n159.__)("Styles"),
            backPath: "/",
            description: (0, import_i18n159.__)(
              `Preview your website's visual identity: colors, typography, and blocks.`
            )
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(SidebarNavigationScreenUnsupported, {});
      },
      preview({ siteData }) {
        return isClassicThemeWithStyleBookSupport(siteData) ? /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(
          StyleBookPreview2,
          {
            isStatic: true,
            settings: siteData.editorSettings
          }
        ) : void 0;
      },
      mobileContent({ siteData }) {
        return isClassicThemeWithStyleBookSupport(siteData) ? /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(
          StyleBookPreview2,
          {
            isStatic: true,
            settings: siteData.editorSettings
          }
        ) : void 0;
      }
    }
  };

  // packages/edit-site/build-module/components/site-editor-routes/notfound.mjs
  var import_i18n160 = __toESM(require_i18n(), 1);
  var import_components157 = __toESM(require_components(), 1);
  var import_jsx_runtime333 = __toESM(require_jsx_runtime(), 1);
  function NotFoundError() {
    return /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(import_components157.Notice, { status: "error", isDismissible: false, children: (0, import_i18n160.__)(
      "The requested page could not be found. Please check the URL."
    ) });
  }
  var notFoundRoute = {
    name: "notfound",
    path: "*",
    areas: {
      sidebar: /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(SidebarNavigationScreenMain, {}),
      mobileSidebar: /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(
        SidebarNavigationScreenMain,
        {
          customDescription: /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(NotFoundError, {})
        }
      ),
      content: /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(import_components157.__experimentalSpacer, { padding: 2, children: /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(NotFoundError, {}) })
    }
  };

  // packages/edit-site/build-module/components/site-editor-routes/index.mjs
  var routes2 = [
    pageItemRoute,
    pagesRoute,
    templateItemRoute,
    templatesRoute,
    templatePartItemRoute,
    patternItemRoute,
    patternsRoute,
    navigationItemRoute,
    navigationRoute,
    identityRoute,
    stylesRoute,
    homeRoute,
    stylebookRoute,
    notFoundRoute
  ];
  function useRegisterSiteEditorRoutes() {
    const registry = (0, import_data87.useRegistry)();
    const { registerRoute: registerRoute2 } = unlock((0, import_data87.useDispatch)(store));
    (0, import_element198.useEffect)(() => {
      registry.batch(() => {
        routes2.forEach(registerRoute2);
      });
    }, [registry, registerRoute2]);
  }

  // packages/edit-site/build-module/components/app/index.mjs
  var import_jsx_runtime334 = __toESM(require_jsx_runtime(), 1);
  var { RouterProvider } = unlock(import_router37.privateApis);
  function AppLayout() {
    useCommonCommands();
    useSetCommandContext();
    return /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(LayoutWithGlobalStylesProvider, {});
  }
  function App() {
    useRegisterSiteEditorRoutes();
    const { routes: routes3, currentTheme, editorSettings } = (0, import_data88.useSelect)((select4) => {
      return {
        routes: unlock(select4(store)).getRoutes(),
        currentTheme: select4(import_core_data69.store).getCurrentTheme(),
        // This is a temp solution until the has_theme_json value is available for the current theme.
        editorSettings: select4(store).getSettings()
      };
    }, []);
    const beforeNavigate = (0, import_element199.useCallback)(({ path, query }) => {
      if (!isPreviewingTheme()) {
        return { path, query };
      }
      return {
        path,
        query: {
          ...query,
          wp_theme_preview: "wp_theme_preview" in query ? query.wp_theme_preview : currentlyPreviewingTheme()
        }
      };
    }, []);
    const matchResolverArgsValue = (0, import_element199.useMemo)(
      () => ({
        siteData: { currentTheme, editorSettings }
      }),
      [currentTheme, editorSettings]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(
      RouterProvider,
      {
        routes: routes3,
        pathArg: "p",
        beforeNavigate,
        matchResolverArgs: matchResolverArgsValue,
        children: /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(AppLayout, {})
      }
    );
  }

  // packages/edit-site/build-module/deprecated.mjs
  var import_editor45 = __toESM(require_editor(), 1);
  var import_url26 = __toESM(require_url(), 1);
  var import_deprecated5 = __toESM(require_deprecated(), 1);
  var import_jsx_runtime335 = __toESM(require_jsx_runtime(), 1);
  var isSiteEditor = (0, import_url26.getPath)(window.location.href)?.includes(
    "site-editor.php"
  );
  var deprecateSlot = (name2) => {
    (0, import_deprecated5.default)(`wp.editPost.${name2}`, {
      since: "6.6",
      alternative: `wp.editor.${name2}`
    });
  };
  function PluginMoreMenuItem(props) {
    if (!isSiteEditor) {
      return null;
    }
    deprecateSlot("PluginMoreMenuItem");
    return /* @__PURE__ */ (0, import_jsx_runtime335.jsx)(import_editor45.PluginMoreMenuItem, { ...props });
  }
  function PluginSidebar(props) {
    if (!isSiteEditor) {
      return null;
    }
    deprecateSlot("PluginSidebar");
    return /* @__PURE__ */ (0, import_jsx_runtime335.jsx)(import_editor45.PluginSidebar, { ...props });
  }
  function PluginSidebarMoreMenuItem(props) {
    if (!isSiteEditor) {
      return null;
    }
    deprecateSlot("PluginSidebarMoreMenuItem");
    return /* @__PURE__ */ (0, import_jsx_runtime335.jsx)(import_editor45.PluginSidebarMoreMenuItem, { ...props });
  }

  // packages/edit-site/build-module/index.mjs
  var import_jsx_runtime336 = __toESM(require_jsx_runtime(), 1);
  var { registerCoreBlockBindingsSources } = unlock(import_editor46.privateApis);
  function initializeEditor(id, settings2) {
    const target = document.getElementById(id);
    const root = (0, import_element200.createRoot)(target);
    (0, import_data89.dispatch)(import_blocks15.store).reapplyBlockTypeFilters();
    const coreBlocks = (0, import_block_library4.__experimentalGetCoreBlocks)().filter(
      ({ name: name2 }) => name2 !== "core/freeform"
    );
    (0, import_block_library4.registerCoreBlocks)(coreBlocks);
    registerCoreBlockBindingsSources();
    (0, import_data89.dispatch)(import_blocks15.store).setFreeformFallbackBlockName("core/html");
    (0, import_widgets.registerLegacyWidgetBlock)({ inserter: false });
    (0, import_widgets.registerWidgetGroupBlock)({ inserter: false });
    if (false) {
      (0, import_block_library4.__experimentalRegisterExperimentalCoreBlocks)({
        enableFSEBlocks: true
      });
    }
    (0, import_data89.dispatch)(import_preferences13.store).setDefaults("core/edit-site", {
      welcomeGuide: true,
      welcomeGuideStyles: true,
      welcomeGuidePage: true,
      welcomeGuideTemplate: true
    });
    (0, import_data89.dispatch)(import_preferences13.store).setDefaults("core", {
      allowRightClickOverrides: true,
      distractionFree: false,
      editorMode: "visual",
      editorTool: "edit",
      fixedToolbar: false,
      focusMode: false,
      inactivePanels: [],
      keepCaretInsideBlock: false,
      openPanels: ["post-status"],
      showBlockBreadcrumbs: true,
      showListViewByDefault: false,
      enableChoosePatternModal: true,
      showCollaborationCursor: false,
      showCollaborationJoinNotifications: true,
      showCollaborationLeaveNotifications: true,
      showCollaborationPostSaveNotifications: true
    });
    if (window.__clientSideMediaProcessing) {
      (0, import_data89.dispatch)(import_preferences13.store).setDefaults("core/media", {
        requireApproval: true,
        optimizeOnUpload: true
      });
    }
    (0, import_data89.dispatch)(store).updateSettings(settings2);
    window.addEventListener("dragover", (e2) => e2.preventDefault(), false);
    window.addEventListener("drop", (e2) => e2.preventDefault(), false);
    root.render(
      /* @__PURE__ */ (0, import_jsx_runtime336.jsx)(import_element200.StrictMode, { children: /* @__PURE__ */ (0, import_jsx_runtime336.jsx)(App, {}) })
    );
    return root;
  }
  function reinitializeEditor() {
    (0, import_deprecated6.default)("wp.editSite.reinitializeEditor", {
      since: "6.2",
      version: "6.3"
    });
  }
  return __toCommonJS(index_exports);
})();
/*! Bundled license information:

use-sync-external-store/cjs/use-sync-external-store-shim.development.js:
  (**
   * @license React
   * use-sync-external-store-shim.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js:
  (**
   * @license React
   * use-sync-external-store-shim/with-selector.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

is-plain-object/dist/is-plain-object.mjs:
  (*!
   * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
   *
   * Copyright (c) 2014-2017, Jon Schlinkert.
   * Released under the MIT License.
   *)
*/
