(function() {
"use strict";
var wp;
(wp ||= {}).editor = (() => {
  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: (a3, b3) => (typeof require !== "undefined" ? require : a3)[b3]
  }) : 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/data
  var require_data = __commonJS({
    "package-external:@wordpress/data"(exports, module) {
      module.exports = window.wp.data;
    }
  });

  // 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/element
  var require_element = __commonJS({
    "package-external:@wordpress/element"(exports, module) {
      module.exports = window.wp.element;
    }
  });

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

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

  // 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/blocks
  var require_blocks = __commonJS({
    "package-external:@wordpress/blocks"(exports, module) {
      module.exports = window.wp.blocks;
    }
  });

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

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

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

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

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

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

  // 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/style-engine
  var require_style_engine = __commonJS({
    "package-external:@wordpress/style-engine"(exports, module) {
      module.exports = window.wp.styleEngine;
    }
  });

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

  // 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(a3, b3) {
        if (a3 === b3) return true;
        if (a3 && b3 && typeof a3 == "object" && typeof b3 == "object") {
          if (a3.constructor !== b3.constructor) return false;
          var length2, i3, keys;
          if (Array.isArray(a3)) {
            length2 = a3.length;
            if (length2 != b3.length) return false;
            for (i3 = length2; i3-- !== 0; )
              if (!equal(a3[i3], b3[i3])) return false;
            return true;
          }
          if (a3 instanceof Map && b3 instanceof Map) {
            if (a3.size !== b3.size) return false;
            for (i3 of a3.entries())
              if (!b3.has(i3[0])) return false;
            for (i3 of a3.entries())
              if (!equal(i3[1], b3.get(i3[0]))) return false;
            return true;
          }
          if (a3 instanceof Set && b3 instanceof Set) {
            if (a3.size !== b3.size) return false;
            for (i3 of a3.entries())
              if (!b3.has(i3[0])) return false;
            return true;
          }
          if (ArrayBuffer.isView(a3) && ArrayBuffer.isView(b3)) {
            length2 = a3.length;
            if (length2 != b3.length) return false;
            for (i3 = length2; i3-- !== 0; )
              if (a3[i3] !== b3[i3]) return false;
            return true;
          }
          if (a3.constructor === RegExp) return a3.source === b3.source && a3.flags === b3.flags;
          if (a3.valueOf !== Object.prototype.valueOf) return a3.valueOf() === b3.valueOf();
          if (a3.toString !== Object.prototype.toString) return a3.toString() === b3.toString();
          keys = Object.keys(a3);
          length2 = keys.length;
          if (length2 !== Object.keys(b3).length) return false;
          for (i3 = length2; i3-- !== 0; )
            if (!Object.prototype.hasOwnProperty.call(b3, keys[i3])) return false;
          for (i3 = length2; i3-- !== 0; ) {
            var key = keys[i3];
            if (!equal(a3[key], b3[key])) return false;
          }
          return true;
        }
        return a3 !== a3 && b3 !== b3;
      };
    }
  });

  // 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/a11y
  var require_a11y = __commonJS({
    "package-external:@wordpress/a11y"(exports, module) {
      module.exports = window.wp.a11y;
    }
  });

  // 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/notices
  var require_notices = __commonJS({
    "package-external:@wordpress/notices"(exports, module) {
      module.exports = window.wp.notices;
    }
  });

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

  // node_modules/fast-deep-equal/index.js
  var require_fast_deep_equal = __commonJS({
    "node_modules/fast-deep-equal/index.js"(exports, module) {
      "use strict";
      module.exports = function equal(a3, b3) {
        if (a3 === b3) return true;
        if (a3 && b3 && typeof a3 == "object" && typeof b3 == "object") {
          if (a3.constructor !== b3.constructor) return false;
          var length2, i3, keys;
          if (Array.isArray(a3)) {
            length2 = a3.length;
            if (length2 != b3.length) return false;
            for (i3 = length2; i3-- !== 0; )
              if (!equal(a3[i3], b3[i3])) return false;
            return true;
          }
          if (a3.constructor === RegExp) return a3.source === b3.source && a3.flags === b3.flags;
          if (a3.valueOf !== Object.prototype.valueOf) return a3.valueOf() === b3.valueOf();
          if (a3.toString !== Object.prototype.toString) return a3.toString() === b3.toString();
          keys = Object.keys(a3);
          length2 = keys.length;
          if (length2 !== Object.keys(b3).length) return false;
          for (i3 = length2; i3-- !== 0; )
            if (!Object.prototype.hasOwnProperty.call(b3, keys[i3])) return false;
          for (i3 = length2; i3-- !== 0; ) {
            var key = keys[i3];
            if (!equal(a3[key], b3[key])) return false;
          }
          return true;
        }
        return a3 !== a3 && b3 !== b3;
      };
    }
  });

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

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

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

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

  // 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, y3) {
          return x2 === y3 && (0 !== x2 || 1 / x2 === 1 / y3) || x2 !== x2 && y3 !== y3;
        }
        function useSyncExternalStore$2(subscribe5, getSnapshot2) {
          didWarnOld18Alpha || void 0 === React77.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 = getSnapshot2();
          if (!didWarnUncachedGetSnapshot) {
            var cachedValue = getSnapshot2();
            objectIs(value, cachedValue) || (console.error(
              "The result of getSnapshot should be cached to avoid an infinite loop"
            ), didWarnUncachedGetSnapshot = true);
          }
          cachedValue = useState161({
            inst: { value, getSnapshot: getSnapshot2 }
          });
          var inst = cachedValue[0].inst, forceUpdate = cachedValue[1];
          useLayoutEffect15(
            function() {
              inst.value = value;
              inst.getSnapshot = getSnapshot2;
              checkIfSnapshotChanged(inst) && forceUpdate({ inst });
            },
            [subscribe5, value, getSnapshot2]
          );
          useEffect118(
            function() {
              checkIfSnapshotChanged(inst) && forceUpdate({ inst });
              return subscribe5(function() {
                checkIfSnapshotChanged(inst) && forceUpdate({ inst });
              });
            },
            [subscribe5]
          );
          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(subscribe5, getSnapshot2) {
          return getSnapshot2();
        }
        "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
        var React77 = require_react(), objectIs = "function" === typeof Object.is ? Object.is : is2, useState161 = React77.useState, useEffect118 = React77.useEffect, useLayoutEffect15 = React77.useLayoutEffect, useDebugValue2 = React77.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 !== React77.useSyncExternalStore ? React77.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, y3) {
          return x2 === y3 && (0 !== x2 || 1 / x2 === 1 / y3) || x2 !== x2 && y3 !== y3;
        }
        "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
        var React77 = require_react(), shim = require_shim(), objectIs = "function" === typeof Object.is ? Object.is : is2, useSyncExternalStore6 = shim.useSyncExternalStore, useRef118 = React77.useRef, useEffect118 = React77.useEffect, useMemo153 = React77.useMemo, useDebugValue2 = React77.useDebugValue;
        exports.useSyncExternalStoreWithSelector = function(subscribe5, getSnapshot2, getServerSnapshot2, selector2, isEqual2) {
          var instRef = useRef118(null);
          if (null === instRef.current) {
            var inst = { hasValue: false, value: null };
            instRef.current = inst;
          } else inst = instRef.current;
          instRef = useMemo153(
            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 === getServerSnapshot2 ? null : getServerSnapshot2;
              return [
                function() {
                  return memoizedSelector(getSnapshot2());
                },
                null === maybeGetServerSnapshot ? void 0 : function() {
                  return memoizedSelector(maybeGetServerSnapshot());
                }
              ];
            },
            [getSnapshot2, getServerSnapshot2, selector2, isEqual2]
          );
          var value = useSyncExternalStore6(subscribe5, instRef[0], instRef[1]);
          useEffect118(
            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/theme
  var require_theme = __commonJS({
    "package-external:@wordpress/theme"(exports, module) {
      module.exports = window.wp.theme;
    }
  });

  // 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 removeAccents6 = function(string) {
        return string.replace(allAccents, matcher);
      };
      var hasAccents = function(string) {
        return !!string.match(firstAccent);
      };
      module.exports = removeAccents6;
      module.exports.has = hasAccents;
      module.exports.remove = removeAccents6;
    }
  });

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

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

  // 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/keyboard-shortcuts
  var require_keyboard_shortcuts = __commonJS({
    "package-external:@wordpress/keyboard-shortcuts"(exports, module) {
      module.exports = window.wp.keyboardShortcuts;
    }
  });

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

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

  // package-external:@wordpress/block-serialization-default-parser
  var require_block_serialization_default_parser = __commonJS({
    "package-external:@wordpress/block-serialization-default-parser"(exports, module) {
      module.exports = window.wp.blockSerializationDefaultParser;
    }
  });

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

  // package-external:@wordpress/upload-media
  var require_upload_media = __commonJS({
    "package-external:@wordpress/upload-media"(exports, module) {
      module.exports = window.wp.uploadMedia;
    }
  });

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

  // node_modules/react-is/cjs/react-is.development.js
  var require_react_is_development = __commonJS({
    "node_modules/react-is/cjs/react-is.development.js"(exports) {
      "use strict";
      if (true) {
        (function() {
          "use strict";
          var hasSymbol = typeof Symbol === "function" && Symbol.for;
          var REACT_ELEMENT_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.element") : 60103;
          var REACT_PORTAL_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.portal") : 60106;
          var REACT_FRAGMENT_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.fragment") : 60107;
          var REACT_STRICT_MODE_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.strict_mode") : 60108;
          var REACT_PROFILER_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.profiler") : 60114;
          var REACT_PROVIDER_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.provider") : 60109;
          var REACT_CONTEXT_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.context") : 60110;
          var REACT_ASYNC_MODE_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.async_mode") : 60111;
          var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.concurrent_mode") : 60111;
          var REACT_FORWARD_REF_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.forward_ref") : 60112;
          var REACT_SUSPENSE_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.suspense") : 60113;
          var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.suspense_list") : 60120;
          var REACT_MEMO_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.memo") : 60115;
          var REACT_LAZY_TYPE2 = hasSymbol ? /* @__PURE__ */ Symbol.for("react.lazy") : 60116;
          var REACT_BLOCK_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.block") : 60121;
          var REACT_FUNDAMENTAL_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.fundamental") : 60117;
          var REACT_RESPONDER_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.responder") : 60118;
          var REACT_SCOPE_TYPE = hasSymbol ? /* @__PURE__ */ Symbol.for("react.scope") : 60119;
          function isValidElementType(type) {
            return typeof type === "string" || typeof type === "function" || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
            type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === "object" && type !== null && (type.$$typeof === REACT_LAZY_TYPE2 || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
          }
          function typeOf(object) {
            if (typeof object === "object" && object !== null) {
              var $$typeof = object.$$typeof;
              switch ($$typeof) {
                case REACT_ELEMENT_TYPE:
                  var type = object.type;
                  switch (type) {
                    case REACT_ASYNC_MODE_TYPE:
                    case REACT_CONCURRENT_MODE_TYPE:
                    case REACT_FRAGMENT_TYPE:
                    case REACT_PROFILER_TYPE:
                    case REACT_STRICT_MODE_TYPE:
                    case REACT_SUSPENSE_TYPE:
                      return type;
                    default:
                      var $$typeofType = type && type.$$typeof;
                      switch ($$typeofType) {
                        case REACT_CONTEXT_TYPE:
                        case REACT_FORWARD_REF_TYPE:
                        case REACT_LAZY_TYPE2:
                        case REACT_MEMO_TYPE:
                        case REACT_PROVIDER_TYPE:
                          return $$typeofType;
                        default:
                          return $$typeof;
                      }
                  }
                case REACT_PORTAL_TYPE:
                  return $$typeof;
              }
            }
            return void 0;
          }
          var AsyncMode = REACT_ASYNC_MODE_TYPE;
          var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
          var ContextConsumer = REACT_CONTEXT_TYPE;
          var ContextProvider = REACT_PROVIDER_TYPE;
          var Element2 = REACT_ELEMENT_TYPE;
          var ForwardRef = REACT_FORWARD_REF_TYPE;
          var Fragment124 = REACT_FRAGMENT_TYPE;
          var Lazy = REACT_LAZY_TYPE2;
          var Memo = REACT_MEMO_TYPE;
          var Portal2 = REACT_PORTAL_TYPE;
          var Profiler = REACT_PROFILER_TYPE;
          var StrictMode = REACT_STRICT_MODE_TYPE;
          var Suspense = REACT_SUSPENSE_TYPE;
          var hasWarnedAboutDeprecatedIsAsyncMode = false;
          function isAsyncMode(object) {
            {
              if (!hasWarnedAboutDeprecatedIsAsyncMode) {
                hasWarnedAboutDeprecatedIsAsyncMode = true;
                console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.");
              }
            }
            return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
          }
          function isConcurrentMode(object) {
            return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
          }
          function isContextConsumer(object) {
            return typeOf(object) === REACT_CONTEXT_TYPE;
          }
          function isContextProvider(object) {
            return typeOf(object) === REACT_PROVIDER_TYPE;
          }
          function isElement3(object) {
            return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
          }
          function isForwardRef(object) {
            return typeOf(object) === REACT_FORWARD_REF_TYPE;
          }
          function isFragment(object) {
            return typeOf(object) === REACT_FRAGMENT_TYPE;
          }
          function isLazy(object) {
            return typeOf(object) === REACT_LAZY_TYPE2;
          }
          function isMemo(object) {
            return typeOf(object) === REACT_MEMO_TYPE;
          }
          function isPortal(object) {
            return typeOf(object) === REACT_PORTAL_TYPE;
          }
          function isProfiler(object) {
            return typeOf(object) === REACT_PROFILER_TYPE;
          }
          function isStrictMode(object) {
            return typeOf(object) === REACT_STRICT_MODE_TYPE;
          }
          function isSuspense(object) {
            return typeOf(object) === REACT_SUSPENSE_TYPE;
          }
          exports.AsyncMode = AsyncMode;
          exports.ConcurrentMode = ConcurrentMode;
          exports.ContextConsumer = ContextConsumer;
          exports.ContextProvider = ContextProvider;
          exports.Element = Element2;
          exports.ForwardRef = ForwardRef;
          exports.Fragment = Fragment124;
          exports.Lazy = Lazy;
          exports.Memo = Memo;
          exports.Portal = Portal2;
          exports.Profiler = Profiler;
          exports.StrictMode = StrictMode;
          exports.Suspense = Suspense;
          exports.isAsyncMode = isAsyncMode;
          exports.isConcurrentMode = isConcurrentMode;
          exports.isContextConsumer = isContextConsumer;
          exports.isContextProvider = isContextProvider;
          exports.isElement = isElement3;
          exports.isForwardRef = isForwardRef;
          exports.isFragment = isFragment;
          exports.isLazy = isLazy;
          exports.isMemo = isMemo;
          exports.isPortal = isPortal;
          exports.isProfiler = isProfiler;
          exports.isStrictMode = isStrictMode;
          exports.isSuspense = isSuspense;
          exports.isValidElementType = isValidElementType;
          exports.typeOf = typeOf;
        })();
      }
    }
  });

  // node_modules/react-is/index.js
  var require_react_is = __commonJS({
    "node_modules/react-is/index.js"(exports, module) {
      "use strict";
      if (false) {
        module.exports = null;
      } else {
        module.exports = require_react_is_development();
      }
    }
  });

  // node_modules/object-assign/index.js
  var require_object_assign = __commonJS({
    "node_modules/object-assign/index.js"(exports, module) {
      "use strict";
      var getOwnPropertySymbols = Object.getOwnPropertySymbols;
      var hasOwnProperty2 = Object.prototype.hasOwnProperty;
      var propIsEnumerable = Object.prototype.propertyIsEnumerable;
      function toObject(val) {
        if (val === null || val === void 0) {
          throw new TypeError("Object.assign cannot be called with null or undefined");
        }
        return Object(val);
      }
      function shouldUseNative() {
        try {
          if (!Object.assign) {
            return false;
          }
          var test1 = new String("abc");
          test1[5] = "de";
          if (Object.getOwnPropertyNames(test1)[0] === "5") {
            return false;
          }
          var test2 = {};
          for (var i3 = 0; i3 < 10; i3++) {
            test2["_" + String.fromCharCode(i3)] = i3;
          }
          var order2 = Object.getOwnPropertyNames(test2).map(function(n3) {
            return test2[n3];
          });
          if (order2.join("") !== "0123456789") {
            return false;
          }
          var test3 = {};
          "abcdefghijklmnopqrst".split("").forEach(function(letter) {
            test3[letter] = letter;
          });
          if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
            return false;
          }
          return true;
        } catch (err) {
          return false;
        }
      }
      module.exports = shouldUseNative() ? Object.assign : function(target, source) {
        var from;
        var to2 = toObject(target);
        var symbols;
        for (var s3 = 1; s3 < arguments.length; s3++) {
          from = Object(arguments[s3]);
          for (var key in from) {
            if (hasOwnProperty2.call(from, key)) {
              to2[key] = from[key];
            }
          }
          if (getOwnPropertySymbols) {
            symbols = getOwnPropertySymbols(from);
            for (var i3 = 0; i3 < symbols.length; i3++) {
              if (propIsEnumerable.call(from, symbols[i3])) {
                to2[symbols[i3]] = from[symbols[i3]];
              }
            }
          }
        }
        return to2;
      };
    }
  });

  // node_modules/prop-types/lib/ReactPropTypesSecret.js
  var require_ReactPropTypesSecret = __commonJS({
    "node_modules/prop-types/lib/ReactPropTypesSecret.js"(exports, module) {
      "use strict";
      var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
      module.exports = ReactPropTypesSecret;
    }
  });

  // node_modules/prop-types/lib/has.js
  var require_has = __commonJS({
    "node_modules/prop-types/lib/has.js"(exports, module) {
      module.exports = Function.call.bind(Object.prototype.hasOwnProperty);
    }
  });

  // node_modules/prop-types/checkPropTypes.js
  var require_checkPropTypes = __commonJS({
    "node_modules/prop-types/checkPropTypes.js"(exports, module) {
      "use strict";
      var printWarning = function() {
      };
      if (true) {
        ReactPropTypesSecret = require_ReactPropTypesSecret();
        loggedTypeFailures = {};
        has = require_has();
        printWarning = function(text) {
          var message2 = "Warning: " + text;
          if (typeof console !== "undefined") {
            console.error(message2);
          }
          try {
            throw new Error(message2);
          } catch (x2) {
          }
        };
      }
      var ReactPropTypesSecret;
      var loggedTypeFailures;
      var has;
      function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
        if (true) {
          for (var typeSpecName in typeSpecs) {
            if (has(typeSpecs, typeSpecName)) {
              var error2;
              try {
                if (typeof typeSpecs[typeSpecName] !== "function") {
                  var err = Error(
                    (componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."
                  );
                  err.name = "Invariant Violation";
                  throw err;
                }
                error2 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
              } catch (ex) {
                error2 = ex;
              }
              if (error2 && !(error2 instanceof Error)) {
                printWarning(
                  (componentName || "React class") + ": type specification of " + location + " `" + typeSpecName + "` is invalid; the type checker function must return `null` or an `Error` but returned a " + typeof error2 + ". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."
                );
              }
              if (error2 instanceof Error && !(error2.message in loggedTypeFailures)) {
                loggedTypeFailures[error2.message] = true;
                var stack = getStack ? getStack() : "";
                printWarning(
                  "Failed " + location + " type: " + error2.message + (stack != null ? stack : "")
                );
              }
            }
          }
        }
      }
      checkPropTypes.resetWarningCache = function() {
        if (true) {
          loggedTypeFailures = {};
        }
      };
      module.exports = checkPropTypes;
    }
  });

  // node_modules/prop-types/factoryWithTypeCheckers.js
  var require_factoryWithTypeCheckers = __commonJS({
    "node_modules/prop-types/factoryWithTypeCheckers.js"(exports, module) {
      "use strict";
      var ReactIs = require_react_is();
      var assign2 = require_object_assign();
      var ReactPropTypesSecret = require_ReactPropTypesSecret();
      var has = require_has();
      var checkPropTypes = require_checkPropTypes();
      var printWarning = function() {
      };
      if (true) {
        printWarning = function(text) {
          var message2 = "Warning: " + text;
          if (typeof console !== "undefined") {
            console.error(message2);
          }
          try {
            throw new Error(message2);
          } catch (x2) {
          }
        };
      }
      function emptyFunctionThatReturnsNull() {
        return null;
      }
      module.exports = function(isValidElement5, throwOnDirectAccess) {
        var ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator;
        var FAUX_ITERATOR_SYMBOL = "@@iterator";
        function getIteratorFn(maybeIterable) {
          var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
          if (typeof iteratorFn === "function") {
            return iteratorFn;
          }
        }
        var ANONYMOUS = "<<anonymous>>";
        var ReactPropTypes = {
          array: createPrimitiveTypeChecker("array"),
          bigint: createPrimitiveTypeChecker("bigint"),
          bool: createPrimitiveTypeChecker("boolean"),
          func: createPrimitiveTypeChecker("function"),
          number: createPrimitiveTypeChecker("number"),
          object: createPrimitiveTypeChecker("object"),
          string: createPrimitiveTypeChecker("string"),
          symbol: createPrimitiveTypeChecker("symbol"),
          any: createAnyTypeChecker(),
          arrayOf: createArrayOfTypeChecker,
          element: createElementTypeChecker(),
          elementType: createElementTypeTypeChecker(),
          instanceOf: createInstanceTypeChecker,
          node: createNodeChecker(),
          objectOf: createObjectOfTypeChecker,
          oneOf: createEnumTypeChecker,
          oneOfType: createUnionTypeChecker,
          shape: createShapeTypeChecker,
          exact: createStrictShapeTypeChecker
        };
        function is2(x2, y3) {
          if (x2 === y3) {
            return x2 !== 0 || 1 / x2 === 1 / y3;
          } else {
            return x2 !== x2 && y3 !== y3;
          }
        }
        function PropTypeError(message2, data) {
          this.message = message2;
          this.data = data && typeof data === "object" ? data : {};
          this.stack = "";
        }
        PropTypeError.prototype = Error.prototype;
        function createChainableTypeChecker(validate) {
          if (true) {
            var manualPropTypeCallCache = {};
            var manualPropTypeWarningCount = 0;
          }
          function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
            componentName = componentName || ANONYMOUS;
            propFullName = propFullName || propName;
            if (secret !== ReactPropTypesSecret) {
              if (throwOnDirectAccess) {
                var err = new Error(
                  "Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types"
                );
                err.name = "Invariant Violation";
                throw err;
              } else if (typeof console !== "undefined") {
                var cacheKey2 = componentName + ":" + propName;
                if (!manualPropTypeCallCache[cacheKey2] && // Avoid spamming the console because they are often not actionable except for lib authors
                manualPropTypeWarningCount < 3) {
                  printWarning(
                    "You are manually calling a React.PropTypes validation function for the `" + propFullName + "` prop on `" + componentName + "`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."
                  );
                  manualPropTypeCallCache[cacheKey2] = true;
                  manualPropTypeWarningCount++;
                }
              }
            }
            if (props[propName] == null) {
              if (isRequired) {
                if (props[propName] === null) {
                  return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`."));
                }
                return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`."));
              }
              return null;
            } else {
              return validate(props, propName, componentName, location, propFullName);
            }
          }
          var chainedCheckType = checkType.bind(null, false);
          chainedCheckType.isRequired = checkType.bind(null, true);
          return chainedCheckType;
        }
        function createPrimitiveTypeChecker(expectedType) {
          function validate(props, propName, componentName, location, propFullName, secret) {
            var propValue = props[propName];
            var propType = getPropType(propValue);
            if (propType !== expectedType) {
              var preciseType = getPreciseType(propValue);
              return new PropTypeError(
                "Invalid " + location + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."),
                { expectedType }
              );
            }
            return null;
          }
          return createChainableTypeChecker(validate);
        }
        function createAnyTypeChecker() {
          return createChainableTypeChecker(emptyFunctionThatReturnsNull);
        }
        function createArrayOfTypeChecker(typeChecker) {
          function validate(props, propName, componentName, location, propFullName) {
            if (typeof typeChecker !== "function") {
              return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf.");
            }
            var propValue = props[propName];
            if (!Array.isArray(propValue)) {
              var propType = getPropType(propValue);
              return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array."));
            }
            for (var i3 = 0; i3 < propValue.length; i3++) {
              var error2 = typeChecker(propValue, i3, componentName, location, propFullName + "[" + i3 + "]", ReactPropTypesSecret);
              if (error2 instanceof Error) {
                return error2;
              }
            }
            return null;
          }
          return createChainableTypeChecker(validate);
        }
        function createElementTypeChecker() {
          function validate(props, propName, componentName, location, propFullName) {
            var propValue = props[propName];
            if (!isValidElement5(propValue)) {
              var propType = getPropType(propValue);
              return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement."));
            }
            return null;
          }
          return createChainableTypeChecker(validate);
        }
        function createElementTypeTypeChecker() {
          function validate(props, propName, componentName, location, propFullName) {
            var propValue = props[propName];
            if (!ReactIs.isValidElementType(propValue)) {
              var propType = getPropType(propValue);
              return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement type."));
            }
            return null;
          }
          return createChainableTypeChecker(validate);
        }
        function createInstanceTypeChecker(expectedClass) {
          function validate(props, propName, componentName, location, propFullName) {
            if (!(props[propName] instanceof expectedClass)) {
              var expectedClassName = expectedClass.name || ANONYMOUS;
              var actualClassName = getClassName(props[propName]);
              return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`."));
            }
            return null;
          }
          return createChainableTypeChecker(validate);
        }
        function createEnumTypeChecker(expectedValues) {
          if (!Array.isArray(expectedValues)) {
            if (true) {
              if (arguments.length > 1) {
                printWarning(
                  "Invalid arguments supplied to oneOf, expected an array, got " + arguments.length + " arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."
                );
              } else {
                printWarning("Invalid argument supplied to oneOf, expected an array.");
              }
            }
            return emptyFunctionThatReturnsNull;
          }
          function validate(props, propName, componentName, location, propFullName) {
            var propValue = props[propName];
            for (var i3 = 0; i3 < expectedValues.length; i3++) {
              if (is2(propValue, expectedValues[i3])) {
                return null;
              }
            }
            var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
              var type = getPreciseType(value);
              if (type === "symbol") {
                return String(value);
              }
              return value;
            });
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` of value `" + String(propValue) + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + "."));
          }
          return createChainableTypeChecker(validate);
        }
        function createObjectOfTypeChecker(typeChecker) {
          function validate(props, propName, componentName, location, propFullName) {
            if (typeof typeChecker !== "function") {
              return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf.");
            }
            var propValue = props[propName];
            var propType = getPropType(propValue);
            if (propType !== "object") {
              return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object."));
            }
            for (var key in propValue) {
              if (has(propValue, key)) {
                var error2 = typeChecker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
                if (error2 instanceof Error) {
                  return error2;
                }
              }
            }
            return null;
          }
          return createChainableTypeChecker(validate);
        }
        function createUnionTypeChecker(arrayOfTypeCheckers) {
          if (!Array.isArray(arrayOfTypeCheckers)) {
            true ? printWarning("Invalid argument supplied to oneOfType, expected an instance of array.") : void 0;
            return emptyFunctionThatReturnsNull;
          }
          for (var i3 = 0; i3 < arrayOfTypeCheckers.length; i3++) {
            var checker = arrayOfTypeCheckers[i3];
            if (typeof checker !== "function") {
              printWarning(
                "Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i3 + "."
              );
              return emptyFunctionThatReturnsNull;
            }
          }
          function validate(props, propName, componentName, location, propFullName) {
            var expectedTypes = [];
            for (var i4 = 0; i4 < arrayOfTypeCheckers.length; i4++) {
              var checker2 = arrayOfTypeCheckers[i4];
              var checkerResult = checker2(props, propName, componentName, location, propFullName, ReactPropTypesSecret);
              if (checkerResult == null) {
                return null;
              }
              if (checkerResult.data && has(checkerResult.data, "expectedType")) {
                expectedTypes.push(checkerResult.data.expectedType);
              }
            }
            var expectedTypesMessage = expectedTypes.length > 0 ? ", expected one of type [" + expectedTypes.join(", ") + "]" : "";
            return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`" + expectedTypesMessage + "."));
          }
          return createChainableTypeChecker(validate);
        }
        function createNodeChecker() {
          function validate(props, propName, componentName, location, propFullName) {
            if (!isNode3(props[propName])) {
              return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode."));
            }
            return null;
          }
          return createChainableTypeChecker(validate);
        }
        function invalidValidatorError(componentName, location, propFullName, key, type) {
          return new PropTypeError(
            (componentName || "React class") + ": " + location + " type `" + propFullName + "." + key + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + type + "`."
          );
        }
        function createShapeTypeChecker(shapeTypes) {
          function validate(props, propName, componentName, location, propFullName) {
            var propValue = props[propName];
            var propType = getPropType(propValue);
            if (propType !== "object") {
              return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
            }
            for (var key in shapeTypes) {
              var checker = shapeTypes[key];
              if (typeof checker !== "function") {
                return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
              }
              var error2 = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
              if (error2) {
                return error2;
              }
            }
            return null;
          }
          return createChainableTypeChecker(validate);
        }
        function createStrictShapeTypeChecker(shapeTypes) {
          function validate(props, propName, componentName, location, propFullName) {
            var propValue = props[propName];
            var propType = getPropType(propValue);
            if (propType !== "object") {
              return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
            }
            var allKeys = assign2({}, props[propName], shapeTypes);
            for (var key in allKeys) {
              var checker = shapeTypes[key];
              if (has(shapeTypes, key) && typeof checker !== "function") {
                return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
              }
              if (!checker) {
                return new PropTypeError(
                  "Invalid " + location + " `" + propFullName + "` key `" + key + "` supplied to `" + componentName + "`.\nBad object: " + JSON.stringify(props[propName], null, "  ") + "\nValid keys: " + JSON.stringify(Object.keys(shapeTypes), null, "  ")
                );
              }
              var error2 = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
              if (error2) {
                return error2;
              }
            }
            return null;
          }
          return createChainableTypeChecker(validate);
        }
        function isNode3(propValue) {
          switch (typeof propValue) {
            case "number":
            case "string":
            case "undefined":
              return true;
            case "boolean":
              return !propValue;
            case "object":
              if (Array.isArray(propValue)) {
                return propValue.every(isNode3);
              }
              if (propValue === null || isValidElement5(propValue)) {
                return true;
              }
              var iteratorFn = getIteratorFn(propValue);
              if (iteratorFn) {
                var iterator = iteratorFn.call(propValue);
                var step;
                if (iteratorFn !== propValue.entries) {
                  while (!(step = iterator.next()).done) {
                    if (!isNode3(step.value)) {
                      return false;
                    }
                  }
                } else {
                  while (!(step = iterator.next()).done) {
                    var entry = step.value;
                    if (entry) {
                      if (!isNode3(entry[1])) {
                        return false;
                      }
                    }
                  }
                }
              } else {
                return false;
              }
              return true;
            default:
              return false;
          }
        }
        function isSymbol(propType, propValue) {
          if (propType === "symbol") {
            return true;
          }
          if (!propValue) {
            return false;
          }
          if (propValue["@@toStringTag"] === "Symbol") {
            return true;
          }
          if (typeof Symbol === "function" && propValue instanceof Symbol) {
            return true;
          }
          return false;
        }
        function getPropType(propValue) {
          var propType = typeof propValue;
          if (Array.isArray(propValue)) {
            return "array";
          }
          if (propValue instanceof RegExp) {
            return "object";
          }
          if (isSymbol(propType, propValue)) {
            return "symbol";
          }
          return propType;
        }
        function getPreciseType(propValue) {
          if (typeof propValue === "undefined" || propValue === null) {
            return "" + propValue;
          }
          var propType = getPropType(propValue);
          if (propType === "object") {
            if (propValue instanceof Date) {
              return "date";
            } else if (propValue instanceof RegExp) {
              return "regexp";
            }
          }
          return propType;
        }
        function getPostfixForTypeWarning(value) {
          var type = getPreciseType(value);
          switch (type) {
            case "array":
            case "object":
              return "an " + type;
            case "boolean":
            case "date":
            case "regexp":
              return "a " + type;
            default:
              return type;
          }
        }
        function getClassName(propValue) {
          if (!propValue.constructor || !propValue.constructor.name) {
            return ANONYMOUS;
          }
          return propValue.constructor.name;
        }
        ReactPropTypes.checkPropTypes = checkPropTypes;
        ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
        ReactPropTypes.PropTypes = ReactPropTypes;
        return ReactPropTypes;
      };
    }
  });

  // node_modules/prop-types/index.js
  var require_prop_types = __commonJS({
    "node_modules/prop-types/index.js"(exports, module) {
      if (true) {
        ReactIs = require_react_is();
        throwOnDirectAccess = true;
        module.exports = require_factoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess);
      } else {
        module.exports = null();
      }
      var ReactIs;
      var throwOnDirectAccess;
    }
  });

  // node_modules/autosize/dist/autosize.js
  var require_autosize = __commonJS({
    "node_modules/autosize/dist/autosize.js"(exports, module) {
      (function(global, factory) {
        if (typeof define === "function" && define.amd) {
          define(["module", "exports"], factory);
        } else if (typeof exports !== "undefined") {
          factory(module, exports);
        } else {
          var mod = {
            exports: {}
          };
          factory(mod, mod.exports);
          global.autosize = mod.exports;
        }
      })(exports, function(module2, exports2) {
        "use strict";
        var map = typeof Map === "function" ? /* @__PURE__ */ new Map() : /* @__PURE__ */ (function() {
          var keys = [];
          var values = [];
          return {
            has: function has(key) {
              return keys.indexOf(key) > -1;
            },
            get: function get(key) {
              return values[keys.indexOf(key)];
            },
            set: function set5(key, value) {
              if (keys.indexOf(key) === -1) {
                keys.push(key);
                values.push(value);
              }
            },
            delete: function _delete(key) {
              var index2 = keys.indexOf(key);
              if (index2 > -1) {
                keys.splice(index2, 1);
                values.splice(index2, 1);
              }
            }
          };
        })();
        var createEvent = function createEvent2(name2) {
          return new Event(name2, { bubbles: true });
        };
        try {
          new Event("test");
        } catch (e3) {
          createEvent = function createEvent2(name2) {
            var evt = document.createEvent("Event");
            evt.initEvent(name2, true, false);
            return evt;
          };
        }
        function assign2(ta) {
          if (!ta || !ta.nodeName || ta.nodeName !== "TEXTAREA" || map.has(ta)) return;
          var heightOffset = null;
          var clientWidth = null;
          var cachedHeight = null;
          function init2() {
            var style = window.getComputedStyle(ta, null);
            if (style.resize === "vertical") {
              ta.style.resize = "none";
            } else if (style.resize === "both") {
              ta.style.resize = "horizontal";
            }
            if (style.boxSizing === "content-box") {
              heightOffset = -(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom));
            } else {
              heightOffset = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
            }
            if (isNaN(heightOffset)) {
              heightOffset = 0;
            }
            update5();
          }
          function changeOverflow(value) {
            {
              var width = ta.style.width;
              ta.style.width = "0px";
              ta.offsetWidth;
              ta.style.width = width;
            }
            ta.style.overflowY = value;
          }
          function getParentOverflows(el) {
            var arr = [];
            while (el && el.parentNode && el.parentNode instanceof Element) {
              if (el.parentNode.scrollTop) {
                arr.push({
                  node: el.parentNode,
                  scrollTop: el.parentNode.scrollTop
                });
              }
              el = el.parentNode;
            }
            return arr;
          }
          function resize() {
            if (ta.scrollHeight === 0) {
              return;
            }
            var overflows = getParentOverflows(ta);
            var docTop = document.documentElement && document.documentElement.scrollTop;
            ta.style.height = "";
            ta.style.height = ta.scrollHeight + heightOffset + "px";
            clientWidth = ta.clientWidth;
            overflows.forEach(function(el) {
              el.node.scrollTop = el.scrollTop;
            });
            if (docTop) {
              document.documentElement.scrollTop = docTop;
            }
          }
          function update5() {
            resize();
            var styleHeight = Math.round(parseFloat(ta.style.height));
            var computed = window.getComputedStyle(ta, null);
            var actualHeight = computed.boxSizing === "content-box" ? Math.round(parseFloat(computed.height)) : ta.offsetHeight;
            if (actualHeight < styleHeight) {
              if (computed.overflowY === "hidden") {
                changeOverflow("scroll");
                resize();
                actualHeight = computed.boxSizing === "content-box" ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
              }
            } else {
              if (computed.overflowY !== "hidden") {
                changeOverflow("hidden");
                resize();
                actualHeight = computed.boxSizing === "content-box" ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
              }
            }
            if (cachedHeight !== actualHeight) {
              cachedHeight = actualHeight;
              var evt = createEvent("autosize:resized");
              try {
                ta.dispatchEvent(evt);
              } catch (err) {
              }
            }
          }
          var pageResize = function pageResize2() {
            if (ta.clientWidth !== clientWidth) {
              update5();
            }
          };
          var destroy2 = function(style) {
            window.removeEventListener("resize", pageResize, false);
            ta.removeEventListener("input", update5, false);
            ta.removeEventListener("keyup", update5, false);
            ta.removeEventListener("autosize:destroy", destroy2, false);
            ta.removeEventListener("autosize:update", update5, false);
            Object.keys(style).forEach(function(key) {
              ta.style[key] = style[key];
            });
            map.delete(ta);
          }.bind(ta, {
            height: ta.style.height,
            resize: ta.style.resize,
            overflowY: ta.style.overflowY,
            overflowX: ta.style.overflowX,
            wordWrap: ta.style.wordWrap
          });
          ta.addEventListener("autosize:destroy", destroy2, false);
          if ("onpropertychange" in ta && "oninput" in ta) {
            ta.addEventListener("keyup", update5, false);
          }
          window.addEventListener("resize", pageResize, false);
          ta.addEventListener("input", update5, false);
          ta.addEventListener("autosize:update", update5, false);
          ta.style.overflowX = "hidden";
          ta.style.wordWrap = "break-word";
          map.set(ta, {
            destroy: destroy2,
            update: update5
          });
          init2();
        }
        function destroy(ta) {
          var methods = map.get(ta);
          if (methods) {
            methods.destroy();
          }
        }
        function update4(ta) {
          var methods = map.get(ta);
          if (methods) {
            methods.update();
          }
        }
        var autosize = null;
        if (typeof window === "undefined" || typeof window.getComputedStyle !== "function") {
          autosize = function autosize2(el) {
            return el;
          };
          autosize.destroy = function(el) {
            return el;
          };
          autosize.update = function(el) {
            return el;
          };
        } else {
          autosize = function autosize2(el, options) {
            if (el) {
              Array.prototype.forEach.call(el.length ? el : [el], function(x2) {
                return assign2(x2, options);
              });
            }
            return el;
          };
          autosize.destroy = function(el) {
            if (el) {
              Array.prototype.forEach.call(el.length ? el : [el], destroy);
            }
            return el;
          };
          autosize.update = function(el) {
            if (el) {
              Array.prototype.forEach.call(el.length ? el : [el], update4);
            }
            return el;
          };
        }
        exports2.default = autosize;
        module2.exports = exports2["default"];
      });
    }
  });

  // node_modules/computed-style/dist/computedStyle.commonjs.js
  var require_computedStyle_commonjs = __commonJS({
    "node_modules/computed-style/dist/computedStyle.commonjs.js"(exports, module) {
      var computedStyle = function(el, prop, getComputedStyle3) {
        getComputedStyle3 = window.getComputedStyle;
        return (
          // If we have getComputedStyle
          (getComputedStyle3 ? (
            // Query it
            // TODO: From CSS-Query notes, we might need (node, null) for FF
            getComputedStyle3(el)
          ) : (
            // Otherwise, we are in IE and use currentStyle
            el.currentStyle
          ))[
            // Switch to camelCase for CSSOM
            // DEV: Grabbed from jQuery
            // https://github.com/jquery/jquery/blob/1.9-stable/src/css.js#L191-L194
            // https://github.com/jquery/jquery/blob/1.9-stable/src/core.js#L593-L597
            prop.replace(/-(\w)/gi, function(word, letter) {
              return letter.toUpperCase();
            })
          ]
        );
      };
      module.exports = computedStyle;
    }
  });

  // node_modules/line-height/lib/line-height.js
  var require_line_height = __commonJS({
    "node_modules/line-height/lib/line-height.js"(exports, module) {
      var computedStyle = require_computedStyle_commonjs();
      function lineHeight(node) {
        var lnHeightStr = computedStyle(node, "line-height");
        var lnHeight = parseFloat(lnHeightStr, 10);
        if (lnHeightStr === lnHeight + "") {
          var _lnHeightStyle = node.style.lineHeight;
          node.style.lineHeight = lnHeightStr + "em";
          lnHeightStr = computedStyle(node, "line-height");
          lnHeight = parseFloat(lnHeightStr, 10);
          if (_lnHeightStyle) {
            node.style.lineHeight = _lnHeightStyle;
          } else {
            delete node.style.lineHeight;
          }
        }
        if (lnHeightStr.indexOf("pt") !== -1) {
          lnHeight *= 4;
          lnHeight /= 3;
        } else if (lnHeightStr.indexOf("mm") !== -1) {
          lnHeight *= 96;
          lnHeight /= 25.4;
        } else if (lnHeightStr.indexOf("cm") !== -1) {
          lnHeight *= 96;
          lnHeight /= 2.54;
        } else if (lnHeightStr.indexOf("in") !== -1) {
          lnHeight *= 96;
        } else if (lnHeightStr.indexOf("pc") !== -1) {
          lnHeight *= 16;
        }
        lnHeight = Math.round(lnHeight);
        if (lnHeightStr === "normal") {
          var nodeName = node.nodeName;
          var _node = document.createElement(nodeName);
          _node.innerHTML = "&nbsp;";
          if (nodeName.toUpperCase() === "TEXTAREA") {
            _node.setAttribute("rows", "1");
          }
          var fontSizeStr = computedStyle(node, "font-size");
          _node.style.fontSize = fontSizeStr;
          _node.style.padding = "0px";
          _node.style.border = "0px";
          var body = document.body;
          body.appendChild(_node);
          var height = _node.offsetHeight;
          lnHeight = height;
          body.removeChild(_node);
        }
        return lnHeight;
      }
      module.exports = lineHeight;
    }
  });

  // node_modules/react-autosize-textarea/lib/TextareaAutosize.js
  var require_TextareaAutosize = __commonJS({
    "node_modules/react-autosize-textarea/lib/TextareaAutosize.js"(exports) {
      "use strict";
      var __extends = exports && exports.__extends || (function() {
        var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
          d3.__proto__ = b3;
        } || function(d3, b3) {
          for (var p4 in b3) if (b3.hasOwnProperty(p4)) d3[p4] = b3[p4];
        };
        return function(d3, b3) {
          extendStatics(d3, b3);
          function __337() {
            this.constructor = d3;
          }
          d3.prototype = b3 === null ? Object.create(b3) : (__337.prototype = b3.prototype, new __337());
        };
      })();
      var __assign2 = exports && exports.__assign || Object.assign || function(t4) {
        for (var s3, i3 = 1, n3 = arguments.length; i3 < n3; i3++) {
          s3 = arguments[i3];
          for (var p4 in s3) if (Object.prototype.hasOwnProperty.call(s3, p4))
            t4[p4] = s3[p4];
        }
        return t4;
      };
      var __rest = exports && exports.__rest || function(s3, e3) {
        var t4 = {};
        for (var p4 in s3) if (Object.prototype.hasOwnProperty.call(s3, p4) && e3.indexOf(p4) < 0)
          t4[p4] = s3[p4];
        if (s3 != null && typeof Object.getOwnPropertySymbols === "function") {
          for (var i3 = 0, p4 = Object.getOwnPropertySymbols(s3); i3 < p4.length; i3++) if (e3.indexOf(p4[i3]) < 0)
            t4[p4[i3]] = s3[p4[i3]];
        }
        return t4;
      };
      exports.__esModule = true;
      var React77 = require_react();
      var PropTypes = require_prop_types();
      var autosize = require_autosize();
      var _getLineHeight = require_line_height();
      var getLineHeight = _getLineHeight;
      var RESIZED = "autosize:resized";
      var TextareaAutosizeClass = (
        /** @class */
        (function(_super) {
          __extends(TextareaAutosizeClass2, _super);
          function TextareaAutosizeClass2() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.state = {
              lineHeight: null
            };
            _this.textarea = null;
            _this.onResize = function(e3) {
              if (_this.props.onResize) {
                _this.props.onResize(e3);
              }
            };
            _this.updateLineHeight = function() {
              if (_this.textarea) {
                _this.setState({
                  lineHeight: getLineHeight(_this.textarea)
                });
              }
            };
            _this.onChange = function(e3) {
              var onChange = _this.props.onChange;
              _this.currentValue = e3.currentTarget.value;
              onChange && onChange(e3);
            };
            return _this;
          }
          TextareaAutosizeClass2.prototype.componentDidMount = function() {
            var _this = this;
            var _a = this.props, maxRows = _a.maxRows, async = _a.async;
            if (typeof maxRows === "number") {
              this.updateLineHeight();
            }
            if (typeof maxRows === "number" || async) {
              setTimeout(function() {
                return _this.textarea && autosize(_this.textarea);
              });
            } else {
              this.textarea && autosize(this.textarea);
            }
            if (this.textarea) {
              this.textarea.addEventListener(RESIZED, this.onResize);
            }
          };
          TextareaAutosizeClass2.prototype.componentWillUnmount = function() {
            if (this.textarea) {
              this.textarea.removeEventListener(RESIZED, this.onResize);
              autosize.destroy(this.textarea);
            }
          };
          TextareaAutosizeClass2.prototype.render = function() {
            var _this = this;
            var _a = this, _b = _a.props, onResize = _b.onResize, maxRows = _b.maxRows, onChange = _b.onChange, style = _b.style, innerRef = _b.innerRef, children = _b.children, props = __rest(_b, ["onResize", "maxRows", "onChange", "style", "innerRef", "children"]), lineHeight = _a.state.lineHeight;
            var maxHeight = maxRows && lineHeight ? lineHeight * maxRows : null;
            return React77.createElement("textarea", __assign2({}, props, { onChange: this.onChange, style: maxHeight ? __assign2({}, style, { maxHeight }) : style, ref: function(element) {
              _this.textarea = element;
              if (typeof _this.props.innerRef === "function") {
                _this.props.innerRef(element);
              } else if (_this.props.innerRef) {
                _this.props.innerRef.current = element;
              }
            } }), children);
          };
          TextareaAutosizeClass2.prototype.componentDidUpdate = function() {
            this.textarea && autosize.update(this.textarea);
          };
          TextareaAutosizeClass2.defaultProps = {
            rows: 1,
            async: false
          };
          TextareaAutosizeClass2.propTypes = {
            rows: PropTypes.number,
            maxRows: PropTypes.number,
            onResize: PropTypes.func,
            innerRef: PropTypes.any,
            async: PropTypes.bool
          };
          return TextareaAutosizeClass2;
        })(React77.Component)
      );
      exports.TextareaAutosize = React77.forwardRef(function(props, ref) {
        return React77.createElement(TextareaAutosizeClass, __assign2({}, props, { innerRef: ref }));
      });
    }
  });

  // node_modules/react-autosize-textarea/lib/index.js
  var require_lib = __commonJS({
    "node_modules/react-autosize-textarea/lib/index.js"(exports, module) {
      "use strict";
      var TextareaAutosize_1 = require_TextareaAutosize();
      module.exports = TextareaAutosize_1.TextareaAutosize;
    }
  });

  // package-external:@wordpress/server-side-render
  var require_server_side_render = __commonJS({
    "package-external:@wordpress/server-side-render"(exports, module) {
      module.exports = window.wp.serverSideRender;
    }
  });

  // packages/editor/build-module/index.mjs
  var index_exports = {};
  __export(index_exports, {
    AlignmentToolbar: () => AlignmentToolbar,
    Autocomplete: () => Autocomplete,
    AutosaveMonitor: () => AutosaveMonitor,
    BlockAlignmentToolbar: () => BlockAlignmentToolbar,
    BlockControls: () => BlockControls,
    BlockEdit: () => BlockEdit,
    BlockEditorKeyboardShortcuts: () => BlockEditorKeyboardShortcuts2,
    BlockFormatControls: () => BlockFormatControls,
    BlockIcon: () => BlockIcon3,
    BlockInspector: () => BlockInspector,
    BlockList: () => BlockList4,
    BlockMover: () => BlockMover,
    BlockNavigationDropdown: () => BlockNavigationDropdown,
    BlockSelectionClearer: () => BlockSelectionClearer,
    BlockSettingsMenu: () => BlockSettingsMenu,
    BlockTitle: () => BlockTitle,
    BlockToolbar: () => BlockToolbar,
    CharacterCount: () => CharacterCount,
    ColorPalette: () => ColorPalette2,
    ContrastChecker: () => ContrastChecker,
    CopyHandler: () => CopyHandler,
    DefaultBlockAppender: () => DefaultBlockAppender,
    DocumentBar: () => DocumentBar,
    DocumentOutline: () => DocumentOutline,
    DocumentOutlineCheck: () => DocumentOutlineCheck,
    EditorHistoryRedo: () => redo_default2,
    EditorHistoryUndo: () => undo_default2,
    EditorKeyboardShortcuts: () => EditorKeyboardShortcuts,
    EditorKeyboardShortcutsRegister: () => register_shortcuts_default,
    EditorNotices: () => editor_notices_default,
    EditorProvider: () => provider_default,
    EditorSnackbars: () => EditorSnackbars,
    EntitiesSavedStates: () => EntitiesSavedStates,
    ErrorBoundary: () => error_boundary_default,
    FontSizePicker: () => FontSizePicker,
    InnerBlocks: () => InnerBlocks,
    Inserter: () => Inserter,
    InspectorAdvancedControls: () => InspectorAdvancedControls,
    InspectorControls: () => InspectorControls,
    LocalAutosaveMonitor: () => local_autosave_monitor_default,
    MediaPlaceholder: () => MediaPlaceholder,
    MediaUpload: () => MediaUpload3,
    MediaUploadCheck: () => MediaUploadCheck2,
    MultiSelectScrollIntoView: () => MultiSelectScrollIntoView,
    NavigableToolbar: () => NavigableToolbar,
    ObserveTyping: () => ObserveTyping,
    PageAttributesCheck: () => check_default2,
    PageAttributesOrder: () => PageAttributesOrderWithChecks,
    PageAttributesPanel: () => PageAttributesPanel,
    PageAttributesParent: () => parent_default2,
    PageTemplate: () => classic_theme_default,
    PanelColorSettings: () => PanelColorSettings,
    PlainText: () => PlainText,
    PluginBlockSettingsMenuItem: () => plugin_block_settings_menu_item_default,
    PluginDocumentSettingPanel: () => plugin_document_setting_panel_default,
    PluginMoreMenuItem: () => PluginMoreMenuItem,
    PluginPostPublishPanel: () => plugin_post_publish_panel_default,
    PluginPostStatusInfo: () => plugin_post_status_info_default,
    PluginPrePublishPanel: () => plugin_pre_publish_panel_default,
    PluginPreviewMenuItem: () => PluginPreviewMenuItem,
    PluginSidebar: () => PluginSidebar,
    PluginSidebarMoreMenuItem: () => PluginSidebarMoreMenuItem,
    PostAuthor: () => post_author_default,
    PostAuthorCheck: () => PostAuthorCheck,
    PostAuthorPanel: () => panel_default,
    PostComments: () => post_comments_default,
    PostDiscussionPanel: () => PostDiscussionPanel,
    PostExcerpt: () => PostExcerpt,
    PostExcerptCheck: () => check_default3,
    PostExcerptPanel: () => PostExcerptPanel,
    PostFeaturedImage: () => post_featured_image_default,
    PostFeaturedImageCheck: () => check_default4,
    PostFeaturedImagePanel: () => PostFeaturedImagePanel,
    PostFormat: () => PostFormat,
    PostFormatCheck: () => PostFormatCheck,
    PostLastRevision: () => post_last_revision_default,
    PostLastRevisionCheck: () => check_default5,
    PostLastRevisionPanel: () => panel_default2,
    PostLockedModal: () => post_locked_modal_default,
    PostPendingStatus: () => post_pending_status_default,
    PostPendingStatusCheck: () => check_default6,
    PostPingbacks: () => post_pingbacks_default,
    PostPreviewButton: () => PostPreviewButton,
    PostPublishButton: () => post_publish_button_default,
    PostPublishButtonLabel: () => PublishButtonLabel,
    PostPublishPanel: () => PostPublishPanel,
    PostSavedState: () => PostSavedState,
    PostSchedule: () => PostSchedule,
    PostScheduleCheck: () => PostScheduleCheck,
    PostScheduleLabel: () => PostScheduleLabel,
    PostSchedulePanel: () => PostSchedulePanel,
    PostSticky: () => PostSticky,
    PostStickyCheck: () => PostStickyCheck,
    PostSwitchToDraftButton: () => PostSwitchToDraftButton,
    PostSyncStatus: () => PostSyncStatus,
    PostTaxonomies: () => post_taxonomies_default,
    PostTaxonomiesCheck: () => PostTaxonomiesCheck,
    PostTaxonomiesFlatTermSelector: () => FlatTermSelector,
    PostTaxonomiesHierarchicalTermSelector: () => HierarchicalTermSelector,
    PostTaxonomiesPanel: () => PostTaxonomies2,
    PostTemplatePanel: () => PostTemplatePanel,
    PostTextEditor: () => PostTextEditor,
    PostTitle: () => post_title_default,
    PostTitleRaw: () => post_title_raw_default,
    PostTrash: () => PostTrash,
    PostTrashCheck: () => PostTrashCheck,
    PostTypeSupportCheck: () => post_type_support_check_default,
    PostURL: () => PostURL,
    PostURLCheck: () => PostURLCheck,
    PostURLLabel: () => PostURLLabel,
    PostURLPanel: () => PostURLPanel,
    PostVisibility: () => PostVisibility,
    PostVisibilityCheck: () => PostVisibilityCheck,
    PostVisibilityLabel: () => PostVisibilityLabel,
    RichText: () => RichText2,
    RichTextShortcut: () => RichTextShortcut,
    RichTextToolbarButton: () => RichTextToolbarButton,
    ServerSideRender: () => import_server_side_render.default,
    SkipToSelectedBlock: () => SkipToSelectedBlock,
    TableOfContents: () => table_of_contents_default,
    TextEditorGlobalKeyboardShortcuts: () => TextEditorGlobalKeyboardShortcuts,
    ThemeSupportCheck: () => ThemeSupportCheck,
    TimeToRead: () => TimeToRead,
    URLInput: () => URLInput,
    URLInputButton: () => URLInputButton,
    URLPopover: () => URLPopover,
    UnsavedChangesWarning: () => UnsavedChangesWarning,
    VisualEditorGlobalKeyboardShortcuts: () => VisualEditorGlobalKeyboardShortcuts,
    Warning: () => Warning,
    WordCount: () => WordCount,
    WritingFlow: () => WritingFlow,
    __unstableRichTextInputEvent: () => __unstableRichTextInputEvent,
    cleanForSlug: () => cleanForSlug2,
    createCustomColorsHOC: () => createCustomColorsHOC,
    getColorClassName: () => getColorClassName2,
    getColorObjectByAttributeValues: () => getColorObjectByAttributeValues,
    getColorObjectByColorValue: () => getColorObjectByColorValue,
    getFontSize: () => getFontSize,
    getFontSizeClass: () => getFontSizeClass,
    getTemplatePartIcon: () => getTemplatePartIcon,
    linkAutocompleter: () => link_default2,
    mediaUpload: () => mediaUpload,
    privateApis: () => privateApis21,
    registerEntityAction: () => registerEntityAction2,
    registerEntityField: () => registerEntityField2,
    store: () => store,
    storeConfig: () => storeConfig,
    transformStyles: () => import_block_editor112.transformStyles,
    unregisterEntityAction: () => unregisterEntityAction2,
    unregisterEntityField: () => unregisterEntityField2,
    useEntitiesSavedStatesIsDirty: () => useIsDirty,
    usePostScheduleLabel: () => usePostScheduleLabel,
    usePostURLLabel: () => usePostURLLabel,
    usePostVisibilityLabel: () => usePostVisibilityLabel,
    userAutocompleter: () => user_default,
    withColorContext: () => withColorContext,
    withColors: () => withColors,
    withFontSizes: () => withFontSizes
  });

  // packages/editor/build-module/hooks/custom-sources-backwards-compatibility.mjs
  var import_data88 = __toESM(require_data(), 1);
  var import_core_data58 = __toESM(require_core_data(), 1);
  var import_element218 = __toESM(require_element(), 1);
  var import_compose35 = __toESM(require_compose(), 1);
  var import_hooks40 = __toESM(require_hooks(), 1);

  // packages/editor/build-module/store/index.mjs
  var import_data87 = __toESM(require_data(), 1);

  // packages/editor/build-module/store/reducer.mjs
  var import_data2 = __toESM(require_data(), 1);

  // packages/editor/build-module/store/defaults.mjs
  var import_block_editor = __toESM(require_block_editor(), 1);
  var EDITOR_SETTINGS_DEFAULTS = {
    ...import_block_editor.SETTINGS_DEFAULTS,
    richEditingEnabled: true,
    codeEditingEnabled: true,
    responsiveEditingEnabled: true,
    blockStatesEditingEnabled: true,
    fontLibraryEnabled: true,
    enableCustomFields: void 0,
    defaultRenderingMode: "post-only"
  };

  // packages/editor/build-module/dataviews/store/reducer.mjs
  var import_data = __toESM(require_data(), 1);
  function isReady(state2 = {}, action) {
    switch (action.type) {
      case "SET_IS_READY":
        return {
          ...state2,
          [action.kind]: {
            ...state2[action.kind],
            [action.name]: true
          }
        };
    }
    return state2;
  }
  function actions(state2 = {}, action) {
    switch (action.type) {
      case "REGISTER_ENTITY_ACTION":
        return {
          ...state2,
          [action.kind]: {
            ...state2[action.kind],
            [action.name]: [
              ...(state2[action.kind]?.[action.name] ?? []).filter(
                (_action) => _action.id !== action.config.id
              ),
              action.config
            ]
          }
        };
      case "UNREGISTER_ENTITY_ACTION": {
        return {
          ...state2,
          [action.kind]: {
            ...state2[action.kind],
            [action.name]: (state2[action.kind]?.[action.name] ?? []).filter((_action) => _action.id !== action.actionId)
          }
        };
      }
    }
    return state2;
  }
  function fields(state2 = {}, action) {
    switch (action.type) {
      case "REGISTER_ENTITY_FIELD":
        return {
          ...state2,
          [action.kind]: {
            ...state2[action.kind],
            [action.name]: [
              ...(state2[action.kind]?.[action.name] ?? []).filter(
                (_field) => _field.id !== action.config.id
              ),
              action.config
            ]
          }
        };
      case "UNREGISTER_ENTITY_FIELD":
        return {
          ...state2,
          [action.kind]: {
            ...state2[action.kind],
            [action.name]: (state2[action.kind]?.[action.name] ?? []).filter((_field) => _field.id !== action.fieldId)
          }
        };
    }
    return state2;
  }
  var reducer_default = (0, import_data.combineReducers)({
    actions,
    fields,
    isReady
  });

  // packages/editor/build-module/store/reducer.mjs
  function getPostRawValue(value) {
    if (value && "object" === typeof value && "raw" in value) {
      return value.raw;
    }
    return value;
  }
  function postId(state2 = null, action) {
    switch (action.type) {
      case "SET_EDITED_POST":
        return action.postId;
    }
    return state2;
  }
  function templateId(state2 = null, action) {
    switch (action.type) {
      case "SET_CURRENT_TEMPLATE_ID":
        return action.id;
    }
    return state2;
  }
  function postType(state2 = null, action) {
    switch (action.type) {
      case "SET_EDITED_POST":
        return action.postType;
    }
    return state2;
  }
  function template(state2 = { isValid: true }, action) {
    switch (action.type) {
      case "SET_TEMPLATE_VALIDITY":
        return {
          ...state2,
          isValid: action.isValid
        };
    }
    return state2;
  }
  function saving(state2 = {}, action) {
    switch (action.type) {
      case "REQUEST_POST_UPDATE_START":
      case "REQUEST_POST_UPDATE_FINISH":
        return {
          pending: action.type === "REQUEST_POST_UPDATE_START",
          options: action.options || {}
        };
    }
    return state2;
  }
  function deleting(state2 = {}, action) {
    switch (action.type) {
      case "REQUEST_POST_DELETE_START":
      case "REQUEST_POST_DELETE_FINISH":
        return {
          pending: action.type === "REQUEST_POST_DELETE_START"
        };
    }
    return state2;
  }
  function postLock(state2 = { isLocked: false }, action) {
    switch (action.type) {
      case "UPDATE_POST_LOCK":
        return action.lock;
    }
    return state2;
  }
  function postSavingLock(state2 = {}, action) {
    switch (action.type) {
      case "LOCK_POST_SAVING":
        return { ...state2, [action.lockName]: true };
      case "UNLOCK_POST_SAVING": {
        const { [action.lockName]: removedLockName, ...restState } = state2;
        return restState;
      }
    }
    return state2;
  }
  function postAutosavingLock(state2 = {}, action) {
    switch (action.type) {
      case "LOCK_POST_AUTOSAVING":
        return { ...state2, [action.lockName]: true };
      case "UNLOCK_POST_AUTOSAVING": {
        const { [action.lockName]: removedLockName, ...restState } = state2;
        return restState;
      }
    }
    return state2;
  }
  function editorSettings(state2 = EDITOR_SETTINGS_DEFAULTS, action) {
    switch (action.type) {
      case "UPDATE_EDITOR_SETTINGS":
        return {
          ...state2,
          ...action.settings
        };
    }
    return state2;
  }
  function renderingMode(state2 = "post-only", action) {
    switch (action.type) {
      case "SET_RENDERING_MODE":
        return action.mode;
    }
    return state2;
  }
  function canvasWidth(state2 = void 0, action) {
    switch (action.type) {
      case "SET_CANVAS_WIDTH":
        return action.width;
    }
    return state2;
  }
  function removedPanels(state2 = [], action) {
    switch (action.type) {
      case "REMOVE_PANEL":
        if (!state2.includes(action.panelName)) {
          return [...state2, action.panelName];
        }
    }
    return state2;
  }
  function blockInserterPanel(state2 = false, action) {
    switch (action.type) {
      case "SET_IS_LIST_VIEW_OPENED":
        return action.isOpen ? false : state2;
      case "SET_IS_INSERTER_OPENED":
        return action.value;
    }
    return state2;
  }
  function listViewPanel(state2 = false, action) {
    switch (action.type) {
      case "SET_IS_INSERTER_OPENED":
        return action.value ? false : state2;
      case "SET_IS_LIST_VIEW_OPENED":
        return action.isOpen;
    }
    return state2;
  }
  function listViewToggleRef(state2 = { current: null }) {
    return state2;
  }
  function inserterSidebarToggleRef(state2 = { current: null }) {
    return state2;
  }
  function publishSidebarActive(state2 = false, action) {
    switch (action.type) {
      case "OPEN_PUBLISH_SIDEBAR":
        return true;
      case "CLOSE_PUBLISH_SIDEBAR":
        return false;
      case "TOGGLE_PUBLISH_SIDEBAR":
        return !state2;
    }
    return state2;
  }
  function stylesPath(state2 = "/", action) {
    switch (action.type) {
      case "SET_STYLES_PATH":
        return action.path;
      case "RESET_STYLES_NAVIGATION":
        return "/";
    }
    return state2;
  }
  function showStylebook(state2 = false, action) {
    switch (action.type) {
      case "SET_SHOW_STYLEBOOK":
        return action.show;
      case "RESET_STYLES_NAVIGATION":
        return false;
    }
    return state2;
  }
  function revisionId(state2 = null, action) {
    switch (action.type) {
      case "SET_CURRENT_REVISION_ID":
        return action.revisionId;
    }
    return state2;
  }
  function revisionPage(state2 = 1, action) {
    switch (action.type) {
      case "SET_REVISION_PAGE":
        return action.page;
      case "SET_CURRENT_REVISION_ID":
        if (!action.revisionId) {
          return 1;
        }
        return state2;
    }
    return state2;
  }
  function showRevisionDiff(state2 = true, action) {
    switch (action.type) {
      case "SET_SHOW_REVISION_DIFF":
        return action.showDiff;
      case "SET_CURRENT_REVISION_ID":
        return !action.revisionId ? true : state2;
    }
    return state2;
  }
  function selectedNote(state2 = {}, action) {
    switch (action.type) {
      case "SELECT_NOTE":
        return { noteId: action.noteId, options: action.options };
    }
    return state2;
  }
  var reducer_default2 = (0, import_data2.combineReducers)({
    postId,
    postType,
    templateId,
    saving,
    deleting,
    postLock,
    template,
    postSavingLock,
    editorSettings,
    postAutosavingLock,
    renderingMode,
    canvasWidth,
    removedPanels,
    blockInserterPanel,
    inserterSidebarToggleRef,
    listViewPanel,
    listViewToggleRef,
    publishSidebarActive,
    stylesPath,
    showStylebook,
    revisionId,
    revisionPage,
    showRevisionDiff,
    selectedNote,
    dataviews: reducer_default
  });

  // packages/editor/build-module/store/selectors.mjs
  var selectors_exports = {};
  __export(selectors_exports, {
    __experimentalGetDefaultTemplatePartAreas: () => __experimentalGetDefaultTemplatePartAreas,
    __experimentalGetDefaultTemplateType: () => __experimentalGetDefaultTemplateType,
    __experimentalGetDefaultTemplateTypes: () => __experimentalGetDefaultTemplateTypes,
    __experimentalGetTemplateInfo: () => __experimentalGetTemplateInfo,
    __unstableIsEditorReady: () => __unstableIsEditorReady,
    canInsertBlockType: () => canInsertBlockType,
    canUserUseUnfilteredHTML: () => canUserUseUnfilteredHTML,
    didPostSaveRequestFail: () => didPostSaveRequestFail,
    didPostSaveRequestSucceed: () => didPostSaveRequestSucceed,
    getActivePostLock: () => getActivePostLock,
    getAdjacentBlockClientId: () => getAdjacentBlockClientId,
    getAutosaveAttribute: () => getAutosaveAttribute,
    getBlock: () => getBlock,
    getBlockAttributes: () => getBlockAttributes,
    getBlockCount: () => getBlockCount,
    getBlockHierarchyRootClientId: () => getBlockHierarchyRootClientId,
    getBlockIndex: () => getBlockIndex,
    getBlockInsertionPoint: () => getBlockInsertionPoint,
    getBlockListSettings: () => getBlockListSettings,
    getBlockMode: () => getBlockMode,
    getBlockName: () => getBlockName,
    getBlockOrder: () => getBlockOrder,
    getBlockRootClientId: () => getBlockRootClientId,
    getBlockSelectionEnd: () => getBlockSelectionEnd,
    getBlockSelectionStart: () => getBlockSelectionStart,
    getBlocks: () => getBlocks,
    getBlocksByClientId: () => getBlocksByClientId,
    getClientIdsOfDescendants: () => getClientIdsOfDescendants,
    getClientIdsWithDescendants: () => getClientIdsWithDescendants,
    getCurrentPost: () => getCurrentPost,
    getCurrentPostAttribute: () => getCurrentPostAttribute,
    getCurrentPostId: () => getCurrentPostId,
    getCurrentPostLastRevisionId: () => getCurrentPostLastRevisionId,
    getCurrentPostRevisionsCount: () => getCurrentPostRevisionsCount,
    getCurrentPostType: () => getCurrentPostType,
    getCurrentTemplateId: () => getCurrentTemplateId,
    getDeviceType: () => getDeviceType,
    getEditedPostAttribute: () => getEditedPostAttribute,
    getEditedPostContent: () => getEditedPostContent,
    getEditedPostPreviewLink: () => getEditedPostPreviewLink,
    getEditedPostSlug: () => getEditedPostSlug,
    getEditedPostVisibility: () => getEditedPostVisibility,
    getEditorBlocks: () => getEditorBlocks,
    getEditorMode: () => getEditorMode,
    getEditorSelection: () => getEditorSelection,
    getEditorSelectionEnd: () => getEditorSelectionEnd,
    getEditorSelectionStart: () => getEditorSelectionStart,
    getEditorSettings: () => getEditorSettings,
    getFirstMultiSelectedBlockClientId: () => getFirstMultiSelectedBlockClientId,
    getGlobalBlockCount: () => getGlobalBlockCount,
    getInserterItems: () => getInserterItems,
    getLastMultiSelectedBlockClientId: () => getLastMultiSelectedBlockClientId,
    getMultiSelectedBlockClientIds: () => getMultiSelectedBlockClientIds,
    getMultiSelectedBlocks: () => getMultiSelectedBlocks,
    getMultiSelectedBlocksEndClientId: () => getMultiSelectedBlocksEndClientId,
    getMultiSelectedBlocksStartClientId: () => getMultiSelectedBlocksStartClientId,
    getNextBlockClientId: () => getNextBlockClientId,
    getPermalink: () => getPermalink,
    getPermalinkParts: () => getPermalinkParts,
    getPostEdits: () => getPostEdits,
    getPostLockUser: () => getPostLockUser,
    getPostTypeLabel: () => getPostTypeLabel,
    getPreviousBlockClientId: () => getPreviousBlockClientId,
    getRenderingMode: () => getRenderingMode,
    getSelectedBlock: () => getSelectedBlock,
    getSelectedBlockClientId: () => getSelectedBlockClientId,
    getSelectedBlockCount: () => getSelectedBlockCount,
    getSelectedBlocksInitialCaretPosition: () => getSelectedBlocksInitialCaretPosition,
    getStateBeforeOptimisticTransaction: () => getStateBeforeOptimisticTransaction,
    getSuggestedPostFormat: () => getSuggestedPostFormat,
    getTemplate: () => getTemplate,
    getTemplateLock: () => getTemplateLock,
    hasChangedContent: () => hasChangedContent,
    hasEditorRedo: () => hasEditorRedo,
    hasEditorUndo: () => hasEditorUndo,
    hasInserterItems: () => hasInserterItems,
    hasMultiSelection: () => hasMultiSelection,
    hasNonPostEntityChanges: () => hasNonPostEntityChanges,
    hasSelectedBlock: () => hasSelectedBlock,
    hasSelectedInnerBlock: () => hasSelectedInnerBlock,
    inSomeHistory: () => inSomeHistory,
    isAncestorMultiSelected: () => isAncestorMultiSelected,
    isAutosavingPost: () => isAutosavingPost,
    isBlockInsertionPointVisible: () => isBlockInsertionPointVisible,
    isBlockMultiSelected: () => isBlockMultiSelected,
    isBlockSelected: () => isBlockSelected,
    isBlockValid: () => isBlockValid,
    isBlockWithinSelection: () => isBlockWithinSelection,
    isCaretWithinFormattedText: () => isCaretWithinFormattedText,
    isCleanNewPost: () => isCleanNewPost,
    isCurrentPostPending: () => isCurrentPostPending,
    isCurrentPostPublished: () => isCurrentPostPublished,
    isCurrentPostScheduled: () => isCurrentPostScheduled,
    isDeletingPost: () => isDeletingPost,
    isEditedPostAutosaveable: () => isEditedPostAutosaveable,
    isEditedPostBeingScheduled: () => isEditedPostBeingScheduled,
    isEditedPostDateFloating: () => isEditedPostDateFloating,
    isEditedPostDirty: () => isEditedPostDirty,
    isEditedPostEmpty: () => isEditedPostEmpty,
    isEditedPostNew: () => isEditedPostNew,
    isEditedPostPublishable: () => isEditedPostPublishable,
    isEditedPostSaveable: () => isEditedPostSaveable,
    isEditorPanelEnabled: () => isEditorPanelEnabled,
    isEditorPanelOpened: () => isEditorPanelOpened,
    isEditorPanelRemoved: () => isEditorPanelRemoved,
    isFirstMultiSelectedBlock: () => isFirstMultiSelectedBlock,
    isInserterOpened: () => isInserterOpened,
    isListViewOpened: () => isListViewOpened,
    isMultiSelecting: () => isMultiSelecting,
    isPermalinkEditable: () => isPermalinkEditable,
    isPostAutosavingLocked: () => isPostAutosavingLocked,
    isPostLockTakeover: () => isPostLockTakeover,
    isPostLocked: () => isPostLocked,
    isPostSavingLocked: () => isPostSavingLocked,
    isPreviewingPost: () => isPreviewingPost,
    isPublishSidebarEnabled: () => isPublishSidebarEnabled,
    isPublishSidebarOpened: () => isPublishSidebarOpened,
    isPublishingPost: () => isPublishingPost,
    isSavingNonPostEntityChanges: () => isSavingNonPostEntityChanges,
    isSavingPost: () => isSavingPost,
    isSelectionEnabled: () => isSelectionEnabled,
    isTyping: () => isTyping,
    isValidTemplate: () => isValidTemplate
  });
  var import_blocks3 = __toESM(require_blocks(), 1);
  var import_date = __toESM(require_date(), 1);
  var import_url = __toESM(require_url(), 1);
  var import_data4 = __toESM(require_data(), 1);
  var import_deprecated = __toESM(require_deprecated(), 1);
  var import_block_editor2 = __toESM(require_block_editor(), 1);
  var import_core_data = __toESM(require_core_data(), 1);
  var import_preferences = __toESM(require_preferences(), 1);

  // packages/editor/build-module/store/constants.mjs
  var EDIT_MERGE_PROPERTIES = /* @__PURE__ */ new Set(["meta"]);
  var STORE_NAME = "core/editor";
  var PERMALINK_POSTNAME_REGEX = /%(?:postname|pagename)%/;
  var ONE_MINUTE_IN_MS = 60 * 1e3;
  var AUTOSAVE_PROPERTIES = ["title", "excerpt", "content"];
  var TEMPLATE_POST_TYPE = "wp_template";
  var TEMPLATE_PART_POST_TYPE = "wp_template_part";
  var PATTERN_POST_TYPE = "wp_block";
  var NAVIGATION_POST_TYPE = "wp_navigation";
  var ATTACHMENT_POST_TYPE = "attachment";
  var TEMPLATE_ORIGINS = {
    custom: "custom",
    theme: "theme",
    plugin: "plugin"
  };
  var TEMPLATE_POST_TYPES = ["wp_template", "wp_template_part"];
  var GLOBAL_POST_TYPES = [
    ...TEMPLATE_POST_TYPES,
    "wp_block",
    "wp_navigation"
  ];
  var DESIGN_POST_TYPES = [
    TEMPLATE_POST_TYPE,
    TEMPLATE_PART_POST_TYPE,
    PATTERN_POST_TYPE,
    NAVIGATION_POST_TYPE
  ];

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

  // packages/icons/build-module/library/add-template.mjs
  var import_primitives = __toESM(require_primitives(), 1);
  var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
  var add_template_default = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_primitives.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_primitives.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M18.5 5.5V8H20V5.5H22.5V4H20V1.5H18.5V4H16V5.5H18.5ZM13.9624 4H6C4.89543 4 4 4.89543 4 6V18C4 19.1046 4.89543 20 6 20H18C19.1046 20 20 19.1046 20 18V10.0391H18.5V18C18.5 18.2761 18.2761 18.5 18 18.5H10L10 10.4917L16.4589 10.5139L16.4641 9.01389L5.5 8.97618V6C5.5 5.72386 5.72386 5.5 6 5.5H13.9624V4ZM5.5 10.4762V18C5.5 18.2761 5.72386 18.5 6 18.5H8.5L8.5 10.4865L5.5 10.4762Z" }) });

  // packages/icons/build-module/library/archive.mjs
  var import_primitives2 = __toESM(require_primitives(), 1);
  var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
  var archive_default = /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_primitives2.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime2.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_runtime3 = __toESM(require_jsx_runtime(), 1);
  var arrow_down_default = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives3.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime3.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_runtime4 = __toESM(require_jsx_runtime(), 1);
  var arrow_left_default = /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives4.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime4.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_runtime5 = __toESM(require_jsx_runtime(), 1);
  var arrow_right_default = /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives5.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime5.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_runtime6 = __toESM(require_jsx_runtime(), 1);
  var arrow_up_default = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives6.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime6.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/aspect-ratio.mjs
  var import_primitives7 = __toESM(require_primitives(), 1);
  var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
  var aspect_ratio_default = /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives7.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives7.Path, { d: "M18.5 5.5h-13c-1.1 0-2 .9-2 2v9c0 1.1.9 2 2 2h13c1.1 0 2-.9 2-2v-9c0-1.1-.9-2-2-2zm.5 11c0 .3-.2.5-.5.5h-13c-.3 0-.5-.2-.5-.5v-9c0-.3.2-.5.5-.5h13c.3 0 .5.2.5.5v9zM6.5 12H8v-2h2V8.5H6.5V12zm9.5 2h-2v1.5h3.5V12H16v2z" }) });

  // packages/icons/build-module/library/audio.mjs
  var import_primitives8 = __toESM(require_primitives(), 1);
  var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
  var audio_default = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_primitives8.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_primitives8.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/background.mjs
  var import_primitives9 = __toESM(require_primitives(), 1);
  var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
  var background_default = /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_primitives9.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_primitives9.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M11.53 4.47a.75.75 0 1 0-1.06 1.06l8 8a.75.75 0 1 0 1.06-1.06l-8-8Zm5 1a.75.75 0 1 0-1.06 1.06l2 2a.75.75 0 1 0 1.06-1.06l-2-2Zm-11.06 10a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06l-2-2a.75.75 0 0 1 0-1.06Zm.06-5a.75.75 0 0 0-1.06 1.06l8 8a.75.75 0 1 0 1.06-1.06l-8-8Zm-.06-3a.75.75 0 0 1 1.06 0l10 10a.75.75 0 1 1-1.06 1.06l-10-10a.75.75 0 0 1 0-1.06Zm3.06-2a.75.75 0 0 0-1.06 1.06l10 10a.75.75 0 1 0 1.06-1.06l-10-10Z" }) });

  // packages/icons/build-module/library/backup.mjs
  var import_primitives10 = __toESM(require_primitives(), 1);
  var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
  var backup_default = /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_primitives10.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_primitives10.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-default.mjs
  var import_primitives11 = __toESM(require_primitives(), 1);
  var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
  var block_default_default = /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_primitives11.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_primitives11.Path, { d: "M19 8h-1V6h-5v2h-2V6H6v2H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-8c0-1.1-.9-2-2-2zm.5 10c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5v-8c0-.3.2-.5.5-.5h14c.3 0 .5.2.5.5v8z" }) });

  // packages/icons/build-module/library/block-table.mjs
  var import_primitives12 = __toESM(require_primitives(), 1);
  var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
  var block_table_default = /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_primitives12.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_primitives12.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/category.mjs
  var import_primitives13 = __toESM(require_primitives(), 1);
  var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
  var category_default = /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_primitives13.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_primitives13.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_primitives14 = __toESM(require_primitives(), 1);
  var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1);
  var check_default = /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_primitives14.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_primitives14.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_primitives15 = __toESM(require_primitives(), 1);
  var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
  var chevron_down_default = /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_primitives15.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_primitives15.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_primitives16 = __toESM(require_primitives(), 1);
  var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
  var chevron_left_small_default = /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_primitives16.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_primitives16.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_primitives17 = __toESM(require_primitives(), 1);
  var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
  var chevron_left_default = /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_primitives17.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_primitives17.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_primitives18 = __toESM(require_primitives(), 1);
  var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
  var chevron_right_small_default = /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_primitives18.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_primitives18.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_primitives19 = __toESM(require_primitives(), 1);
  var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
  var chevron_right_default = /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_primitives19.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_primitives19.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_primitives20 = __toESM(require_primitives(), 1);
  var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
  var chevron_up_default = /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_primitives20.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_primitives20.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_primitives21 = __toESM(require_primitives(), 1);
  var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
  var close_small_default = /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_primitives21.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_primitives21.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/close.mjs
  var import_primitives22 = __toESM(require_primitives(), 1);
  var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1);
  var close_default = /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(import_primitives22.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(import_primitives22.Path, { d: "m13.06 12 6.47-6.47-1.06-1.06L12 10.94 5.53 4.47 4.47 5.53 10.94 12l-6.47 6.47 1.06 1.06L12 13.06l6.47 6.47 1.06-1.06L13.06 12Z" }) });

  // packages/icons/build-module/library/cloud-upload.mjs
  var import_primitives23 = __toESM(require_primitives(), 1);
  var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
  var cloud_upload_default = /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(import_primitives23.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(import_primitives23.Path, { d: "M17.3 10.1C17.3 7.60001 15.2 5.70001 12.5 5.70001C10.3 5.70001 8.4 7.10001 7.9 9.00001H7.7C5.7 9.00001 4 10.7 4 12.8C4 14.9 5.7 16.6 7.7 16.6H9.5V15.2H7.7C6.5 15.2 5.5 14.1 5.5 12.9C5.5 11.7 6.5 10.5 7.7 10.5H9L9.3 9.40001C9.7 8.10001 11 7.20001 12.5 7.20001C14.3 7.20001 15.8 8.50001 15.8 10.1V11.4L17.1 11.6C17.9 11.7 18.5 12.5 18.5 13.4C18.5 14.4 17.7 15.2 16.8 15.2H14.5V16.6H16.7C18.5 16.6 19.9 15.1 19.9 13.3C20 11.7 18.8 10.4 17.3 10.1Z M14.1245 14.2426L15.1852 13.182L12.0032 10L8.82007 13.1831L9.88072 14.2438L11.25 12.8745V18H12.75V12.8681L14.1245 14.2426Z" }) });

  // packages/icons/build-module/library/cloud.mjs
  var import_primitives24 = __toESM(require_primitives(), 1);
  var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1);
  var cloud_default = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(import_primitives24.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(import_primitives24.Path, { d: "M17.3 10.1c0-2.5-2.1-4.4-4.8-4.4-2.2 0-4.1 1.4-4.6 3.3h-.2C5.7 9 4 10.7 4 12.8c0 2.1 1.7 3.8 3.7 3.8h9c1.8 0 3.2-1.5 3.2-3.3.1-1.6-1.1-2.9-2.6-3.2zm-.5 5.1h-9c-1.2 0-2.2-1.1-2.2-2.3s1-2.4 2.2-2.4h1.3l.3-1.1c.4-1.3 1.7-2.2 3.2-2.2 1.8 0 3.3 1.3 3.3 2.9v1.3l1.3.2c.8.1 1.4.9 1.4 1.8-.1 1-.9 1.8-1.8 1.8z" }) });

  // packages/icons/build-module/library/code.mjs
  var import_primitives25 = __toESM(require_primitives(), 1);
  var import_jsx_runtime25 = __toESM(require_jsx_runtime(), 1);
  var code_default = /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(import_primitives25.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(import_primitives25.Path, { d: "M20.8 10.7l-4.3-4.3-1.1 1.1 4.3 4.3c.1.1.1.3 0 .4l-4.3 4.3 1.1 1.1 4.3-4.3c.7-.8.7-1.9 0-2.6zM4.2 11.8l4.3-4.3-1-1-4.3 4.3c-.7.7-.7 1.8 0 2.5l4.3 4.3 1.1-1.1-4.3-4.3c-.2-.1-.2-.3-.1-.4z" }) });

  // packages/icons/build-module/library/cog.mjs
  var import_primitives26 = __toESM(require_primitives(), 1);
  var import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
  var cog_default = /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(import_primitives26.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(import_primitives26.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/color.mjs
  var import_primitives27 = __toESM(require_primitives(), 1);
  var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1);
  var color_default = /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(import_primitives27.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(import_primitives27.Path, { d: "M17.2 10.9c-.5-1-1.2-2.1-2.1-3.2-.6-.9-1.3-1.7-2.1-2.6L12 4l-1 1.1c-.6.9-1.3 1.7-2 2.6-.8 1.2-1.5 2.3-2 3.2-.6 1.2-1 2.2-1 3 0 3.4 2.7 6.1 6.1 6.1s6.1-2.7 6.1-6.1c0-.8-.3-1.8-1-3zm-5.1 7.6c-2.5 0-4.6-2.1-4.6-4.6 0-.3.1-1 .8-2.3.5-.9 1.1-1.9 2-3.1.7-.9 1.3-1.7 1.8-2.3.7.8 1.3 1.6 1.8 2.3.8 1.1 1.5 2.2 2 3.1.7 1.3.8 2 .8 2.3 0 2.5-2.1 4.6-4.6 4.6z" }) });

  // packages/icons/build-module/library/comment-author-avatar.mjs
  var import_primitives28 = __toESM(require_primitives(), 1);
  var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
  var comment_author_avatar_default = /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_primitives28.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(import_primitives28.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/comment.mjs
  var import_primitives29 = __toESM(require_primitives(), 1);
  var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1);
  var comment_default = /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(import_primitives29.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(import_primitives29.Path, { d: "M18 4H6c-1.1 0-2 .9-2 2v12.9c0 .6.5 1.1 1.1 1.1.3 0 .5-.1.8-.3L8.5 17H18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm.5 11c0 .3-.2.5-.5.5H7.9l-2.4 2.4V6c0-.3.2-.5.5-.5h12c.3 0 .5.2.5.5v9z" }) });

  // packages/icons/build-module/library/copy-small.mjs
  var import_primitives30 = __toESM(require_primitives(), 1);
  var import_jsx_runtime30 = __toESM(require_jsx_runtime(), 1);
  var copy_small_default = /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_primitives30.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_primitives30.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M5.625 5.5h9.75c.069 0 .125.056.125.125v9.75a.125.125 0 0 1-.125.125h-9.75a.125.125 0 0 1-.125-.125v-9.75c0-.069.056-.125.125-.125ZM4 5.625C4 4.728 4.728 4 5.625 4h9.75C16.273 4 17 4.728 17 5.625v9.75c0 .898-.727 1.625-1.625 1.625h-9.75A1.625 1.625 0 0 1 4 15.375v-9.75Zm14.5 11.656v-9H20v9C20 18.8 18.77 20 17.251 20H6.25v-1.5h11.001c.69 0 1.249-.528 1.249-1.219Z" }) });

  // packages/icons/build-module/library/desktop.mjs
  var import_primitives31 = __toESM(require_primitives(), 1);
  var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1);
  var desktop_default = /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_primitives31.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_primitives31.Path, { d: "M20.5 16h-.7V8c0-1.1-.9-2-2-2H6.2c-1.1 0-2 .9-2 2v8h-.7c-.8 0-1.5.7-1.5 1.5h20c0-.8-.7-1.5-1.5-1.5zM5.7 8c0-.3.2-.5.5-.5h11.6c.3 0 .5.2.5.5v7.6H5.7V8z" }) });

  // packages/icons/build-module/library/download.mjs
  var import_primitives32 = __toESM(require_primitives(), 1);
  var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
  var download_default = /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_primitives32.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_primitives32.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_primitives33 = __toESM(require_primitives(), 1);
  var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1);
  var drafts_default = /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_primitives33.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_primitives33.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-left.mjs
  var import_primitives34 = __toESM(require_primitives(), 1);
  var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
  var drawer_left_default = /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(import_primitives34.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(import_primitives34.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-2zM8.5 18.5H6c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h2.5v13zm10-.5c0 .3-.2.5-.5.5h-8v-13h8c.3 0 .5.2.5.5v12z" }) });

  // packages/icons/build-module/library/drawer-right.mjs
  var import_primitives35 = __toESM(require_primitives(), 1);
  var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1);
  var drawer_right_default = /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_primitives35.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_primitives35.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_primitives36 = __toESM(require_primitives(), 1);
  var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1);
  var envelope_default = /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(import_primitives36.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(import_primitives36.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_primitives37 = __toESM(require_primitives(), 1);
  var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1);
  var error_default = /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(import_primitives37.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(import_primitives37.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/external.mjs
  var import_primitives38 = __toESM(require_primitives(), 1);
  var import_jsx_runtime38 = __toESM(require_jsx_runtime(), 1);
  var external_default = /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(import_primitives38.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(import_primitives38.Path, { d: "M19.5 4.5h-7V6h4.44l-5.97 5.97 1.06 1.06L18 7.06v4.44h1.5v-7Zm-13 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3H17v3a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h3V5.5h-3Z" }) });

  // packages/icons/build-module/library/file.mjs
  var import_primitives39 = __toESM(require_primitives(), 1);
  var import_jsx_runtime39 = __toESM(require_jsx_runtime(), 1);
  var file_default = /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(import_primitives39.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(import_primitives39.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/flip-horizontal.mjs
  var import_primitives40 = __toESM(require_primitives(), 1);
  var import_jsx_runtime40 = __toESM(require_jsx_runtime(), 1);
  var flip_horizontal_default = /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(import_primitives40.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(import_primitives40.Path, { d: "M4 6v12c0 1.1.9 2 2 2h3v-1.5H6c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h3V4H6c-1.1 0-2 .9-2 2zm7.2 16h1.5V2h-1.5v20zM15 5.5h1.5V4H15v1.5zm3.5.5H20c0-1.1-.9-2-2-2v1.5c.3 0 .5.2.5.5zm0 10.5H20v-2h-1.5v2zm0-3.5H20v-2h-1.5v2zm-.5 5.5V20c1.1 0 2-.9 2-2h-1.5c0 .3-.2.5-.5.5zM15 20h1.5v-1.5H15V20zm3.5-10.5H20v-2h-1.5v2z" }) });

  // packages/icons/build-module/library/flip-vertical.mjs
  var import_primitives41 = __toESM(require_primitives(), 1);
  var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1);
  var flip_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_primitives41.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_primitives41.Path, { d: "M2 11.2v1.5h20v-1.5H2zM5.5 6c0-.3.2-.5.5-.5h12c.3 0 .5.2.5.5v3H20V6c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v3h1.5V6zm2 14h2v-1.5h-2V20zm3.5 0h2v-1.5h-2V20zm7-1.5V20c1.1 0 2-.9 2-2h-1.5c0 .3-.2.5-.5.5zm.5-2H20V15h-1.5v1.5zM5.5 18H4c0 1.1.9 2 2 2v-1.5c-.3 0-.5-.2-.5-.5zm0-3H4v1.5h1.5V15zm9 5h2v-1.5h-2V20z" }) });

  // packages/icons/build-module/library/footer.mjs
  var import_primitives42 = __toESM(require_primitives(), 1);
  var import_jsx_runtime42 = __toESM(require_jsx_runtime(), 1);
  var footer_default = /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_primitives42.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_primitives42.Path, { fillRule: "evenodd", d: "M18 5.5h-8v8h8.5V6a.5.5 0 00-.5-.5zm-9.5 8h-3V6a.5.5 0 01.5-.5h2.5v8zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z" }) });

  // packages/icons/build-module/library/format-list-bullets-rtl.mjs
  var import_primitives43 = __toESM(require_primitives(), 1);
  var import_jsx_runtime43 = __toESM(require_jsx_runtime(), 1);
  var format_list_bullets_rtl_default = /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(import_primitives43.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(import_primitives43.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_primitives44 = __toESM(require_primitives(), 1);
  var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1);
  var format_list_bullets_default = /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(import_primitives44.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(import_primitives44.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_primitives45 = __toESM(require_primitives(), 1);
  var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1);
  var funnel_default = /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(import_primitives45.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(import_primitives45.Path, { d: "M10 17.5H14V16H10V17.5ZM6 6V7.5H18V6H6ZM8 12.5H16V11H8V12.5Z" }) });

  // packages/icons/build-module/library/globe.mjs
  var import_primitives46 = __toESM(require_primitives(), 1);
  var import_jsx_runtime46 = __toESM(require_jsx_runtime(), 1);
  var globe_default = /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_primitives46.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(import_primitives46.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/header.mjs
  var import_primitives47 = __toESM(require_primitives(), 1);
  var import_jsx_runtime47 = __toESM(require_jsx_runtime(), 1);
  var header_default = /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(import_primitives47.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(import_primitives47.Path, { d: "M18.5 10.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/info.mjs
  var import_primitives48 = __toESM(require_primitives(), 1);
  var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1);
  var info_default = /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(import_primitives48.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(import_primitives48.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M5.5 12a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0ZM12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm.75 4v1.5h-1.5V8h1.5Zm0 8v-5h-1.5v5h1.5Z" }) });

  // packages/icons/build-module/library/keyboard.mjs
  var import_primitives49 = __toESM(require_primitives(), 1);
  var import_jsx_runtime49 = __toESM(require_jsx_runtime(), 1);
  var keyboard_default = /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(import_primitives49.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
    /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_primitives49.Path, { d: "m16 15.5h-8v-1.5h8zm-7.5-2.5h-2v-2h2zm3 0h-2v-2h2zm3 0h-2v-2h2zm3 0h-2v-2h2zm-9-3h-2v-2h2zm3 0h-2v-2h2zm3 0h-2v-2h2zm3 0h-2v-2h2z" }),
    /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(import_primitives49.Path, { d: "m18.5 6.5h-13a.5.5 0 0 0 -.5.5v9.5a.5.5 0 0 0 .5.5h13a.5.5 0 0 0 .5-.5v-9.5a.5.5 0 0 0 -.5-.5zm-13-1.5h13a2 2 0 0 1 2 2v9.5a2 2 0 0 1 -2 2h-13a2 2 0 0 1 -2-2v-9.5a2 2 0 0 1 2-2z" })
  ] });

  // packages/icons/build-module/library/layout.mjs
  var import_primitives50 = __toESM(require_primitives(), 1);
  var import_jsx_runtime50 = __toESM(require_jsx_runtime(), 1);
  var layout_default = /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_primitives50.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(import_primitives50.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/line-solid.mjs
  var import_primitives51 = __toESM(require_primitives(), 1);
  var import_jsx_runtime51 = __toESM(require_jsx_runtime(), 1);
  var line_solid_default = /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(import_primitives51.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(import_primitives51.Path, { d: "M5 11.25h14v1.5H5z" }) });

  // packages/icons/build-module/library/link.mjs
  var import_primitives52 = __toESM(require_primitives(), 1);
  var import_jsx_runtime52 = __toESM(require_jsx_runtime(), 1);
  var link_default = /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_primitives52.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_primitives52.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-view.mjs
  var import_primitives53 = __toESM(require_primitives(), 1);
  var import_jsx_runtime53 = __toESM(require_jsx_runtime(), 1);
  var list_view_default = /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_primitives53.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_primitives53.Path, { d: "M3 6h11v1.5H3V6Zm3.5 5.5h11V13h-11v-1.5ZM21 17H10v1.5h11V17Z" }) });

  // packages/icons/build-module/library/lock-small.mjs
  var import_primitives54 = __toESM(require_primitives(), 1);
  var import_jsx_runtime54 = __toESM(require_jsx_runtime(), 1);
  var lock_small_default = /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(import_primitives54.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(import_primitives54.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M15 11h-.2V9c0-1.5-1.2-2.8-2.8-2.8S9.2 7.5 9.2 9v2H9c-.6 0-1 .4-1 1v4c0 .6.4 1 1 1h6c.6 0 1-.4 1-1v-4c0-.6-.4-1-1-1zm-1.8 0h-2.5V9c0-.7.6-1.2 1.2-1.2s1.2.6 1.2 1.2v2z" }) });

  // packages/icons/build-module/library/mobile.mjs
  var import_primitives55 = __toESM(require_primitives(), 1);
  var import_jsx_runtime55 = __toESM(require_jsx_runtime(), 1);
  var mobile_default = /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(import_primitives55.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(import_primitives55.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_primitives56 = __toESM(require_primitives(), 1);
  var import_jsx_runtime56 = __toESM(require_jsx_runtime(), 1);
  var more_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(import_primitives56.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(import_primitives56.Path, { d: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z" }) });

  // packages/icons/build-module/library/navigation-overlay.mjs
  var import_primitives57 = __toESM(require_primitives(), 1);
  var import_jsx_runtime57 = __toESM(require_jsx_runtime(), 1);
  var navigation_overlay_default = /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_primitives57.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(import_primitives57.Path, { d: "M18.5 10a1.5 1.5 0 0 1 1.5 1.5v7a1.5 1.5 0 0 1-1.5 1.5h-7a1.5 1.5 0 0 1-1.5-1.5v-7a1.5 1.5 0 0 1 1.5-1.5zM16 4a2 2 0 0 1 2 2v2h-1.5V6a.5.5 0 0 0-.5-.5H6a.5.5 0 0 0-.5.5v3H8v1.5H5.5V16a.5.5 0 0 0 .5.5h2V18H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z" }) });

  // packages/icons/build-module/library/navigation.mjs
  var import_primitives58 = __toESM(require_primitives(), 1);
  var import_jsx_runtime58 = __toESM(require_jsx_runtime(), 1);
  var navigation_default = /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(import_primitives58.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(import_primitives58.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_primitives59 = __toESM(require_primitives(), 1);
  var import_jsx_runtime59 = __toESM(require_jsx_runtime(), 1);
  var next_default = /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(import_primitives59.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(import_primitives59.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_primitives60 = __toESM(require_primitives(), 1);
  var import_jsx_runtime60 = __toESM(require_jsx_runtime(), 1);
  var not_allowed_default = /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_primitives60.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_primitives60.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/page.mjs
  var import_primitives61 = __toESM(require_primitives(), 1);
  var import_jsx_runtime61 = __toESM(require_jsx_runtime(), 1);
  var page_default = /* @__PURE__ */ (0, import_jsx_runtime61.jsxs)(import_primitives61.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
    /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(import_primitives61.Path, { d: "M15.5 7.5h-7V9h7V7.5Zm-7 3.5h7v1.5h-7V11Zm7 3.5h-7V16h7v-1.5Z" }),
    /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(import_primitives61.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/pencil.mjs
  var import_primitives62 = __toESM(require_primitives(), 1);
  var import_jsx_runtime62 = __toESM(require_jsx_runtime(), 1);
  var pencil_default = /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(import_primitives62.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(import_primitives62.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_primitives63 = __toESM(require_primitives(), 1);
  var import_jsx_runtime63 = __toESM(require_jsx_runtime(), 1);
  var pending_default = /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(import_primitives63.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(import_primitives63.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/plugins.mjs
  var import_primitives64 = __toESM(require_primitives(), 1);
  var import_jsx_runtime64 = __toESM(require_jsx_runtime(), 1);
  var plugins_default = /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(import_primitives64.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(import_primitives64.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/plus.mjs
  var import_primitives65 = __toESM(require_primitives(), 1);
  var import_jsx_runtime65 = __toESM(require_jsx_runtime(), 1);
  var plus_default = /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_primitives65.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(import_primitives65.Path, { d: "M11 12.5V17.5H12.5V12.5H17.5V11H12.5V6H11V11H6V12.5H11Z" }) });

  // packages/icons/build-module/library/post.mjs
  var import_primitives66 = __toESM(require_primitives(), 1);
  var import_jsx_runtime66 = __toESM(require_jsx_runtime(), 1);
  var post_default = /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(import_primitives66.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(import_primitives66.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_primitives67 = __toESM(require_primitives(), 1);
  var import_jsx_runtime67 = __toESM(require_jsx_runtime(), 1);
  var previous_default = /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(import_primitives67.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(import_primitives67.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_primitives68 = __toESM(require_primitives(), 1);
  var import_jsx_runtime68 = __toESM(require_jsx_runtime(), 1);
  var published_default = /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(import_primitives68.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(import_primitives68.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/redo.mjs
  var import_primitives69 = __toESM(require_primitives(), 1);
  var import_jsx_runtime69 = __toESM(require_jsx_runtime(), 1);
  var redo_default = /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(import_primitives69.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(import_primitives69.Path, { d: "M15.6 6.5l-1.1 1 2.9 3.3H8c-.9 0-1.7.3-2.3.9-1.4 1.5-1.4 4.2-1.4 5.6v.2h1.5v-.3c0-1.1 0-3.5 1-4.5.3-.3.7-.5 1.3-.5h9.2L14.5 15l1.1 1.1 4.6-4.6-4.6-5z" }) });

  // packages/icons/build-module/library/reset.mjs
  var import_primitives70 = __toESM(require_primitives(), 1);
  var import_jsx_runtime70 = __toESM(require_jsx_runtime(), 1);
  var reset_default = /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_primitives70.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(import_primitives70.Path, { d: "M7 11.5h10V13H7z" }) });

  // packages/icons/build-module/library/rotate-left.mjs
  var import_primitives71 = __toESM(require_primitives(), 1);
  var import_jsx_runtime71 = __toESM(require_jsx_runtime(), 1);
  var rotate_left_default = /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(import_primitives71.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(import_primitives71.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_primitives72 = __toESM(require_primitives(), 1);
  var import_jsx_runtime72 = __toESM(require_jsx_runtime(), 1);
  var rotate_right_default = /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_primitives72.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(import_primitives72.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_primitives73 = __toESM(require_primitives(), 1);
  var import_jsx_runtime73 = __toESM(require_jsx_runtime(), 1);
  var scheduled_default = /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(import_primitives73.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(import_primitives73.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_primitives74 = __toESM(require_primitives(), 1);
  var import_jsx_runtime74 = __toESM(require_jsx_runtime(), 1);
  var search_default = /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_primitives74.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(import_primitives74.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_primitives75 = __toESM(require_primitives(), 1);
  var import_jsx_runtime75 = __toESM(require_jsx_runtime(), 1);
  var seen_default = /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_primitives75.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(import_primitives75.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/settings.mjs
  var import_primitives76 = __toESM(require_primitives(), 1);
  var import_jsx_runtime76 = __toESM(require_jsx_runtime(), 1);
  var settings_default = /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(import_primitives76.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: [
    /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(import_primitives76.Path, { d: "m19 7.5h-7.628c-.3089-.87389-1.1423-1.5-2.122-1.5-.97966 0-1.81309.62611-2.12197 1.5h-2.12803v1.5h2.12803c.30888.87389 1.14231 1.5 2.12197 1.5.9797 0 1.8131-.62611 2.122-1.5h7.628z" }),
    /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(import_primitives76.Path, { d: "m19 15h-2.128c-.3089-.8739-1.1423-1.5-2.122-1.5s-1.8131.6261-2.122 1.5h-7.628v1.5h7.628c.3089.8739 1.1423 1.5 2.122 1.5s1.8131-.6261 2.122-1.5h2.128z" })
  ] });

  // packages/icons/build-module/library/shadow.mjs
  var import_primitives77 = __toESM(require_primitives(), 1);
  var import_jsx_runtime77 = __toESM(require_jsx_runtime(), 1);
  var shadow_default = /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(import_primitives77.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(import_primitives77.Path, { d: "M12 8c-2.2 0-4 1.8-4 4s1.8 4 4 4 4-1.8 4-4-1.8-4-4-4zm0 6.5c-1.4 0-2.5-1.1-2.5-2.5s1.1-2.5 2.5-2.5 2.5 1.1 2.5 2.5-1.1 2.5-2.5 2.5zM12.8 3h-1.5v3h1.5V3zm-1.6 18h1.5v-3h-1.5v3zm6.8-9.8v1.5h3v-1.5h-3zm-12 0H3v1.5h3v-1.5zm9.7 5.6 2.1 2.1 1.1-1.1-2.1-2.1-1.1 1.1zM8.3 7.2 6.2 5.1 5.1 6.2l2.1 2.1 1.1-1.1zM5.1 17.8l1.1 1.1 2.1-2.1-1.1-1.1-2.1 2.1zM18.9 6.2l-1.1-1.1-2.1 2.1 1.1 1.1 2.1-2.1z" }) });

  // packages/icons/build-module/library/shuffle.mjs
  var import_primitives78 = __toESM(require_primitives(), 1);
  var import_jsx_runtime78 = __toESM(require_jsx_runtime(), 1);
  var shuffle_default = /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_primitives78.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(import_primitives78.Path, { d: "M17.192 6.75L15.47 5.03l1.06-1.06 3.537 3.53-3.537 3.53-1.06-1.06 1.723-1.72h-3.19c-.602 0-.993.202-1.28.498-.309.319-.538.792-.695 1.383-.13.488-.222 1.023-.296 1.508-.034.664-.116 1.413-.303 2.117-.193.721-.513 1.467-1.068 2.04-.575.594-1.359.954-2.357.954H4v-1.5h4.003c.601 0 .993-.202 1.28-.498.308-.319.538-.792.695-1.383.149-.557.216-1.093.288-1.662l.039-.31a9.653 9.653 0 0 1 .272-1.653c.193-.722.513-1.467 1.067-2.04.576-.594 1.36-.954 2.358-.954h3.19zM8.004 6.75c.8 0 1.46.23 1.988.628a6.24 6.24 0 0 0-.684 1.396 1.725 1.725 0 0 0-.024-.026c-.287-.296-.679-.498-1.28-.498H4v-1.5h4.003zM12.699 14.726c-.161.459-.38.94-.684 1.396.527.397 1.188.628 1.988.628h3.19l-1.722 1.72 1.06 1.06L20.067 16l-3.537-3.53-1.06 1.06 1.723 1.72h-3.19c-.602 0-.993-.202-1.28-.498a1.96 1.96 0 0 1-.024-.026z" }) });

  // packages/icons/build-module/library/sidebar.mjs
  var import_primitives79 = __toESM(require_primitives(), 1);
  var import_jsx_runtime79 = __toESM(require_jsx_runtime(), 1);
  var sidebar_default = /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(import_primitives79.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(import_primitives79.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.5zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z" }) });

  // packages/icons/build-module/library/square.mjs
  var import_primitives80 = __toESM(require_primitives(), 1);
  var import_jsx_runtime80 = __toESM(require_jsx_runtime(), 1);
  var square_default = /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(import_primitives80.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(import_primitives80.Path, { fill: "none", d: "M5.75 12.75V18.25H11.25M12.75 5.75H18.25V11.25", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "square" }) });

  // packages/icons/build-module/library/star-empty.mjs
  var import_primitives81 = __toESM(require_primitives(), 1);
  var import_jsx_runtime81 = __toESM(require_jsx_runtime(), 1);
  var star_empty_default = /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_primitives81.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(import_primitives81.Path, { fillRule: "evenodd", clipRule: "evenodd", d: "M9.706 8.646a.25.25 0 01-.188.137l-4.626.672a.25.25 0 00-.139.427l3.348 3.262a.25.25 0 01.072.222l-.79 4.607a.25.25 0 00.362.264l4.138-2.176a.25.25 0 01.233 0l4.137 2.175a.25.25 0 00.363-.263l-.79-4.607a.25.25 0 01.072-.222l3.347-3.262a.25.25 0 00-.139-.427l-4.626-.672a.25.25 0 01-.188-.137l-2.069-4.192a.25.25 0 00-.448 0L9.706 8.646zM12 7.39l-.948 1.921a1.75 1.75 0 01-1.317.957l-2.12.308 1.534 1.495c.412.402.6.982.503 1.55l-.362 2.11 1.896-.997a1.75 1.75 0 011.629 0l1.895.997-.362-2.11a1.75 1.75 0 01.504-1.55l1.533-1.495-2.12-.308a1.75 1.75 0 01-1.317-.957L12 7.39z" }) });

  // packages/icons/build-module/library/star-filled.mjs
  var import_primitives82 = __toESM(require_primitives(), 1);
  var import_jsx_runtime82 = __toESM(require_jsx_runtime(), 1);
  var star_filled_default = /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_primitives82.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(import_primitives82.Path, { d: "M11.776 4.454a.25.25 0 01.448 0l2.069 4.192a.25.25 0 00.188.137l4.626.672a.25.25 0 01.139.426l-3.348 3.263a.25.25 0 00-.072.222l.79 4.607a.25.25 0 01-.362.263l-4.138-2.175a.25.25 0 00-.232 0l-4.138 2.175a.25.25 0 01-.363-.263l.79-4.607a.25.25 0 00-.071-.222L4.754 9.881a.25.25 0 01.139-.426l4.626-.672a.25.25 0 00.188-.137l2.069-4.192z" }) });

  // packages/icons/build-module/library/styles.mjs
  var import_primitives83 = __toESM(require_primitives(), 1);
  var import_jsx_runtime83 = __toESM(require_jsx_runtime(), 1);
  var styles_default = /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_primitives83.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(import_primitives83.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_primitives84 = __toESM(require_primitives(), 1);
  var import_jsx_runtime84 = __toESM(require_jsx_runtime(), 1);
  var symbol_filled_default = /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(import_primitives84.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(import_primitives84.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_primitives85 = __toESM(require_primitives(), 1);
  var import_jsx_runtime85 = __toESM(require_jsx_runtime(), 1);
  var symbol_default = /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_primitives85.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_primitives85.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/tablet.mjs
  var import_primitives86 = __toESM(require_primitives(), 1);
  var import_jsx_runtime86 = __toESM(require_jsx_runtime(), 1);
  var tablet_default = /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(import_primitives86.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(import_primitives86.Path, { d: "M17 4H7c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm.5 14c0 .3-.2.5-.5.5H7c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h10c.3 0 .5.2.5.5v12zm-7.5-.5h4V16h-4v1.5z" }) });

  // packages/icons/build-module/library/trash.mjs
  var import_primitives87 = __toESM(require_primitives(), 1);
  var import_jsx_runtime87 = __toESM(require_jsx_runtime(), 1);
  var trash_default = /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_primitives87.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(import_primitives87.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/typography.mjs
  var import_primitives88 = __toESM(require_primitives(), 1);
  var import_jsx_runtime88 = __toESM(require_jsx_runtime(), 1);
  var typography_default = /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(import_primitives88.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(import_primitives88.Path, { d: "m8.6 7 3.9 10.8h-1.7l-1-2.8H5.7l-1 2.8H3L6.9 7h1.7Zm-2.4 6.6h3L7.7 9.3l-1.5 4.3ZM17.691 8.879c.473 0 .88.055 1.221.165.352.1.643.264.875.495.274.253.456.572.544.957.088.374.132.83.132 1.37v4.554c0 .274.033.472.099.593.077.11.198.166.363.166.11 0 .215-.028.313-.083.11-.055.237-.137.38-.247l.165.28a3.304 3.304 0 0 1-.71.446c-.23.11-.527.165-.89.165-.352 0-.639-.055-.858-.165-.22-.11-.386-.27-.495-.479-.1-.209-.149-.468-.149-.775-.286.462-.627.814-1.023 1.056-.396.242-.858.363-1.386.363-.462 0-.858-.088-1.188-.264a1.752 1.752 0 0 1-.742-.726 2.201 2.201 0 0 1-.248-1.056c0-.484.11-.875.33-1.172.22-.308.5-.556.841-.742.352-.187.721-.341 1.106-.462.396-.132.765-.253 1.106-.363.351-.121.637-.259.857-.413.232-.154.347-.357.347-.61V10.81c0-.396-.066-.71-.198-.941a1.05 1.05 0 0 0-.511-.511 1.763 1.763 0 0 0-.76-.149c-.253 0-.522.039-.808.116a1.165 1.165 0 0 0-.677.412 1.1 1.1 0 0 1 .595.396c.165.187.247.424.247.71 0 .307-.104.55-.313.726-.198.176-.451.263-.76.263-.34 0-.594-.104-.758-.313a1.231 1.231 0 0 1-.248-.759c0-.297.072-.539.214-.726.154-.187.352-.363.595-.528.264-.176.6-.324 1.006-.445.418-.121.88-.182 1.386-.182Zm.99 3.729a1.57 1.57 0 0 1-.528.462c-.231.121-.479.248-.742.38a5.377 5.377 0 0 0-.76.462c-.23.165-.423.38-.577.643-.154.264-.231.6-.231 1.007 0 .429.11.77.33 1.023.22.242.517.363.891.363.308 0 .594-.088.858-.264.275-.176.528-.44.759-.792v-3.284Z" }) });

  // packages/icons/build-module/library/undo.mjs
  var import_primitives89 = __toESM(require_primitives(), 1);
  var import_jsx_runtime89 = __toESM(require_jsx_runtime(), 1);
  var undo_default = /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(import_primitives89.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(import_primitives89.Path, { d: "M18.3 11.7c-.6-.6-1.4-.9-2.3-.9H6.7l2.9-3.3-1.1-1-4.5 5L8.5 16l1-1-2.7-2.7H16c.5 0 .9.2 1.3.5 1 1 1 3.4 1 4.5v.3h1.5v-.2c0-1.5 0-4.3-1.5-5.7z" }) });

  // packages/icons/build-module/library/unseen.mjs
  var import_primitives90 = __toESM(require_primitives(), 1);
  var import_jsx_runtime90 = __toESM(require_jsx_runtime(), 1);
  var unseen_default = /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(import_primitives90.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(import_primitives90.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/verse.mjs
  var import_primitives91 = __toESM(require_primitives(), 1);
  var import_jsx_runtime91 = __toESM(require_jsx_runtime(), 1);
  var verse_default = /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(import_primitives91.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(import_primitives91.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_primitives92 = __toESM(require_primitives(), 1);
  var import_jsx_runtime92 = __toESM(require_jsx_runtime(), 1);
  var video_default = /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(import_primitives92.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(import_primitives92.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/icons/build-module/library/wordpress.mjs
  var import_primitives93 = __toESM(require_primitives(), 1);
  var import_jsx_runtime93 = __toESM(require_jsx_runtime(), 1);
  var wordpress_default = /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(import_primitives93.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "-2 -2 24 24", fill: "currentColor", children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(import_primitives93.Path, { d: "M20 10c0-5.51-4.49-10-10-10C4.48 0 0 4.49 0 10c0 5.52 4.48 10 10 10 5.51 0 10-4.48 10-10zM7.78 15.37L4.37 6.22c.55-.02 1.17-.08 1.17-.08.5-.06.44-1.13-.06-1.11 0 0-1.45.11-2.37.11-.18 0-.37 0-.58-.01C4.12 2.69 6.87 1.11 10 1.11c2.33 0 4.45.87 6.05 2.34-.68-.11-1.65.39-1.65 1.58 0 .74.45 1.36.9 2.1.35.61.55 1.36.55 2.46 0 1.49-1.4 5-1.4 5l-3.03-8.37c.54-.02.82-.17.82-.17.5-.05.44-1.25-.06-1.22 0 0-1.44.12-2.38.12-.87 0-2.33-.12-2.33-.12-.5-.03-.56 1.2-.06 1.22l.92.08 1.26 3.41zM17.41 10c.24-.64.74-1.87.43-4.25.7 1.29 1.05 2.71 1.05 4.25 0 3.29-1.73 6.24-4.4 7.78.97-2.59 1.94-5.2 2.92-7.78zM6.1 18.09C3.12 16.65 1.11 13.53 1.11 10c0-1.3.23-2.48.72-3.59C3.25 10.3 4.67 14.2 6.1 18.09zm4.03-6.63l2.58 6.98c-.86.29-1.76.45-2.71.45-.79 0-1.57-.11-2.29-.33.81-2.38 1.62-4.74 2.42-7.1z" }) });

  // packages/editor/build-module/utils/get-template-part-icon.mjs
  function getTemplatePartIcon(areaOrIconName) {
    if ("header" === areaOrIconName) {
      return header_default;
    } else if ("footer" === areaOrIconName) {
      return footer_default;
    } else if ("sidebar" === areaOrIconName) {
      return sidebar_default;
    } else if ("navigation-overlay" === areaOrIconName) {
      return navigation_overlay_default;
    }
    return symbol_filled_default;
  }

  // packages/editor/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/editor"
  );

  // packages/editor/build-module/utils/get-template-info.mjs
  var EMPTY_OBJECT = {};
  var getTemplateInfo = (params) => {
    if (!params) {
      return EMPTY_OBJECT;
    }
    const { templateTypes, templateAreas, template: template2 } = params;
    const { description, slug, title, area } = template2;
    const { title: defaultTitle, description: defaultDescription } = Object.values(templateTypes).find((type) => type.slug === slug) ?? EMPTY_OBJECT;
    const templateTitle = typeof title === "string" ? title : title?.rendered;
    const templateDescription = typeof description === "string" ? description : description?.raw;
    const templateAreasWithIcon = templateAreas?.map((item) => ({
      ...item,
      icon: getTemplatePartIcon(item.icon)
    }));
    const templateIcon = templateAreasWithIcon?.find((item) => area === item.area)?.icon || layout_default;
    return {
      title: templateTitle && templateTitle !== slug ? templateTitle : defaultTitle || slug,
      description: templateDescription || defaultDescription,
      icon: templateIcon
    };
  };

  // 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(settings) {
    const typographySettings = settings?.typography ?? {};
    const layoutSettings = settings?.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, settings) {
    const { size: defaultSize } = preset;
    if (!defaultSize || "0" === defaultSize || false === preset?.fluid) {
      return defaultSize;
    }
    if (!isFluidTypographyEnabled(settings?.typography) && !isFluidTypographyEnabled(preset)) {
      return defaultSize;
    }
    const fluidTypographySettings = getFluidTypographyOptionsFromSettings(settings)?.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, settings) => getTypographyFontSizeValue(preset, settings),
      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(settings, blockName, presetPath = [], presetProperty = "slug", presetValueValue) {
    const orderedPresetsByOrigin = [
      blockName ? getValueFromObjectPath(settings, [
        "blocks",
        blockName,
        ...presetPath
      ]) : void 0,
      getValueFromObjectPath(settings, 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(
                settings,
                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(
      ([state2, legacyState]) => {
        if (Object.hasOwn(node, legacyState)) {
          if (normalized === node) {
            normalized = { ...node };
          }
          if (!Object.hasOwn(node, state2)) {
            normalized[state2] = 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(o4) {
    return Object.prototype.toString.call(o4) === "[object Object]";
  }
  function isPlainObject(o4) {
    var ctor, prot;
    if (isObject(o4) === false) return false;
    ctor = o4.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;
        }
      }
    );
  }

  // node_modules/memize/dist/index.js
  function memize(fn, options) {
    var size4 = 0;
    var head2;
    var tail;
    options = options || {};
    function memoized() {
      var node = head2, len2 = arguments.length, args, i3;
      searchCache: while (node) {
        if (node.args.length !== arguments.length) {
          node = node.next;
          continue;
        }
        for (i3 = 0; i3 < len2; i3++) {
          if (node.args[i3] !== arguments[i3]) {
            node = node.next;
            continue searchCache;
          }
        }
        if (node !== head2) {
          if (node === tail) {
            tail = node.prev;
          }
          node.prev.next = node.next;
          if (node.next) {
            node.next.prev = node.prev;
          }
          node.next = head2;
          node.prev = null;
          head2.prev = node;
          head2 = node;
        }
        return node.val;
      }
      args = new Array(len2);
      for (i3 = 0; i3 < len2; i3++) {
        args[i3] = arguments[i3];
      }
      node = {
        args,
        // Generate the result from original function
        val: fn.apply(null, args)
      };
      if (head2) {
        head2.prev = node;
        node.next = head2;
      } else {
        tail = node;
      }
      if (size4 === /** @type {MemizeOptions} */
      options.maxSize) {
        tail = /** @type {MemizeCacheNode} */
        tail.prev;
        tail.next = null;
      } else {
        size4++;
      }
      head2 = node;
      return node.val;
    }
    memoized.clear = function() {
      head2 = null;
      tail = null;
      size4 = 0;
    };
    return memoized;
  }

  // packages/global-styles-engine/build-module/utils/get-global-styles-changes.mjs
  var import_i18n = __toESM(require_i18n(), 1);
  var import_blocks = __toESM(require_blocks(), 1);
  var globalStylesChangesCache = /* @__PURE__ */ new Map();
  var EMPTY_ARRAY = [];
  var translationMap = {
    caption: (0, import_i18n.__)("Caption"),
    link: (0, import_i18n.__)("Link"),
    button: (0, import_i18n.__)("Button"),
    heading: (0, import_i18n.__)("Heading"),
    h1: (0, import_i18n.__)("H1"),
    h2: (0, import_i18n.__)("H2"),
    h3: (0, import_i18n.__)("H3"),
    h4: (0, import_i18n.__)("H4"),
    h5: (0, import_i18n.__)("H5"),
    h6: (0, import_i18n.__)("H6"),
    "settings.color": (0, import_i18n.__)("Color"),
    "settings.typography": (0, import_i18n.__)("Typography"),
    "settings.shadow": (0, import_i18n.__)("Shadow"),
    "settings.layout": (0, import_i18n.__)("Layout"),
    "styles.color": (0, import_i18n.__)("Colors"),
    "styles.spacing": (0, import_i18n.__)("Spacing"),
    "styles.background": (0, import_i18n.__)("Background"),
    "styles.typography": (0, import_i18n.__)("Typography")
  };
  var getBlockNames = memize(
    () => (0, import_blocks.getBlockTypes)().reduce(
      (accumulator, {
        name: name2,
        title
      }) => {
        accumulator[name2] = title;
        return accumulator;
      },
      {}
    )
  );
  var isObject2 = (obj) => obj !== null && typeof obj === "object";
  function getTranslation(key) {
    if (translationMap[key]) {
      return translationMap[key];
    }
    const keyArray = key.split(".");
    if (keyArray?.[0] === "blocks") {
      const blockName = getBlockNames()?.[keyArray[1]];
      return blockName || keyArray[1];
    }
    if (keyArray?.[0] === "elements") {
      return translationMap[keyArray[1]] || keyArray[1];
    }
    return void 0;
  }
  function deepCompare(changedObject, originalObject, parentPath = "") {
    if (!isObject2(changedObject) && !isObject2(originalObject)) {
      return changedObject !== originalObject ? parentPath.split(".").slice(0, 2).join(".") : void 0;
    }
    changedObject = isObject2(changedObject) ? changedObject : {};
    originalObject = isObject2(originalObject) ? originalObject : {};
    const allKeys = /* @__PURE__ */ new Set([
      ...Object.keys(changedObject),
      ...Object.keys(originalObject)
    ]);
    let diffs = [];
    for (const key of allKeys) {
      const path = parentPath ? parentPath + "." + key : key;
      const changedPath = deepCompare(
        changedObject[key],
        originalObject[key],
        path
      );
      if (changedPath) {
        diffs = diffs.concat(changedPath);
      }
    }
    return diffs;
  }
  function getGlobalStylesChangelist(next, previous) {
    const cacheKey2 = JSON.stringify({ next, previous });
    if (globalStylesChangesCache.has(cacheKey2)) {
      return globalStylesChangesCache.get(cacheKey2);
    }
    const changedValueTree = deepCompare(
      {
        styles: {
          background: next?.styles?.background,
          color: next?.styles?.color,
          typography: next?.styles?.typography,
          spacing: next?.styles?.spacing
        },
        blocks: next?.styles?.blocks,
        elements: next?.styles?.elements,
        settings: next?.settings
      },
      {
        styles: {
          background: previous?.styles?.background,
          color: previous?.styles?.color,
          typography: previous?.styles?.typography,
          spacing: previous?.styles?.spacing
        },
        blocks: previous?.styles?.blocks,
        elements: previous?.styles?.elements,
        settings: previous?.settings
      }
    );
    if (!changedValueTree || Array.isArray(changedValueTree) && !changedValueTree.length) {
      globalStylesChangesCache.set(cacheKey2, []);
      return [];
    }
    const changedValueArray = Array.isArray(changedValueTree) ? changedValueTree : [changedValueTree];
    const result = [...new Set(changedValueArray)].reduce((acc, curr) => {
      const translation = getTranslation(curr);
      if (translation) {
        acc.push([curr.split(".")[0], translation]);
      }
      return acc;
    }, []);
    globalStylesChangesCache.set(cacheKey2, result);
    return result;
  }
  function getGlobalStylesChanges(next, previous, options = {}) {
    let changeList = getGlobalStylesChangelist(next, previous);
    const changesLength = changeList.length;
    const { maxResults } = options;
    if (changesLength) {
      if (!!maxResults && changesLength > maxResults) {
        changeList = changeList.slice(0, maxResults);
      }
      return Object.entries(
        changeList.reduce((acc, curr) => {
          const group = acc[curr[0]] || [];
          if (!group.includes(curr[1])) {
            acc[curr[0]] = [...group, curr[1]];
          }
          return acc;
        }, {})
      ).map(([key, changeValues]) => {
        const changeValuesLength = changeValues.length;
        const joinedChangesValue = changeValues.join(
          /* translators: Used between list items, there is a space after the comma. */
          (0, import_i18n.__)(", ")
          // eslint-disable-line @wordpress/i18n-no-flanking-whitespace
        );
        switch (key) {
          case "blocks": {
            return (0, import_i18n.sprintf)(
              // translators: %s: a list of block names separated by a comma.
              (0, import_i18n._n)("%s block.", "%s blocks.", changeValuesLength),
              joinedChangesValue
            );
          }
          case "elements": {
            return (0, import_i18n.sprintf)(
              // translators: %s: a list of element names separated by a comma.
              (0, import_i18n._n)("%s element.", "%s elements.", changeValuesLength),
              joinedChangesValue
            );
          }
          case "settings": {
            return (0, import_i18n.sprintf)(
              // translators: %s: a list of theme.json setting labels separated by a comma.
              (0, import_i18n.__)("%s settings."),
              joinedChangesValue
            );
          }
          case "styles": {
            return (0, import_i18n.sprintf)(
              // translators: %s: a list of theme.json top-level styles labels separated by a comma.
              (0, import_i18n.__)("%s styles."),
              joinedChangesValue
            );
          }
          default: {
            return (0, import_i18n.sprintf)(
              // translators: %s: a list of global styles changes separated by a comma.
              (0, import_i18n.__)("%s."),
              joinedChangesValue
            );
          }
        }
      });
    }
    return EMPTY_ARRAY;
  }

  // packages/global-styles-engine/build-module/core/render.mjs
  var import_blocks2 = __toESM(require_blocks(), 1);
  var import_style_engine2 = __toESM(require_style_engine(), 1);
  var import_data3 = __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 r = { grad: 0.9, turn: 360, rad: 360 / (2 * Math.PI) };
  var t = function(r4) {
    return "string" == typeof r4 ? r4.length > 0 : "number" == typeof r4;
  };
  var n = function(r4, t4, n3) {
    return void 0 === t4 && (t4 = 0), void 0 === n3 && (n3 = Math.pow(10, t4)), Math.round(n3 * r4) / n3 + 0;
  };
  var e = function(r4, t4, n3) {
    return void 0 === t4 && (t4 = 0), void 0 === n3 && (n3 = 1), r4 > n3 ? n3 : r4 > t4 ? r4 : t4;
  };
  var u = function(r4) {
    return (r4 = isFinite(r4) ? r4 % 360 : 0) > 0 ? r4 : r4 + 360;
  };
  var a = function(r4) {
    return { r: e(r4.r, 0, 255), g: e(r4.g, 0, 255), b: e(r4.b, 0, 255), a: e(r4.a) };
  };
  var o = function(r4) {
    return { r: n(r4.r), g: n(r4.g), b: n(r4.b), a: n(r4.a, 3) };
  };
  var i = /^#([0-9a-f]{3,8})$/i;
  var s = function(r4) {
    var t4 = r4.toString(16);
    return t4.length < 2 ? "0" + t4 : t4;
  };
  var h = function(r4) {
    var t4 = r4.r, n3 = r4.g, e3 = r4.b, u3 = r4.a, a3 = Math.max(t4, n3, e3), o4 = a3 - Math.min(t4, n3, e3), i3 = o4 ? a3 === t4 ? (n3 - e3) / o4 : a3 === n3 ? 2 + (e3 - t4) / o4 : 4 + (t4 - n3) / o4 : 0;
    return { h: 60 * (i3 < 0 ? i3 + 6 : i3), s: a3 ? o4 / a3 * 100 : 0, v: a3 / 255 * 100, a: u3 };
  };
  var b = function(r4) {
    var t4 = r4.h, n3 = r4.s, e3 = r4.v, u3 = r4.a;
    t4 = t4 / 360 * 6, n3 /= 100, e3 /= 100;
    var a3 = Math.floor(t4), o4 = e3 * (1 - n3), i3 = e3 * (1 - (t4 - a3) * n3), s3 = e3 * (1 - (1 - t4 + a3) * n3), h3 = a3 % 6;
    return { r: 255 * [e3, i3, o4, o4, s3, e3][h3], g: 255 * [s3, e3, e3, i3, o4, o4][h3], b: 255 * [o4, o4, s3, e3, e3, i3][h3], a: u3 };
  };
  var g = function(r4) {
    return { h: u(r4.h), s: e(r4.s, 0, 100), l: e(r4.l, 0, 100), a: e(r4.a) };
  };
  var d = function(r4) {
    return { h: n(r4.h), s: n(r4.s), l: n(r4.l), a: n(r4.a, 3) };
  };
  var f = function(r4) {
    return b((n3 = (t4 = r4).s, { h: t4.h, s: (n3 *= ((e3 = t4.l) < 50 ? e3 : 100 - e3) / 100) > 0 ? 2 * n3 / (e3 + n3) * 100 : 0, v: e3 + n3, a: t4.a }));
    var t4, n3, e3;
  };
  var c = function(r4) {
    return { h: (t4 = h(r4)).h, s: (u3 = (200 - (n3 = t4.s)) * (e3 = t4.v) / 100) > 0 && u3 < 200 ? n3 * e3 / 100 / (u3 <= 100 ? u3 : 200 - u3) * 100 : 0, l: u3 / 2, a: t4.a };
    var t4, n3, e3, u3;
  };
  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(r4) {
    var t4 = i.exec(r4);
    return t4 ? (r4 = t4[1]).length <= 4 ? { r: parseInt(r4[0] + r4[0], 16), g: parseInt(r4[1] + r4[1], 16), b: parseInt(r4[2] + r4[2], 16), a: 4 === r4.length ? n(parseInt(r4[3] + r4[3], 16) / 255, 2) : 1 } : 6 === r4.length || 8 === r4.length ? { r: parseInt(r4.substr(0, 2), 16), g: parseInt(r4.substr(2, 2), 16), b: parseInt(r4.substr(4, 2), 16), a: 8 === r4.length ? n(parseInt(r4.substr(6, 2), 16) / 255, 2) : 1 } : null : null;
  }, "hex"], [function(r4) {
    var t4 = v.exec(r4) || m.exec(r4);
    return t4 ? t4[2] !== t4[4] || t4[4] !== t4[6] ? null : a({ r: Number(t4[1]) / (t4[2] ? 100 / 255 : 1), g: Number(t4[3]) / (t4[4] ? 100 / 255 : 1), b: Number(t4[5]) / (t4[6] ? 100 / 255 : 1), a: void 0 === t4[7] ? 1 : Number(t4[7]) / (t4[8] ? 100 : 1) }) : null;
  }, "rgb"], [function(t4) {
    var n3 = l.exec(t4) || p2.exec(t4);
    if (!n3) return null;
    var e3, u3, a3 = g({ h: (e3 = n3[1], u3 = n3[2], void 0 === u3 && (u3 = "deg"), Number(e3) * (r[u3] || 1)), s: Number(n3[3]), l: Number(n3[4]), a: void 0 === n3[5] ? 1 : Number(n3[5]) / (n3[6] ? 100 : 1) });
    return f(a3);
  }, "hsl"]], object: [[function(r4) {
    var n3 = r4.r, e3 = r4.g, u3 = r4.b, o4 = r4.a, i3 = void 0 === o4 ? 1 : o4;
    return t(n3) && t(e3) && t(u3) ? a({ r: Number(n3), g: Number(e3), b: Number(u3), a: Number(i3) }) : null;
  }, "rgb"], [function(r4) {
    var n3 = r4.h, e3 = r4.s, u3 = r4.l, a3 = r4.a, o4 = void 0 === a3 ? 1 : a3;
    if (!t(n3) || !t(e3) || !t(u3)) return null;
    var i3 = g({ h: Number(n3), s: Number(e3), l: Number(u3), a: Number(o4) });
    return f(i3);
  }, "hsl"], [function(r4) {
    var n3 = r4.h, a3 = r4.s, o4 = r4.v, i3 = r4.a, s3 = void 0 === i3 ? 1 : i3;
    if (!t(n3) || !t(a3) || !t(o4)) return null;
    var h3 = (function(r5) {
      return { h: u(r5.h), s: e(r5.s, 0, 100), v: e(r5.v, 0, 100), a: e(r5.a) };
    })({ h: Number(n3), s: Number(a3), v: Number(o4), a: Number(s3) });
    return b(h3);
  }, "hsv"]] };
  var N = function(r4, t4) {
    for (var n3 = 0; n3 < t4.length; n3++) {
      var e3 = t4[n3][0](r4);
      if (e3) return [e3, t4[n3][1]];
    }
    return [null, void 0];
  };
  var x = function(r4) {
    return "string" == typeof r4 ? N(r4.trim(), y.string) : "object" == typeof r4 && null !== r4 ? N(r4, y.object) : [null, void 0];
  };
  var M = function(r4, t4) {
    var n3 = c(r4);
    return { h: n3.h, s: e(n3.s + 100 * t4, 0, 100), l: n3.l, a: n3.a };
  };
  var H = function(r4) {
    return (299 * r4.r + 587 * r4.g + 114 * r4.b) / 1e3 / 255;
  };
  var $ = function(r4, t4) {
    var n3 = c(r4);
    return { h: n3.h, s: n3.s, l: e(n3.l + 100 * t4, 0, 100), a: n3.a };
  };
  var j = (function() {
    function r4(r5) {
      this.parsed = x(r5)[0], this.rgba = this.parsed || { r: 0, g: 0, b: 0, a: 1 };
    }
    return r4.prototype.isValid = function() {
      return null !== this.parsed;
    }, r4.prototype.brightness = function() {
      return n(H(this.rgba), 2);
    }, r4.prototype.isDark = function() {
      return H(this.rgba) < 0.5;
    }, r4.prototype.isLight = function() {
      return H(this.rgba) >= 0.5;
    }, r4.prototype.toHex = function() {
      return r5 = o(this.rgba), t4 = r5.r, e3 = r5.g, u3 = r5.b, i3 = (a3 = r5.a) < 1 ? s(n(255 * a3)) : "", "#" + s(t4) + s(e3) + s(u3) + i3;
      var r5, t4, e3, u3, a3, i3;
    }, r4.prototype.toRgb = function() {
      return o(this.rgba);
    }, r4.prototype.toRgbString = function() {
      return r5 = o(this.rgba), t4 = r5.r, n3 = r5.g, e3 = r5.b, (u3 = r5.a) < 1 ? "rgba(" + t4 + ", " + n3 + ", " + e3 + ", " + u3 + ")" : "rgb(" + t4 + ", " + n3 + ", " + e3 + ")";
      var r5, t4, n3, e3, u3;
    }, r4.prototype.toHsl = function() {
      return d(c(this.rgba));
    }, r4.prototype.toHslString = function() {
      return r5 = d(c(this.rgba)), t4 = r5.h, n3 = r5.s, e3 = r5.l, (u3 = r5.a) < 1 ? "hsla(" + t4 + ", " + n3 + "%, " + e3 + "%, " + u3 + ")" : "hsl(" + t4 + ", " + n3 + "%, " + e3 + "%)";
      var r5, t4, n3, e3, u3;
    }, r4.prototype.toHsv = function() {
      return r5 = h(this.rgba), { h: n(r5.h), s: n(r5.s), v: n(r5.v), a: n(r5.a, 3) };
      var r5;
    }, r4.prototype.invert = function() {
      return w({ r: 255 - (r5 = this.rgba).r, g: 255 - r5.g, b: 255 - r5.b, a: r5.a });
      var r5;
    }, r4.prototype.saturate = function(r5) {
      return void 0 === r5 && (r5 = 0.1), w(M(this.rgba, r5));
    }, r4.prototype.desaturate = function(r5) {
      return void 0 === r5 && (r5 = 0.1), w(M(this.rgba, -r5));
    }, r4.prototype.grayscale = function() {
      return w(M(this.rgba, -1));
    }, r4.prototype.lighten = function(r5) {
      return void 0 === r5 && (r5 = 0.1), w($(this.rgba, r5));
    }, r4.prototype.darken = function(r5) {
      return void 0 === r5 && (r5 = 0.1), w($(this.rgba, -r5));
    }, r4.prototype.rotate = function(r5) {
      return void 0 === r5 && (r5 = 15), this.hue(this.hue() + r5);
    }, r4.prototype.alpha = function(r5) {
      return "number" == typeof r5 ? w({ r: (t4 = this.rgba).r, g: t4.g, b: t4.b, a: r5 }) : n(this.rgba.a, 3);
      var t4;
    }, r4.prototype.hue = function(r5) {
      var t4 = c(this.rgba);
      return "number" == typeof r5 ? w({ h: r5, s: t4.s, l: t4.l, a: t4.a }) : n(t4.h);
    }, r4.prototype.isEqual = function(r5) {
      return this.toHex() === w(r5).toHex();
    }, r4;
  })();
  var w = function(r4) {
    return r4 instanceof j ? r4 : new j(r4);
  };
  var S = [];
  var k = function(r4) {
    r4.forEach(function(r5) {
      S.indexOf(r5) < 0 && (r5(j, y), S.push(r5));
    });
  };

  // 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(str3) {
    return str3.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, settings, blockName) => {
    if (blockName !== "core/paragraph") {
      return featureDeclarations;
    }
    const blockSettings = settings?.blocks?.["core/paragraph"];
    const textIndentSetting = blockSettings?.typography?.textIndent ?? settings?.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, settings) => {
    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 = {
            ...settings?.dimensions?.dimensionSizes ?? {},
            ...settings?.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_blocks2.__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
          }
        ];
      }
    );
  }
  function getElementStylesByName(styleNode, responsiveMediaQueries) {
    const elementStylesByName = { ...styleNode?.elements ?? {} };
    Object.keys(responsiveMediaQueries).forEach((breakpointKey) => {
      Object.entries(styleNode?.[breakpointKey]?.elements ?? {}).forEach(
        ([elementName, styles]) => {
          elementStylesByName[elementName] = {
            ...elementStylesByName[elementName] ?? {},
            [breakpointKey]: styles
          };
        }
      );
    });
    return elementStylesByName;
  }
  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_blocks2.__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(
                getElementStylesByName(
                  typedVariation,
                  responsiveMediaQueries
                )
              ).forEach(([element, elementStyles]) => {
                if (elementStyles && import_blocks2.__EXPERIMENTAL_ELEMENTS[element]) {
                  variationNodesToAdd.push({
                    styles: elementStyles,
                    selector: scopeSelector(
                      variationSelector,
                      import_blocks2.__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(
                    getElementStylesByName(
                      variationBlockStyles,
                      responsiveMediaQueries
                    )
                  ).forEach(
                    ([
                      variationBlockElement,
                      variationBlockElementStyles
                    ]) => {
                      if (variationBlockElementStyles && import_blocks2.__EXPERIMENTAL_ELEMENTS[variationBlockElement]) {
                        variationNodesToAdd.push({
                          styles: variationBlockElementStyles,
                          selector: scopeSelector(
                            variationBlockSelector,
                            import_blocks2.__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(
          getElementStylesByName(typedNode, responsiveMediaQueries)
        ).forEach(([elementName, value]) => {
          if (typeof blockSelectors !== "string" && value && blockSelectors?.[blockName] && import_blocks2.__EXPERIMENTAL_ELEMENTS[elementName]) {
            nodes.push({
              styles: value,
              selector: blockSelectors[blockName]?.selector.split(",").map((sel) => {
                const elementSelectors = import_blocks2.__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_data3.select)(import_blocks2.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_blocks2.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_blocks2.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(
      (state2) => !!state2 && state2 !== 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 slice2 = getStyleForState(layerObject, selectedState);
    return slice2 && typeof slice2 === "object" && !Array.isArray(slice2) ? slice2 : 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 memo = /* @__PURE__ */ new WeakMap();
  function resolveStyle(globalStyles, context = {}) {
    const styleData = globalStyles?.styles;
    if (!styleData || typeof styleData !== "object") {
      return computeResolvedStyle(globalStyles, context);
    }
    let byLinks = memo.get(styleData);
    if (!byLinks) {
      byLinks = /* @__PURE__ */ new WeakMap();
      memo.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_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/global-styles-engine"
  );

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

  // packages/global-styles-engine/build-module/preview-state-styles.mjs
  function generatePreviewStateStyles(stateStyles, blockName) {
    if (!stateStyles || !blockName) {
      return "";
    }
    const previewConfig = {
      settings: {},
      // Empty settings to satisfy the config structure
      styles: {
        blocks: {
          [blockName]: stateStyles
        }
      }
    };
    try {
      const [generatedStyles] = generateGlobalStyles(previewConfig, []);
      return generatedStyles.map((style) => style.css).join("\n");
    } catch {
      return "";
    }
  }

  // packages/editor/build-module/utils/device-type.mjs
  var { getViewportBreakpoints: getViewportBreakpoints2, getViewportBreakpointValueInPixels: getViewportBreakpointValueInPixels2 } = unlock(
    privateApis
  );
  var VIEWPORT_KEY_BY_DEVICE_TYPE = {
    Tablet: "tablet",
    Mobile: "mobile"
  };
  var DESKTOP_DEVICE_TYPE = "Desktop";
  var TABLET_DEVICE_TYPE = "Tablet";
  var MOBILE_DEVICE_TYPE = "Mobile";
  var DEVICE_PREVIEW_WIDTH_OFFSET = 1;
  var VIEWPORT_STATE_BY_DEVICE_TYPE = {
    Desktop: "default",
    Tablet: "@tablet",
    Mobile: "@mobile"
  };
  function getDeviceTypeByCanvasWidth(canvasWidth2, viewportSettings) {
    const width = getViewportBreakpointValueInPixels2(canvasWidth2);
    const breakpoints = getViewportBreakpoints2(viewportSettings);
    if (width && width <= getViewportBreakpointValueInPixels2(breakpoints.mobile)) {
      return MOBILE_DEVICE_TYPE;
    }
    if (width && width <= getViewportBreakpointValueInPixels2(breakpoints.tablet)) {
      return TABLET_DEVICE_TYPE;
    }
    return DESKTOP_DEVICE_TYPE;
  }
  function getCanvasWidthByDeviceType(deviceType, viewportSettings) {
    const viewportKey = VIEWPORT_KEY_BY_DEVICE_TYPE[deviceType];
    if (!viewportKey) {
      return void 0;
    }
    const breakpoints = getViewportBreakpoints2(viewportSettings);
    const width = getViewportBreakpointValueInPixels2(
      breakpoints[viewportKey]
    );
    if (width === void 0) {
      return void 0;
    }
    let lowerBreakpoint = 0;
    if (deviceType === TABLET_DEVICE_TYPE) {
      lowerBreakpoint = getViewportBreakpointValueInPixels2(breakpoints.mobile) ?? 0;
    }
    const offset4 = Math.min(
      DEVICE_PREVIEW_WIDTH_OFFSET,
      (width - lowerBreakpoint) / 2
    );
    return width - offset4;
  }

  // packages/editor/build-module/store/selectors.mjs
  var EMPTY_OBJECT2 = {};
  var hasEditorUndo = (0, import_data4.createRegistrySelector)((select9) => () => {
    return select9(import_core_data.store).hasUndo();
  });
  var hasEditorRedo = (0, import_data4.createRegistrySelector)((select9) => () => {
    return select9(import_core_data.store).hasRedo();
  });
  function isEditedPostNew(state2) {
    return getCurrentPost(state2).status === "auto-draft";
  }
  function hasChangedContent(state2) {
    const edits = getPostEdits(state2);
    return "content" in edits;
  }
  var isEditedPostDirty = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      const postType2 = getCurrentPostType(state2);
      const postId2 = getCurrentPostId(state2);
      return select9(import_core_data.store).hasEditsForEntityRecord(
        "postType",
        postType2,
        postId2
      );
    }
  );
  var hasNonPostEntityChanges = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      const dirtyEntityRecords = select9(import_core_data.store).__experimentalGetDirtyEntityRecords();
      const { type, id } = getCurrentPost(state2);
      return dirtyEntityRecords.some(
        (entityRecord) => entityRecord.kind !== "postType" || entityRecord.name !== type || entityRecord.key !== id
      );
    }
  );
  function isCleanNewPost(state2) {
    return !isEditedPostDirty(state2) && isEditedPostNew(state2);
  }
  var getCurrentPost = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      const postId2 = getCurrentPostId(state2);
      const postType2 = getCurrentPostType(state2);
      const post2 = select9(import_core_data.store).getRawEntityRecord(
        "postType",
        postType2,
        postId2
      );
      if (post2) {
        return post2;
      }
      return EMPTY_OBJECT2;
    }
  );
  function getCurrentPostType(state2) {
    return state2.postType;
  }
  function getCurrentPostId(state2) {
    return state2.postId;
  }
  function getCurrentTemplateId(state2) {
    return state2.templateId;
  }
  function getCurrentPostRevisionsCount(state2) {
    return getCurrentPost(state2)._links?.["version-history"]?.[0]?.count ?? 0;
  }
  function getCurrentPostLastRevisionId(state2) {
    return getCurrentPost(state2)._links?.["predecessor-version"]?.[0]?.id ?? null;
  }
  var getPostEdits = (0, import_data4.createRegistrySelector)((select9) => (state2) => {
    const postType2 = getCurrentPostType(state2);
    const postId2 = getCurrentPostId(state2);
    return select9(import_core_data.store).getEntityRecordEdits(
      "postType",
      postType2,
      postId2
    ) || EMPTY_OBJECT2;
  });
  function getCurrentPostAttribute(state2, attributeName) {
    switch (attributeName) {
      case "type":
        return getCurrentPostType(state2);
      case "id":
        return getCurrentPostId(state2);
      default:
        const post2 = getCurrentPost(state2);
        if (!post2.hasOwnProperty(attributeName)) {
          break;
        }
        return getPostRawValue(post2[attributeName]);
    }
  }
  var getNestedEditedPostProperty = (0, import_data4.createSelector)(
    (state2, attributeName) => {
      const edits = getPostEdits(state2);
      if (!edits.hasOwnProperty(attributeName)) {
        return getCurrentPostAttribute(state2, attributeName);
      }
      return {
        ...getCurrentPostAttribute(state2, attributeName),
        ...edits[attributeName]
      };
    },
    (state2, attributeName) => [
      getCurrentPostAttribute(state2, attributeName),
      getPostEdits(state2)[attributeName]
    ]
  );
  function getEditedPostAttribute(state2, attributeName) {
    switch (attributeName) {
      case "content":
        return getEditedPostContent(state2);
    }
    const edits = getPostEdits(state2);
    if (!edits.hasOwnProperty(attributeName)) {
      return getCurrentPostAttribute(state2, attributeName);
    }
    if (EDIT_MERGE_PROPERTIES.has(attributeName)) {
      return getNestedEditedPostProperty(state2, attributeName);
    }
    return edits[attributeName];
  }
  var getAutosaveAttribute = (0, import_data4.createRegistrySelector)(
    (select9) => (state2, attributeName) => {
      if (!AUTOSAVE_PROPERTIES.includes(attributeName) && attributeName !== "preview_link") {
        return;
      }
      const postType2 = getCurrentPostType(state2);
      const postId2 = getCurrentPostId(state2);
      const currentUserId = select9(import_core_data.store).getCurrentUser()?.id;
      const autosave2 = select9(import_core_data.store).getAutosave(
        postType2,
        postId2,
        currentUserId
      );
      if (autosave2) {
        return getPostRawValue(autosave2[attributeName]);
      }
    }
  );
  function getEditedPostVisibility(state2) {
    const status = getEditedPostAttribute(state2, "status");
    if (status === "private") {
      return "private";
    }
    const password = getEditedPostAttribute(state2, "password");
    if (password) {
      return "password";
    }
    return "public";
  }
  function isCurrentPostPending(state2) {
    return getCurrentPost(state2).status === "pending";
  }
  function isCurrentPostPublished(state2, currentPost) {
    const post2 = currentPost || getCurrentPost(state2);
    return ["publish", "private"].indexOf(post2.status) !== -1 || post2.status === "future" && !(0, import_date.isInTheFuture)(
      new Date(Number((0, import_date.getDate)(post2.date)) - ONE_MINUTE_IN_MS)
    );
  }
  function isCurrentPostScheduled(state2) {
    return getCurrentPost(state2).status === "future" && !isCurrentPostPublished(state2);
  }
  function isEditedPostPublishable(state2) {
    const post2 = getCurrentPost(state2);
    if (post2.type === ATTACHMENT_POST_TYPE) {
      return isEditedPostDirty(state2);
    }
    return isEditedPostDirty(state2) || ["publish", "private", "future"].indexOf(post2.status) === -1;
  }
  function isEditedPostSaveable(state2) {
    if (isSavingPost(state2)) {
      return false;
    }
    return !!getEditedPostAttribute(state2, "title") || !!getEditedPostAttribute(state2, "excerpt") || !isEditedPostEmpty(state2);
  }
  var isEditedPostEmpty = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      const postId2 = getCurrentPostId(state2);
      const postType2 = getCurrentPostType(state2);
      const record = select9(import_core_data.store).getEditedEntityRecord(
        "postType",
        postType2,
        postId2
      );
      if (typeof record.content !== "function") {
        return !record.content;
      }
      const blocks = getEditedPostAttribute(state2, "blocks");
      if (blocks.length === 0) {
        return true;
      }
      if (blocks.length > 1) {
        return false;
      }
      const blockName = blocks[0].name;
      if (blockName !== (0, import_blocks3.getDefaultBlockName)() && blockName !== (0, import_blocks3.getFreeformContentHandlerName)()) {
        return false;
      }
      return !getEditedPostContent(state2);
    }
  );
  var isEditedPostAutosaveable = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      if (!isEditedPostSaveable(state2)) {
        return false;
      }
      if (isPostAutosavingLocked(state2)) {
        return false;
      }
      const postType2 = getCurrentPostType(state2);
      const postTypeObject = select9(import_core_data.store).getPostType(postType2);
      if (!postTypeObject?.supports?.autosave) {
        return false;
      }
      const postId2 = getCurrentPostId(state2);
      const hasFetchedAutosave = select9(import_core_data.store).hasFetchedAutosaves(
        postType2,
        postId2
      );
      const currentUserId = select9(import_core_data.store).getCurrentUser()?.id;
      const autosave2 = select9(import_core_data.store).getAutosave(
        postType2,
        postId2,
        currentUserId
      );
      if (!hasFetchedAutosave) {
        return false;
      }
      if (!autosave2) {
        return true;
      }
      if (hasChangedContent(state2)) {
        return true;
      }
      return ["title", "excerpt", "meta"].some(
        (field) => getPostRawValue(autosave2[field]) !== getEditedPostAttribute(state2, field)
      );
    }
  );
  function isEditedPostBeingScheduled(state2) {
    const date = getEditedPostAttribute(state2, "date");
    const checkedDate = new Date(
      Number((0, import_date.getDate)(date)) - ONE_MINUTE_IN_MS
    );
    return (0, import_date.isInTheFuture)(checkedDate);
  }
  function isEditedPostDateFloating(state2) {
    const date = getEditedPostAttribute(state2, "date");
    const modified = getEditedPostAttribute(state2, "modified");
    const status = getCurrentPost(state2).status;
    if (status === "draft" || status === "auto-draft" || status === "pending") {
      return date === modified || date === null;
    }
    return false;
  }
  function isDeletingPost(state2) {
    return !!state2.deleting.pending;
  }
  function isSavingPost(state2) {
    return !!state2.saving.pending;
  }
  var isSavingNonPostEntityChanges = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      const entitiesBeingSaved = select9(import_core_data.store).__experimentalGetEntitiesBeingSaved();
      const { type, id } = getCurrentPost(state2);
      return entitiesBeingSaved.some(
        (entityRecord) => entityRecord.kind !== "postType" || entityRecord.name !== type || entityRecord.key !== id
      );
    }
  );
  var didPostSaveRequestSucceed = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      const postType2 = getCurrentPostType(state2);
      const postId2 = getCurrentPostId(state2);
      return !select9(import_core_data.store).getLastEntitySaveError(
        "postType",
        postType2,
        postId2
      );
    }
  );
  var didPostSaveRequestFail = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      const postType2 = getCurrentPostType(state2);
      const postId2 = getCurrentPostId(state2);
      return !!select9(import_core_data.store).getLastEntitySaveError(
        "postType",
        postType2,
        postId2
      );
    }
  );
  function isAutosavingPost(state2) {
    return isSavingPost(state2) && Boolean(state2.saving.options?.isAutosave);
  }
  function isPreviewingPost(state2) {
    return isSavingPost(state2) && Boolean(state2.saving.options?.isPreview);
  }
  function getEditedPostPreviewLink(state2) {
    if (state2.saving.pending || isSavingPost(state2)) {
      return;
    }
    let previewLink = getAutosaveAttribute(state2, "preview_link");
    if (!previewLink || "draft" === getCurrentPost(state2).status) {
      previewLink = getEditedPostAttribute(state2, "link");
      if (previewLink) {
        previewLink = (0, import_url.addQueryArgs)(previewLink, { preview: true });
      }
    }
    const featuredImageId = getEditedPostAttribute(state2, "featured_media");
    if (previewLink && featuredImageId) {
      return (0, import_url.addQueryArgs)(previewLink, { _thumbnail_id: featuredImageId });
    }
    return previewLink;
  }
  var getSuggestedPostFormat = (0, import_data4.createRegistrySelector)(
    (select9) => () => {
      const blocks = select9(import_block_editor2.store).getBlocks();
      if (blocks.length > 2) {
        return null;
      }
      let name2;
      if (blocks.length === 1) {
        name2 = blocks[0].name;
        if (name2 === "core/embed") {
          const provider = blocks[0].attributes?.providerNameSlug;
          if (["youtube", "vimeo"].includes(provider)) {
            name2 = "core/video";
          } else if (["spotify", "soundcloud"].includes(provider)) {
            name2 = "core/audio";
          }
        }
      }
      if (blocks.length === 2 && blocks[1].name === "core/paragraph") {
        name2 = blocks[0].name;
      }
      switch (name2) {
        case "core/image":
          return "image";
        case "core/quote":
        case "core/pullquote":
          return "quote";
        case "core/gallery":
          return "gallery";
        case "core/video":
          return "video";
        case "core/audio":
          return "audio";
        default:
          return null;
      }
    }
  );
  var getEditedPostContent = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      const postId2 = getCurrentPostId(state2);
      const postType2 = getCurrentPostType(state2);
      const record = select9(import_core_data.store).getEditedEntityRecord(
        "postType",
        postType2,
        postId2
      );
      if (record) {
        if (typeof record.content === "function") {
          return record.content(record);
        } else if (record.blocks) {
          return (0, import_blocks3.__unstableSerializeAndClean)(record.blocks);
        } else if (record.content) {
          return record.content;
        }
      }
      return "";
    }
  );
  function isPublishingPost(state2) {
    return isSavingPost(state2) && !isCurrentPostPublished(state2) && getEditedPostAttribute(state2, "status") === "publish";
  }
  function isPermalinkEditable(state2) {
    const permalinkTemplate = getEditedPostAttribute(
      state2,
      "permalink_template"
    );
    return PERMALINK_POSTNAME_REGEX.test(permalinkTemplate);
  }
  function getPermalink(state2) {
    const permalinkParts = getPermalinkParts(state2);
    if (!permalinkParts) {
      return null;
    }
    const { prefix: prefix2, postName, suffix } = permalinkParts;
    if (isPermalinkEditable(state2)) {
      return prefix2 + postName + suffix;
    }
    return prefix2;
  }
  function getEditedPostSlug(state2) {
    return getEditedPostAttribute(state2, "slug") || (0, import_url.cleanForSlug)(getEditedPostAttribute(state2, "title")) || getCurrentPostId(state2);
  }
  function getPermalinkParts(state2) {
    const permalinkTemplate = getEditedPostAttribute(
      state2,
      "permalink_template"
    );
    if (!permalinkTemplate) {
      return null;
    }
    const postName = getEditedPostAttribute(state2, "slug") || getEditedPostAttribute(state2, "generated_slug");
    const [prefix2, suffix] = permalinkTemplate.split(
      PERMALINK_POSTNAME_REGEX
    );
    return {
      prefix: prefix2,
      postName,
      suffix
    };
  }
  function isPostLocked(state2) {
    return state2.postLock.isLocked;
  }
  function isPostSavingLocked(state2) {
    return Object.keys(state2.postSavingLock).length > 0;
  }
  function isPostAutosavingLocked(state2) {
    return Object.keys(state2.postAutosavingLock).length > 0;
  }
  function isPostLockTakeover(state2) {
    return state2.postLock.isTakeover;
  }
  function getPostLockUser(state2) {
    return state2.postLock.user;
  }
  function getActivePostLock(state2) {
    return state2.postLock.activePostLock;
  }
  function canUserUseUnfilteredHTML(state2) {
    return Boolean(
      getCurrentPost(state2)._links?.hasOwnProperty(
        "wp:action-unfiltered-html"
      )
    );
  }
  var isPublishSidebarEnabled = (0, import_data4.createRegistrySelector)(
    (select9) => () => !!select9(import_preferences.store).get("core", "isPublishSidebarEnabled")
  );
  var getEditorBlocks = (0, import_data4.createSelector)(
    (state2) => {
      return getEditedPostAttribute(state2, "blocks") || (0, import_blocks3.parse)(getEditedPostContent(state2));
    },
    (state2) => [
      getEditedPostAttribute(state2, "blocks"),
      getEditedPostContent(state2)
    ]
  );
  function isEditorPanelRemoved(state2, panelName) {
    return state2.removedPanels.includes(panelName);
  }
  var isEditorPanelEnabled = (0, import_data4.createRegistrySelector)(
    (select9) => (state2, panelName) => {
      const inactivePanels = select9(import_preferences.store).get(
        "core",
        "inactivePanels"
      );
      return !isEditorPanelRemoved(state2, panelName) && !inactivePanels?.includes(panelName);
    }
  );
  var isEditorPanelOpened = (0, import_data4.createRegistrySelector)(
    (select9) => (state2, panelName) => {
      const openPanels = select9(import_preferences.store).get(
        "core",
        "openPanels"
      );
      return !!openPanels?.includes(panelName);
    }
  );
  function getEditorSelectionStart(state2) {
    (0, import_deprecated.default)("select('core/editor').getEditorSelectionStart", {
      since: "5.8",
      alternative: "select('core/editor').getEditorSelection"
    });
    return getEditedPostAttribute(state2, "selection")?.selectionStart;
  }
  function getEditorSelectionEnd(state2) {
    (0, import_deprecated.default)("select('core/editor').getEditorSelectionStart", {
      since: "5.8",
      alternative: "select('core/editor').getEditorSelection"
    });
    return getEditedPostAttribute(state2, "selection")?.selectionEnd;
  }
  function getEditorSelection(state2) {
    return getEditedPostAttribute(state2, "selection");
  }
  function __unstableIsEditorReady(state2) {
    return !!state2.postId;
  }
  function getEditorSettings(state2) {
    return state2.editorSettings;
  }
  function getRenderingMode(state2) {
    return state2.renderingMode;
  }
  var getDeviceType = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      const blockEditorSelect = unlock(select9(import_block_editor2.store));
      const isZoomOut = blockEditorSelect.isZoomOut();
      if (isZoomOut) {
        return "Desktop";
      }
      const canvasWidth2 = state2.canvasWidth;
      const viewportSettings = blockEditorSelect.getSettings().__experimentalFeatures?.viewport;
      return getDeviceTypeByCanvasWidth(canvasWidth2, viewportSettings);
    }
  );
  function isListViewOpened(state2) {
    return state2.listViewPanel;
  }
  function isInserterOpened(state2) {
    return !!state2.blockInserterPanel;
  }
  var getEditorMode = (0, import_data4.createRegistrySelector)(
    (select9) => () => select9(import_preferences.store).get("core", "editorMode") ?? "visual"
  );
  function getStateBeforeOptimisticTransaction() {
    (0, import_deprecated.default)("select('core/editor').getStateBeforeOptimisticTransaction", {
      since: "5.7",
      hint: "No state history is kept on this store anymore"
    });
    return null;
  }
  function inSomeHistory() {
    (0, import_deprecated.default)("select('core/editor').inSomeHistory", {
      since: "5.7",
      hint: "No state history is kept on this store anymore"
    });
    return false;
  }
  function getBlockEditorSelector(name2) {
    return (0, import_data4.createRegistrySelector)((select9) => (state2, ...args) => {
      (0, import_deprecated.default)("`wp.data.select( 'core/editor' )." + name2 + "`", {
        since: "5.3",
        alternative: "`wp.data.select( 'core/block-editor' )." + name2 + "`",
        version: "6.2"
      });
      return select9(import_block_editor2.store)[name2](...args);
    });
  }
  var getBlockName = getBlockEditorSelector("getBlockName");
  var isBlockValid = getBlockEditorSelector("isBlockValid");
  var getBlockAttributes = getBlockEditorSelector("getBlockAttributes");
  var getBlock = getBlockEditorSelector("getBlock");
  var getBlocks = getBlockEditorSelector("getBlocks");
  var getClientIdsOfDescendants = getBlockEditorSelector(
    "getClientIdsOfDescendants"
  );
  var getClientIdsWithDescendants = getBlockEditorSelector(
    "getClientIdsWithDescendants"
  );
  var getGlobalBlockCount = getBlockEditorSelector(
    "getGlobalBlockCount"
  );
  var getBlocksByClientId = getBlockEditorSelector(
    "getBlocksByClientId"
  );
  var getBlockCount = getBlockEditorSelector("getBlockCount");
  var getBlockSelectionStart = getBlockEditorSelector(
    "getBlockSelectionStart"
  );
  var getBlockSelectionEnd = getBlockEditorSelector(
    "getBlockSelectionEnd"
  );
  var getSelectedBlockCount = getBlockEditorSelector(
    "getSelectedBlockCount"
  );
  var hasSelectedBlock = getBlockEditorSelector("hasSelectedBlock");
  var getSelectedBlockClientId = getBlockEditorSelector(
    "getSelectedBlockClientId"
  );
  var getSelectedBlock = getBlockEditorSelector("getSelectedBlock");
  var getBlockRootClientId = getBlockEditorSelector(
    "getBlockRootClientId"
  );
  var getBlockHierarchyRootClientId = getBlockEditorSelector(
    "getBlockHierarchyRootClientId"
  );
  var getAdjacentBlockClientId = getBlockEditorSelector(
    "getAdjacentBlockClientId"
  );
  var getPreviousBlockClientId = getBlockEditorSelector(
    "getPreviousBlockClientId"
  );
  var getNextBlockClientId = getBlockEditorSelector(
    "getNextBlockClientId"
  );
  var getSelectedBlocksInitialCaretPosition = getBlockEditorSelector(
    "getSelectedBlocksInitialCaretPosition"
  );
  var getMultiSelectedBlockClientIds = getBlockEditorSelector(
    "getMultiSelectedBlockClientIds"
  );
  var getMultiSelectedBlocks = getBlockEditorSelector(
    "getMultiSelectedBlocks"
  );
  var getFirstMultiSelectedBlockClientId = getBlockEditorSelector(
    "getFirstMultiSelectedBlockClientId"
  );
  var getLastMultiSelectedBlockClientId = getBlockEditorSelector(
    "getLastMultiSelectedBlockClientId"
  );
  var isFirstMultiSelectedBlock = getBlockEditorSelector(
    "isFirstMultiSelectedBlock"
  );
  var isBlockMultiSelected = getBlockEditorSelector(
    "isBlockMultiSelected"
  );
  var isAncestorMultiSelected = getBlockEditorSelector(
    "isAncestorMultiSelected"
  );
  var getMultiSelectedBlocksStartClientId = getBlockEditorSelector(
    "getMultiSelectedBlocksStartClientId"
  );
  var getMultiSelectedBlocksEndClientId = getBlockEditorSelector(
    "getMultiSelectedBlocksEndClientId"
  );
  var getBlockOrder = getBlockEditorSelector("getBlockOrder");
  var getBlockIndex = getBlockEditorSelector("getBlockIndex");
  var isBlockSelected = getBlockEditorSelector("isBlockSelected");
  var hasSelectedInnerBlock = getBlockEditorSelector(
    "hasSelectedInnerBlock"
  );
  var isBlockWithinSelection = getBlockEditorSelector(
    "isBlockWithinSelection"
  );
  var hasMultiSelection = getBlockEditorSelector("hasMultiSelection");
  var isMultiSelecting = getBlockEditorSelector("isMultiSelecting");
  var isSelectionEnabled = getBlockEditorSelector("isSelectionEnabled");
  var getBlockMode = getBlockEditorSelector("getBlockMode");
  var isTyping = getBlockEditorSelector("isTyping");
  var isCaretWithinFormattedText = getBlockEditorSelector(
    "isCaretWithinFormattedText"
  );
  var getBlockInsertionPoint = getBlockEditorSelector(
    "getBlockInsertionPoint"
  );
  var isBlockInsertionPointVisible = getBlockEditorSelector(
    "isBlockInsertionPointVisible"
  );
  var isValidTemplate = getBlockEditorSelector("isValidTemplate");
  var getTemplate = getBlockEditorSelector("getTemplate");
  var getTemplateLock = getBlockEditorSelector("getTemplateLock");
  var canInsertBlockType = getBlockEditorSelector("canInsertBlockType");
  var getInserterItems = getBlockEditorSelector("getInserterItems");
  var hasInserterItems = getBlockEditorSelector("hasInserterItems");
  var getBlockListSettings = getBlockEditorSelector(
    "getBlockListSettings"
  );
  var __experimentalGetDefaultTemplateTypes = (0, import_data4.createRegistrySelector)(
    (select9) => () => {
      (0, import_deprecated.default)(
        "select('core/editor').__experimentalGetDefaultTemplateTypes",
        {
          since: "6.8",
          alternative: "select('core/core-data').getCurrentTheme()?.default_template_types"
        }
      );
      return select9(import_core_data.store).getCurrentTheme()?.default_template_types;
    }
  );
  var __experimentalGetDefaultTemplatePartAreas = (0, import_data4.createRegistrySelector)(
    (select9) => (0, import_data4.createSelector)(() => {
      (0, import_deprecated.default)(
        "select('core/editor').__experimentalGetDefaultTemplatePartAreas",
        {
          since: "6.8",
          alternative: "select('core/core-data').getCurrentTheme()?.default_template_part_areas"
        }
      );
      const areas = select9(import_core_data.store).getCurrentTheme()?.default_template_part_areas || [];
      return areas.map((item) => {
        return { ...item, icon: getTemplatePartIcon(item.icon) };
      });
    })
  );
  var __experimentalGetDefaultTemplateType = (0, import_data4.createRegistrySelector)(
    (select9) => (0, import_data4.createSelector)((state2, slug) => {
      (0, import_deprecated.default)(
        "select('core/editor').__experimentalGetDefaultTemplateType",
        {
          since: "6.8"
        }
      );
      const templateTypes = select9(import_core_data.store).getCurrentTheme()?.default_template_types;
      if (!templateTypes) {
        return EMPTY_OBJECT2;
      }
      return Object.values(templateTypes).find(
        (type) => type.slug === slug
      ) ?? EMPTY_OBJECT2;
    })
  );
  var __experimentalGetTemplateInfo = (0, import_data4.createRegistrySelector)(
    (select9) => (0, import_data4.createSelector)((state2, template2) => {
      (0, import_deprecated.default)("select('core/editor').__experimentalGetTemplateInfo", {
        since: "6.8"
      });
      if (!template2) {
        return EMPTY_OBJECT2;
      }
      const currentTheme = select9(import_core_data.store).getCurrentTheme();
      const templateTypes = currentTheme?.default_template_types || [];
      const templateAreas = currentTheme?.default_template_part_areas || [];
      return getTemplateInfo({
        template: template2,
        templateAreas,
        templateTypes
      });
    })
  );
  var getPostTypeLabel = (0, import_data4.createRegistrySelector)(
    (select9) => (state2) => {
      const currentPostType = getCurrentPostType(state2);
      const postType2 = select9(import_core_data.store).getPostType(currentPostType);
      return postType2?.labels?.singular_name;
    }
  );
  function isPublishSidebarOpened(state2) {
    return state2.publishSidebarActive;
  }

  // packages/editor/build-module/store/actions.mjs
  var actions_exports3 = {};
  __export(actions_exports3, {
    __experimentalTearDownEditor: () => __experimentalTearDownEditor,
    __unstableSaveForPreview: () => __unstableSaveForPreview,
    autosave: () => autosave,
    clearSelectedBlock: () => clearSelectedBlock,
    closePublishSidebar: () => closePublishSidebar,
    createUndoLevel: () => createUndoLevel,
    disablePublishSidebar: () => disablePublishSidebar,
    editPost: () => editPost,
    enablePublishSidebar: () => enablePublishSidebar,
    enterFormattedText: () => enterFormattedText,
    exitFormattedText: () => exitFormattedText,
    hideInsertionPoint: () => hideInsertionPoint,
    insertBlock: () => insertBlock,
    insertBlocks: () => insertBlocks,
    insertDefaultBlock: () => insertDefaultBlock,
    lockPostAutosaving: () => lockPostAutosaving,
    lockPostSaving: () => lockPostSaving,
    mergeBlocks: () => mergeBlocks,
    moveBlockToPosition: () => moveBlockToPosition,
    moveBlocksDown: () => moveBlocksDown,
    moveBlocksUp: () => moveBlocksUp,
    multiSelect: () => multiSelect,
    openPublishSidebar: () => openPublishSidebar,
    receiveBlocks: () => receiveBlocks,
    redo: () => redo,
    refreshPost: () => refreshPost,
    removeBlock: () => removeBlock,
    removeBlocks: () => removeBlocks,
    removeEditorPanel: () => removeEditorPanel,
    replaceBlock: () => replaceBlock,
    replaceBlocks: () => replaceBlocks,
    resetBlocks: () => resetBlocks,
    resetEditorBlocks: () => resetEditorBlocks,
    resetPost: () => resetPost,
    savePost: () => savePost,
    selectBlock: () => selectBlock,
    setDeviceType: () => setDeviceType,
    setEditedPost: () => setEditedPost,
    setIsInserterOpened: () => setIsInserterOpened,
    setIsListViewOpened: () => setIsListViewOpened,
    setRenderingMode: () => setRenderingMode,
    setTemplateValidity: () => setTemplateValidity,
    setupEditor: () => setupEditor,
    setupEditorState: () => setupEditorState,
    showInsertionPoint: () => showInsertionPoint,
    startMultiSelect: () => startMultiSelect,
    startTyping: () => startTyping,
    stopMultiSelect: () => stopMultiSelect,
    stopTyping: () => stopTyping,
    switchEditorMode: () => switchEditorMode,
    synchronizeTemplate: () => synchronizeTemplate,
    toggleBlockMode: () => toggleBlockMode,
    toggleDistractionFree: () => toggleDistractionFree,
    toggleEditorPanelEnabled: () => toggleEditorPanelEnabled,
    toggleEditorPanelOpened: () => toggleEditorPanelOpened,
    togglePublishSidebar: () => togglePublishSidebar,
    toggleSelection: () => toggleSelection,
    toggleSpotlightMode: () => toggleSpotlightMode,
    toggleTopToolbar: () => toggleTopToolbar,
    trashPost: () => trashPost2,
    undo: () => undo,
    unlockPostAutosaving: () => unlockPostAutosaving,
    unlockPostSaving: () => unlockPostSaving,
    updateBlock: () => updateBlock,
    updateBlockAttributes: () => updateBlockAttributes,
    updateBlockListSettings: () => updateBlockListSettings,
    updateEditorSettings: () => updateEditorSettings,
    updatePost: () => updatePost,
    updatePostLock: () => updatePostLock
  });
  var import_a11y7 = __toESM(require_a11y(), 1);
  var import_api_fetch8 = __toESM(require_api_fetch(), 1);
  var import_deprecated9 = __toESM(require_deprecated(), 1);
  var import_blocks20 = __toESM(require_blocks(), 1);
  var import_notices20 = __toESM(require_notices(), 1);
  var import_core_data57 = __toESM(require_core_data(), 1);
  var import_block_editor36 = __toESM(require_block_editor(), 1);
  var import_hooks39 = __toESM(require_hooks(), 1);
  var import_preferences10 = __toESM(require_preferences(), 1);
  var import_i18n205 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/store/local-autosave.mjs
  function postKey(postId2, isPostNew) {
    return `wp-autosave-block-editor-post-${isPostNew ? "auto-draft" : postId2}`;
  }
  function localAutosaveGet(postId2, isPostNew) {
    return window.sessionStorage.getItem(postKey(postId2, isPostNew));
  }
  function localAutosaveSet(postId2, isPostNew, title, content, excerpt) {
    window.sessionStorage.setItem(
      postKey(postId2, isPostNew),
      JSON.stringify({
        post_title: title,
        content,
        excerpt
      })
    );
  }
  function localAutosaveClear(postId2, isPostNew) {
    window.sessionStorage.removeItem(postKey(postId2, isPostNew));
  }

  // packages/editor/build-module/store/utils/notice-builder.mjs
  var import_i18n2 = __toESM(require_i18n(), 1);
  function getNotificationArgumentsForSaveSuccess(data) {
    const { previousPost, post: post2, postType: postType2 } = data;
    if (data.options?.isAutosave) {
      return [];
    }
    const publishStatus = ["publish", "private", "future"];
    const isPublished = publishStatus.includes(previousPost.status);
    const willPublish = publishStatus.includes(post2.status);
    const willTrash = post2.status === "trash" && previousPost.status !== "trash";
    let noticeMessage;
    let shouldShowLink = postType2?.viewable ?? false;
    let isDraft;
    if (willTrash) {
      noticeMessage = postType2.labels.item_trashed;
      shouldShowLink = false;
    } else if (post2.type === ATTACHMENT_POST_TYPE) {
      noticeMessage = (0, import_i18n2.__)("Media updated.");
      shouldShowLink = false;
    } else if (!isPublished && !willPublish) {
      noticeMessage = (0, import_i18n2.__)("Draft saved.");
      isDraft = true;
    } else if (isPublished && !willPublish) {
      noticeMessage = postType2.labels.item_reverted_to_draft;
      shouldShowLink = false;
    } else if (!isPublished && willPublish) {
      noticeMessage = {
        publish: postType2.labels.item_published,
        private: postType2.labels.item_published_privately,
        future: postType2.labels.item_scheduled
      }[post2.status];
    } else {
      noticeMessage = postType2.labels.item_updated;
    }
    const actions2 = [];
    if (shouldShowLink) {
      actions2.push({
        label: isDraft ? (0, import_i18n2.__)("View Preview") : postType2.labels.view_item,
        url: post2.link,
        openInNewTab: true
      });
    }
    return [
      noticeMessage,
      {
        id: "editor-save",
        type: "snackbar",
        actions: actions2
      }
    ];
  }
  function getNotificationArgumentsForSaveFail(data) {
    const { post: post2, edits, error: error2 } = data;
    if (error2 && "rest_autosave_no_changes" === error2.code) {
      return [];
    }
    const publishStatus = ["publish", "private", "future"];
    const isPublished = publishStatus.indexOf(post2.status) !== -1;
    if (error2.code === "offline_error") {
      const messages2 = {
        publish: (0, import_i18n2.__)(
          "Publishing failed because you were offline. Please verify your connection and try again."
        ),
        private: (0, import_i18n2.__)(
          "Publishing failed because you were offline. Please verify your connection and try again."
        ),
        future: (0, import_i18n2.__)(
          "Scheduling failed because you were offline. Please verify your connection and try again."
        ),
        default: (0, import_i18n2.__)(
          "Updating failed because you were offline. Please verify your connection and try again."
        )
      };
      const noticeMessage2 = !isPublished && edits.status in messages2 ? messages2[edits.status] : messages2.default;
      return [noticeMessage2, { id: "editor-save" }];
    }
    const messages = {
      publish: (0, import_i18n2.__)("Publishing failed."),
      private: (0, import_i18n2.__)("Publishing failed."),
      future: (0, import_i18n2.__)("Scheduling failed."),
      default: (0, import_i18n2.__)("Updating failed.")
    };
    let noticeMessage = !isPublished && edits.status in messages ? messages[edits.status] : messages.default;
    if (error2.message && !/<\/?[^>]*>/.test(error2.message)) {
      noticeMessage = [noticeMessage, error2.message].join(" ");
    }
    return [
      noticeMessage,
      {
        id: "editor-save"
      }
    ];
  }
  function getNotificationArgumentsForTrashFail(data) {
    return [
      data.error.message && data.error.code !== "unknown_error" ? data.error.message : (0, import_i18n2.__)("Trashing failed"),
      {
        id: "editor-trash-fail"
      }
    ];
  }

  // packages/editor/build-module/store/private-actions.mjs
  var private_actions_exports = {};
  __export(private_actions_exports, {
    createTemplate: () => createTemplate,
    hideBlockTypes: () => hideBlockTypes,
    openRevision: () => openRevision,
    registerEntityAction: () => registerEntityAction,
    registerEntityField: () => registerEntityField,
    registerPostTypeSchema: () => registerPostTypeSchema,
    removeTemplates: () => removeTemplates,
    resetStylesNavigation: () => resetStylesNavigation,
    restoreRevision: () => restoreRevision,
    revertTemplate: () => revertTemplate2,
    saveDirtyEntities: () => saveDirtyEntities,
    selectNote: () => selectNote,
    setCanvasWidth: () => setCanvasWidth,
    setCurrentRevisionId: () => setCurrentRevisionId,
    setCurrentTemplateId: () => setCurrentTemplateId,
    setDefaultRenderingMode: () => setDefaultRenderingMode,
    setIsReady: () => setIsReady,
    setRevisionPage: () => setRevisionPage,
    setShowRevisionDiff: () => setShowRevisionDiff,
    setShowStylebook: () => setShowStylebook,
    setStylesPath: () => setStylesPath,
    showBlockTypes: () => showBlockTypes,
    unregisterEntityAction: () => unregisterEntityAction,
    unregisterEntityField: () => unregisterEntityField
  });
  var import_core_data56 = __toESM(require_core_data(), 1);
  var import_i18n204 = __toESM(require_i18n(), 1);
  var import_notices19 = __toESM(require_notices(), 1);
  var import_block_editor35 = __toESM(require_block_editor(), 1);
  var import_preferences9 = __toESM(require_preferences(), 1);
  var import_url14 = __toESM(require_url(), 1);
  var import_api_fetch7 = __toESM(require_api_fetch(), 1);
  var import_blocks19 = __toESM(require_blocks(), 1);
  var import_html_entities13 = __toESM(require_html_entities(), 1);
  var import_date16 = __toESM(require_date(), 1);

  // packages/editor/build-module/store/utils/is-template-revertable.mjs
  function isTemplateRevertable(templateOrTemplatePart) {
    if (!templateOrTemplatePart) {
      return false;
    }
    return templateOrTemplatePart.source === TEMPLATE_ORIGINS.custom && (Boolean(templateOrTemplatePart?.plugin) || templateOrTemplatePart?.has_theme_file);
  }

  // packages/editor/build-module/store/private-selectors.mjs
  var private_selectors_exports = {};
  __export(private_selectors_exports, {
    buildRevisionsPageQuery: () => buildRevisionsPageQuery,
    getCanvasWidth: () => getCanvasWidth,
    getCurrentRevision: () => getCurrentRevision,
    getCurrentRevisionId: () => getCurrentRevisionId,
    getDefaultRenderingMode: () => getDefaultRenderingMode,
    getEntityActions: () => getEntityActions2,
    getEntityFields: () => getEntityFields2,
    getInserter: () => getInserter,
    getInserterSidebarToggleRef: () => getInserterSidebarToggleRef,
    getListViewToggleRef: () => getListViewToggleRef,
    getPageRevisions: () => getPageRevisions,
    getPostBlocksByName: () => getPostBlocksByName,
    getPostIcon: () => getPostIcon,
    getPreviousRevision: () => getPreviousRevision,
    getRevisionPage: () => getRevisionPage,
    getRevisionsPerPage: () => getRevisionsPerPage,
    getSelectedNote: () => getSelectedNote,
    getShowStylebook: () => getShowStylebook,
    getStylesPath: () => getStylesPath,
    hasPostMetaChanges: () => hasPostMetaChanges,
    isCollaborationEnabledForCurrentPost: () => isCollaborationEnabledForCurrentPost,
    isEntityReady: () => isEntityReady2,
    isNoteFocused: () => isNoteFocused,
    isRevisionsMode: () => isRevisionsMode,
    isShowingRevisionDiff: () => isShowingRevisionDiff
  });
  var import_fast_deep_equal = __toESM(require_fast_deep_equal(), 1);
  var import_block_editor3 = __toESM(require_block_editor(), 1);
  var import_data6 = __toESM(require_data(), 1);
  var import_core_data3 = __toESM(require_core_data(), 1);
  var import_preferences2 = __toESM(require_preferences(), 1);

  // packages/editor/build-module/dataviews/store/private-selectors.mjs
  var EMPTY_ARRAY2 = [];
  function getEntityActions(state2, kind, name2) {
    return state2.actions[kind]?.[name2] ?? EMPTY_ARRAY2;
  }
  function getEntityFields(state2, kind, name2) {
    return state2.fields[kind]?.[name2] ?? EMPTY_ARRAY2;
  }
  function isEntityReady(state2, kind, name2) {
    return state2.isReady[kind]?.[name2];
  }

  // node_modules/uuid/dist/stringify.js
  var byteToHex = [];
  for (let i3 = 0; i3 < 256; ++i3) {
    byteToHex.push((i3 + 256).toString(16).slice(1));
  }
  function unsafeStringify(arr, offset4 = 0) {
    return (byteToHex[arr[offset4 + 0]] + byteToHex[arr[offset4 + 1]] + byteToHex[arr[offset4 + 2]] + byteToHex[arr[offset4 + 3]] + "-" + byteToHex[arr[offset4 + 4]] + byteToHex[arr[offset4 + 5]] + "-" + byteToHex[arr[offset4 + 6]] + byteToHex[arr[offset4 + 7]] + "-" + byteToHex[arr[offset4 + 8]] + byteToHex[arr[offset4 + 9]] + "-" + byteToHex[arr[offset4 + 10]] + byteToHex[arr[offset4 + 11]] + byteToHex[arr[offset4 + 12]] + byteToHex[arr[offset4 + 13]] + byteToHex[arr[offset4 + 14]] + byteToHex[arr[offset4 + 15]]).toLowerCase();
  }

  // node_modules/uuid/dist/rng.js
  var rnds8 = new Uint8Array(16);
  function rng() {
    return crypto.getRandomValues(rnds8);
  }

  // node_modules/uuid/dist/v4.js
  function v4(options, buf, offset4) {
    if (!buf && !options && crypto.randomUUID) {
      return crypto.randomUUID();
    }
    return _v4(options, buf, offset4);
  }
  function _v4(options, buf, offset4) {
    options = options || {};
    const rnds = options.random ?? options.rng?.() ?? rng();
    if (rnds.length < 16) {
      throw new Error("Random bytes length must be >= 16");
    }
    rnds[6] = rnds[6] & 15 | 64;
    rnds[8] = rnds[8] & 63 | 128;
    if (buf) {
      offset4 = offset4 || 0;
      if (offset4 < 0 || offset4 + 16 > buf.length) {
        throw new RangeError(`UUID byte range ${offset4}:${offset4 + 15} is out of buffer bounds`);
      }
      for (let i3 = 0; i3 < 16; ++i3) {
        buf[offset4 + i3] = rnds[i3];
      }
      return buf;
    }
    return unsafeStringify(rnds);
  }
  var v4_default = v4;

  // packages/editor/build-module/utils/media-upload/index.mjs
  var import_data5 = __toESM(require_data(), 1);
  var import_core_data2 = __toESM(require_core_data(), 1);
  var import_media_utils = __toESM(require_media_utils(), 1);

  // packages/editor/build-module/components/upload-progress-snackbar/tracker.mjs
  var import_element2 = __toESM(require_element(), 1);
  var state = null;
  var listeners = /* @__PURE__ */ new Set();
  function notify() {
    listeners.forEach((listener) => listener());
  }
  function addFiles(filenames) {
    if (!filenames.length) {
      return;
    }
    if (!state) {
      state = { total: 0, completed: 0, pending: [] };
    }
    state = {
      total: state.total + filenames.length,
      completed: state.completed,
      pending: [...state.pending, ...filenames]
    };
    notify();
  }
  function advance(count) {
    if (!state || count <= 0) {
      return;
    }
    const completed = Math.min(state.total, state.completed + count);
    const pending = state.pending.slice(count);
    if (completed >= state.total) {
      state = null;
    } else {
      state = { total: state.total, completed, pending };
    }
    notify();
  }
  function getState() {
    return state;
  }
  function subscribe(listener) {
    listeners.add(listener);
    return () => {
      listeners.delete(listener);
    };
  }
  function useTracker() {
    return (0, import_element2.useSyncExternalStore)(subscribe, getState, getState);
  }

  // packages/editor/build-module/utils/media-upload/index.mjs
  var noop = () => {
  };
  function mediaUpload({
    additionalData = {},
    allowedTypes,
    filesList,
    maxUploadFileSize,
    onError = noop,
    onFileChange,
    onSuccess,
    multiple = true,
    isTransportOnly = false
  }) {
    const { receiveEntityRecords } = (0, import_data5.dispatch)(import_core_data2.store);
    const { getCurrentPost: getCurrentPost2, getEditorSettings: getEditorSettings2 } = (0, import_data5.select)(store);
    const {
      lockPostAutosaving: lockPostAutosaving2,
      unlockPostAutosaving: unlockPostAutosaving2,
      lockPostSaving: lockPostSaving2,
      unlockPostSaving: unlockPostSaving2
    } = (0, import_data5.dispatch)(store);
    const wpAllowedMimeTypes = getEditorSettings2().allowedMimeTypes;
    const lockKey = `image-upload-${v4_default()}`;
    maxUploadFileSize = maxUploadFileSize || getEditorSettings2().maxUploadFileSize;
    const currentPost = getCurrentPost2();
    const currentPostId = typeof currentPost?.id === "number" ? currentPost.id : currentPost?.wp_id;
    const clearSaveLock = () => {
      unlockPostSaving2(lockKey);
      unlockPostAutosaving2(lockKey);
    };
    if (!isTransportOnly) {
      lockPostSaving2(lockKey);
      lockPostAutosaving2(lockKey);
    }
    const postData = currentPostId ? { post: currentPostId } : {};
    if (!isTransportOnly) {
      const trackingFiles = Array.from(filesList).map(
        (f3) => f3?.name || ""
      );
      addFiles(trackingFiles);
    }
    let lastCompletedCount = 0;
    (0, import_media_utils.uploadMedia)({
      allowedTypes,
      filesList,
      onFileChange: (files) => {
        onFileChange?.(files);
        const entityFiles = files.filter((_file) => _file?.id);
        if (entityFiles?.length) {
          const invalidateCache = true;
          receiveEntityRecords(
            "postType",
            "attachment",
            entityFiles,
            void 0,
            invalidateCache
          );
        }
        if (!isTransportOnly && entityFiles.length === files.length) {
          clearSaveLock();
        }
        if (!isTransportOnly) {
          const completedCount = entityFiles.length;
          if (completedCount > lastCompletedCount) {
            advance(completedCount - lastCompletedCount);
            lastCompletedCount = completedCount;
          }
        }
      },
      onSuccess,
      additionalData: {
        ...postData,
        ...additionalData
      },
      maxUploadFileSize,
      onError: ({ message: message2 }) => {
        if (!isTransportOnly) {
          clearSaveLock();
          advance(1);
        }
        onError(message2);
      },
      wpAllowedMimeTypes,
      multiple
    });
  }

  // packages/editor/build-module/utils/url.mjs
  var import_url2 = __toESM(require_url(), 1);
  var import_deprecated2 = __toESM(require_deprecated(), 1);
  function cleanForSlug2(string) {
    (0, import_deprecated2.default)("wp.editor.cleanForSlug", {
      since: "12.7",
      plugin: "Gutenberg",
      alternative: "wp.url.cleanForSlug"
    });
    return (0, import_url2.cleanForSlug)(string);
  }

  // packages/editor/build-module/store/private-selectors.mjs
  var EMPTY_INSERTION_POINT = {
    rootClientId: void 0,
    insertionIndex: void 0,
    filterValue: void 0
  };
  var RENDERING_MODES = ["post-only", "template-locked"];
  var getInserter = (0, import_data6.createRegistrySelector)(
    (select9) => (0, import_data6.createSelector)(
      (state2) => {
        if (typeof state2.blockInserterPanel === "object") {
          return state2.blockInserterPanel;
        }
        if (getRenderingMode(state2) === "template-locked") {
          const {
            getBlocksByName,
            getSelectedBlockClientId: getSelectedBlockClientId2,
            getBlockParents,
            getBlockOrder: getBlockOrder2
          } = select9(import_block_editor3.store);
          const [postContentClientId] = getBlocksByName("core/post-content");
          if (postContentClientId) {
            const selectedBlockClientId = getSelectedBlockClientId2();
            if (selectedBlockClientId && selectedBlockClientId !== postContentClientId && getBlockParents(selectedBlockClientId).includes(
              postContentClientId
            )) {
              return EMPTY_INSERTION_POINT;
            }
            return {
              rootClientId: postContentClientId,
              insertionIndex: getBlockOrder2(postContentClientId).length,
              filterValue: void 0
            };
          }
        }
        return EMPTY_INSERTION_POINT;
      },
      (state2) => {
        const {
          getBlocksByName,
          getSelectedBlockClientId: getSelectedBlockClientId2,
          getBlockParents,
          getBlockOrder: getBlockOrder2
        } = select9(import_block_editor3.store);
        const [postContentClientId] = getBlocksByName("core/post-content");
        const selectedBlockClientId = getSelectedBlockClientId2();
        return [
          state2.blockInserterPanel,
          getRenderingMode(state2),
          postContentClientId,
          selectedBlockClientId,
          selectedBlockClientId ? getBlockParents(selectedBlockClientId) : void 0,
          postContentClientId ? getBlockOrder2(postContentClientId).length : void 0
        ];
      }
    )
  );
  function getListViewToggleRef(state2) {
    return state2.listViewToggleRef;
  }
  function getInserterSidebarToggleRef(state2) {
    return state2.inserterSidebarToggleRef;
  }
  var CARD_ICONS = {
    wp_block: symbol_default,
    wp_navigation: navigation_default,
    page: page_default,
    post: verse_default
  };
  var getPostIcon = (0, import_data6.createRegistrySelector)(
    (select9) => (state2, postType2, options) => {
      {
        if (postType2 === "wp_template_part" || postType2 === "wp_template") {
          const templateAreas = select9(import_core_data3.store).getCurrentTheme()?.default_template_part_areas || [];
          const areaData = templateAreas.find(
            (item) => options.area === item.area
          );
          if (areaData?.icon) {
            return getTemplatePartIcon(areaData.icon);
          }
          return layout_default;
        }
        if (CARD_ICONS[postType2]) {
          return CARD_ICONS[postType2];
        }
        const postTypeEntity = select9(import_core_data3.store).getPostType(postType2);
        if (typeof postTypeEntity?.icon === "string" && postTypeEntity.icon.startsWith("dashicons-")) {
          return postTypeEntity.icon.slice(10);
        }
        return page_default;
      }
    }
  );
  var hasPostMetaChanges = (0, import_data6.createRegistrySelector)(
    (select9) => (state2, postType2, postId2) => {
      const { type: currentPostType, id: currentPostId } = getCurrentPost(state2);
      const edits = select9(import_core_data3.store).getEntityRecordNonTransientEdits(
        "postType",
        postType2 || currentPostType,
        postId2 || currentPostId
      );
      if (!edits?.meta) {
        return false;
      }
      const originalPostMeta = select9(import_core_data3.store).getEntityRecord(
        "postType",
        postType2 || currentPostType,
        postId2 || currentPostId
      )?.meta;
      return !(0, import_fast_deep_equal.default)(
        { ...originalPostMeta, footnotes: void 0 },
        { ...edits.meta, footnotes: void 0 }
      );
    }
  );
  function getEntityActions2(state2, ...args) {
    return getEntityActions(state2.dataviews, ...args);
  }
  function isEntityReady2(state2, ...args) {
    return isEntityReady(state2.dataviews, ...args);
  }
  function getEntityFields2(state2, ...args) {
    return getEntityFields(state2.dataviews, ...args);
  }
  var getPostBlocksByName = (0, import_data6.createRegistrySelector)(
    (select9) => (0, import_data6.createSelector)(
      (state2, blockNames) => {
        blockNames = Array.isArray(blockNames) ? blockNames : [blockNames];
        const { getBlocksByName, getBlockParents, getBlockName: getBlockName2 } = select9(import_block_editor3.store);
        return getBlocksByName(blockNames).filter(
          (clientId) => getBlockParents(clientId).every((parentClientId) => {
            const parentBlockName = getBlockName2(parentClientId);
            return (
              // Ignore descendents of the query block.
              parentBlockName !== "core/query" && // Enable only the top-most block.
              !blockNames.includes(parentBlockName)
            );
          })
        );
      },
      (state2, blockNames) => {
        blockNames = Array.isArray(blockNames) ? blockNames : [blockNames];
        const { getBlocksByName, getBlockParents } = select9(import_block_editor3.store);
        const clientIds = getBlocksByName(blockNames);
        const parentsOfClientIds = clientIds.map(
          (id) => getBlockParents(id)
        );
        return [clientIds, ...parentsOfClientIds];
      }
    )
  );
  var getDefaultRenderingMode = (0, import_data6.createRegistrySelector)(
    (select9) => (state2, postType2) => {
      const { getPostType, getCurrentTheme, hasFinishedResolution } = select9(import_core_data3.store);
      const currentTheme = getCurrentTheme();
      const postTypeEntity = getPostType(postType2);
      if (!hasFinishedResolution("getPostType", [postType2]) || !hasFinishedResolution("getCurrentTheme")) {
        return void 0;
      }
      const theme2 = currentTheme?.stylesheet;
      const defaultModePreference = select9(import_preferences2.store).get(
        "core",
        "renderingModes"
      )?.[theme2]?.[postType2];
      if (RENDERING_MODES.includes(defaultModePreference)) {
        return defaultModePreference;
      }
      const postTypeDefaultMode = Array.isArray(
        postTypeEntity?.supports?.editor
      ) ? postTypeEntity.supports.editor.find(
        (features) => "default-mode" in features
      )?.["default-mode"] : void 0;
      if (RENDERING_MODES.includes(postTypeDefaultMode)) {
        return postTypeDefaultMode;
      }
      const settingsDefaultMode = getEditorSettings(state2).defaultRenderingMode;
      if (RENDERING_MODES.includes(settingsDefaultMode)) {
        return settingsDefaultMode;
      }
      return "post-only";
    }
  );
  function getStylesPath(state2) {
    return state2.stylesPath ?? "/";
  }
  function getShowStylebook(state2) {
    return state2.showStylebook ?? false;
  }
  var getCanvasWidth = (0, import_data6.createRegistrySelector)(
    (select9) => (state2) => {
      if (unlock(select9(import_block_editor3.store)).isZoomOut()) {
        return void 0;
      }
      return state2.canvasWidth;
    }
  );
  function getRevisionPage(state2) {
    return state2.revisionPage;
  }
  function buildRevisionsPageQuery(revisionKey, page) {
    return {
      per_page: REVISIONS_PER_PAGE,
      page,
      context: "edit",
      orderby: "date",
      order: "desc",
      _fields: [
        .../* @__PURE__ */ new Set([
          "id",
          "date",
          "modified",
          "author",
          "slug",
          "meta",
          "title.raw",
          "excerpt.raw",
          "content.raw",
          revisionKey
        ])
      ].join()
    };
  }
  var REVISIONS_PER_PAGE = 100;
  function getRevisionsPerPage() {
    return REVISIONS_PER_PAGE;
  }
  var getPageRevisions = (0, import_data6.createRegistrySelector)(
    (select9) => (state2, page) => {
      if (!page) {
        return null;
      }
      const { type: postType2, id: postId2 } = getCurrentPost(state2);
      if (!postType2 || !postId2) {
        return null;
      }
      const entityConfig = select9(import_core_data3.store).getEntityConfig(
        "postType",
        postType2
      );
      const revisionKey = entityConfig?.revisionKey || "id";
      return select9(import_core_data3.store).getRevisions(
        "postType",
        postType2,
        postId2,
        buildRevisionsPageQuery(revisionKey, page)
      );
    }
  );
  function isRevisionsMode(state2) {
    return state2.revisionId !== null;
  }
  function isShowingRevisionDiff(state2) {
    return state2.showRevisionDiff;
  }
  function getCurrentRevisionId(state2) {
    return state2.revisionId;
  }
  var getCurrentRevision = (0, import_data6.createRegistrySelector)(
    (select9) => (state2) => {
      const revisionId2 = getCurrentRevisionId(state2);
      if (!revisionId2) {
        return void 0;
      }
      const page = getRevisionPage(state2);
      if (!page) {
        return null;
      }
      const { type: postType2, id: postId2 } = getCurrentPost(state2);
      const entityConfig = select9(import_core_data3.store).getEntityConfig(
        "postType",
        postType2
      );
      const revisionKey = entityConfig?.revisionKey || "id";
      const revisions = select9(import_core_data3.store).getRevisions(
        "postType",
        postType2,
        postId2,
        buildRevisionsPageQuery(revisionKey, page)
      );
      if (!revisions) {
        return null;
      }
      const revision = revisions.find(
        (record) => record[revisionKey] === revisionId2
      );
      if (revision) {
        return revision;
      }
      return select9(import_core_data3.store).getRevision(
        "postType",
        postType2,
        postId2,
        revisionId2,
        { context: "edit" }
      ) ?? null;
    }
  );
  function getSelectedNote(state2) {
    return state2.selectedNote?.noteId;
  }
  function isNoteFocused(state2) {
    return !!state2.selectedNote?.options?.focus;
  }
  var getPreviousRevision = (0, import_data6.createRegistrySelector)(
    (select9) => (state2) => {
      const currentRevisionId = getCurrentRevisionId(state2);
      if (!currentRevisionId) {
        return void 0;
      }
      const page = getRevisionPage(state2);
      if (!page) {
        return null;
      }
      const { type: postType2, id: postId2 } = getCurrentPost(state2);
      const entityConfig = select9(import_core_data3.store).getEntityConfig(
        "postType",
        postType2
      );
      const revisionKey = entityConfig?.revisionKey || "id";
      const query = buildRevisionsPageQuery(revisionKey, page);
      const revisions = select9(import_core_data3.store).getRevisions(
        "postType",
        postType2,
        postId2,
        query
      );
      if (!revisions) {
        return null;
      }
      const currentIndex = revisions.findIndex(
        (r4) => r4[revisionKey] === currentRevisionId
      );
      if (currentIndex >= 0 && currentIndex < revisions.length - 1) {
        return revisions[currentIndex + 1];
      }
      const totalRevisions = getCurrentPostRevisionsCount(state2);
      const totalPages = Math.ceil(totalRevisions / query.per_page) || 1;
      if (currentIndex === revisions.length - 1 && page < totalPages) {
        const nextPageRevisions = select9(import_core_data3.store).getRevisions(
          "postType",
          postType2,
          postId2,
          buildRevisionsPageQuery(revisionKey, page + 1)
        );
        return nextPageRevisions?.[0] ?? null;
      }
      return null;
    }
  );
  var isCollaborationEnabledForCurrentPost = (0, import_data6.createRegistrySelector)(
    (select9) => (state2) => {
      if (!unlock(select9(import_core_data3.store)).isCollaborationSupported()) {
        return false;
      }
      const currentPostType = getCurrentPostType(state2);
      const currentPostId = getCurrentPostId(state2);
      const entityConfig = select9(import_core_data3.store).getEntityConfig(
        "postType",
        currentPostType
      );
      const syncConfig = entityConfig?.syncConfig;
      return Boolean(
        syncConfig && syncConfig.supportsPersistence && window._wpCollaborationEnabled && false !== syncConfig.shouldSync?.(
          `postType/${currentPostType}`,
          currentPostId
        )
      );
    }
  );

  // packages/editor/build-module/dataviews/store/private-actions.mjs
  var import_core_data55 = __toESM(require_core_data(), 1);
  var import_hooks38 = __toESM(require_hooks(), 1);

  // packages/fields/build-module/fields/slug/index.mjs
  var import_i18n5 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/slug/slug-edit.mjs
  var import_components = __toESM(require_components(), 1);
  var import_compose = __toESM(require_compose(), 1);
  var import_data7 = __toESM(require_data(), 1);
  var import_element3 = __toESM(require_element(), 1);
  var import_notices = __toESM(require_notices(), 1);
  var import_url5 = __toESM(require_url(), 1);
  var import_i18n4 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/slug/utils.mjs
  var import_url4 = __toESM(require_url(), 1);

  // packages/fields/build-module/actions/utils.mjs
  var import_html_entities = __toESM(require_html_entities(), 1);
  var import_i18n3 = __toESM(require_i18n(), 1);
  function isTemplate(post2) {
    return post2.type === "wp_template";
  }
  function isTemplatePart(post2) {
    return post2.type === "wp_template_part";
  }
  function isTemplateOrTemplatePart(p4) {
    return p4.type === "wp_template" || p4.type === "wp_template_part";
  }
  function getItemTitle(item, fallback = (0, import_i18n3.__)("(no title)")) {
    let title = "";
    if (typeof item.title === "string") {
      title = (0, import_html_entities.decodeEntities)(item.title);
    } else if (item.title && "rendered" in item.title) {
      title = (0, import_html_entities.decodeEntities)(item.title.rendered);
    } else if (item.title && "raw" in item.title) {
      title = (0, import_html_entities.decodeEntities)(item.title.raw);
    }
    return title || fallback;
  }
  function isTemplateRemovable(template2) {
    if (!template2) {
      return false;
    }
    return [template2.source, template2.source].includes("custom") && !Boolean(template2.type === "wp_template" && template2?.plugin) && !template2.has_theme_file;
  }

  // packages/fields/build-module/fields/slug/utils.mjs
  var getSlug = (item) => {
    if (typeof item !== "object") {
      return "";
    }
    return item.slug || (0, import_url4.cleanForSlug)(getItemTitle(item)) || item.id.toString();
  };

  // packages/fields/build-module/fields/slug/slug-edit.mjs
  var import_jsx_runtime94 = __toESM(require_jsx_runtime(), 1);
  var SlugEdit = ({
    field,
    onChange,
    data
  }) => {
    const { id } = field;
    const slug = field.getValue({ item: data }) || getSlug(data);
    const permalinkTemplate = data.permalink_template || "";
    const PERMALINK_POSTNAME_REGEX2 = /%(?:postname|pagename)%/;
    const [prefix2, suffix] = permalinkTemplate.split(
      PERMALINK_POSTNAME_REGEX2
    );
    const permalinkPrefix = prefix2;
    const permalinkSuffix = suffix;
    const isEditable = PERMALINK_POSTNAME_REGEX2.test(permalinkTemplate);
    const originalSlugRef = (0, import_element3.useRef)(slug);
    const slugToDisplay = slug || originalSlugRef.current;
    const permalink = isEditable ? `${permalinkPrefix}${slugToDisplay}${permalinkSuffix}` : (0, import_url5.safeDecodeURIComponent)(data.link || "");
    (0, import_element3.useEffect)(() => {
      if (slug && originalSlugRef.current === void 0) {
        originalSlugRef.current = slug;
      }
    }, [slug]);
    const onChangeControl = (0, import_element3.useCallback)(
      (newValue) => onChange({
        [id]: newValue
      }),
      [id, onChange]
    );
    const { createNotice } = (0, import_data7.useDispatch)(import_notices.store);
    const copyButtonRef = (0, import_compose.useCopyToClipboard)(permalink, () => {
      createNotice("info", (0, import_i18n4.__)("Copied Permalink to clipboard."), {
        isDismissible: true,
        type: "snackbar"
      });
    });
    const postUrlSlugDescriptionId = "editor-post-url__slug-description-" + (0, import_compose.useInstanceId)(SlugEdit);
    return /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)("fieldset", { className: "fields-controls__slug", children: [
      isEditable && /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(import_components.__experimentalVStack, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(import_components.__experimentalVStack, { spacing: "0px", children: [
          /* @__PURE__ */ (0, import_jsx_runtime94.jsx)("span", { children: (0, import_i18n4.__)(
            "Customize the last part of the Permalink."
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(import_components.ExternalLink, { href: "https://wordpress.org/documentation/article/page-post-settings-sidebar/#permalink", children: (0, import_i18n4.__)("Learn more") })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(
          import_components.__experimentalInputControl,
          {
            prefix: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(import_components.__experimentalInputControlPrefixWrapper, { children: "/" }),
            suffix: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(import_components.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(
              import_components.Button,
              {
                size: "small",
                icon: copy_small_default,
                ref: copyButtonRef,
                label: (0, import_i18n4.__)("Copy")
              }
            ) }),
            label: (0, import_i18n4.__)("Link"),
            hideLabelFromVision: true,
            value: slug,
            autoComplete: "off",
            spellCheck: "false",
            type: "text",
            className: "fields-controls__slug-input",
            onChange: (newValue) => {
              onChangeControl(newValue);
            },
            onBlur: () => {
              if (slug === "") {
                onChangeControl(originalSlugRef.current);
              }
            },
            "aria-describedby": postUrlSlugDescriptionId
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)("div", { className: "fields-controls__slug-help", children: [
          /* @__PURE__ */ (0, import_jsx_runtime94.jsx)("span", { className: "fields-controls__slug-help-visual-label", children: (0, import_i18n4.__)("Permalink:") }),
          /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(
            import_components.ExternalLink,
            {
              className: "fields-controls__slug-help-link",
              href: permalink,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime94.jsx)("span", { className: "fields-controls__slug-help-prefix", children: permalinkPrefix }),
                /* @__PURE__ */ (0, import_jsx_runtime94.jsx)("span", { className: "fields-controls__slug-help-slug", children: slugToDisplay }),
                /* @__PURE__ */ (0, import_jsx_runtime94.jsx)("span", { className: "fields-controls__slug-help-suffix", children: permalinkSuffix })
              ]
            }
          )
        ] })
      ] }),
      !isEditable && /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(
        import_components.ExternalLink,
        {
          className: "fields-controls__slug-help",
          href: permalink,
          children: permalink
        }
      )
    ] });
  };
  var slug_edit_default = SlugEdit;

  // packages/fields/build-module/fields/slug/slug-view.mjs
  var import_element4 = __toESM(require_element(), 1);
  var SlugView = ({ item }) => {
    const slug = getSlug(item);
    const originalSlugRef = (0, import_element4.useRef)(slug);
    (0, import_element4.useEffect)(() => {
      if (slug && originalSlugRef.current === void 0) {
        originalSlugRef.current = slug;
      }
    }, [slug]);
    const slugToDisplay = slug || originalSlugRef.current;
    return `${slugToDisplay}`;
  };
  var slug_view_default = SlugView;

  // packages/fields/build-module/fields/slug/index.mjs
  var slugField = {
    id: "slug",
    type: "text",
    label: (0, import_i18n5.__)("Slug"),
    Edit: slug_edit_default,
    render: slug_view_default,
    filterBy: false
  };
  var slug_default = slugField;

  // packages/fields/build-module/fields/title/index.mjs
  var import_i18n7 = __toESM(require_i18n(), 1);

  // node_modules/clsx/dist/clsx.mjs
  function r2(e3) {
    var t4, f3, n3 = "";
    if ("string" == typeof e3 || "number" == typeof e3) n3 += e3;
    else if ("object" == typeof e3) if (Array.isArray(e3)) {
      var o4 = e3.length;
      for (t4 = 0; t4 < o4; t4++) e3[t4] && (f3 = r2(e3[t4])) && (n3 && (n3 += " "), n3 += f3);
    } else for (f3 in e3) e3[f3] && (n3 && (n3 += " "), n3 += f3);
    return n3;
  }
  function clsx() {
    for (var e3, t4, f3 = 0, n3 = "", o4 = arguments.length; f3 < o4; f3++) (e3 = arguments[f3]) && (t4 = r2(e3)) && (n3 && (n3 += " "), n3 += t4);
    return n3;
  }
  var clsx_default = clsx;

  // packages/fields/build-module/fields/title/view.mjs
  var import_components2 = __toESM(require_components(), 1);
  var import_i18n6 = __toESM(require_i18n(), 1);
  var import_jsx_runtime95 = __toESM(require_jsx_runtime(), 1);
  function BaseTitleView({
    item,
    className,
    children
  }) {
    const renderedTitle = getItemTitle(item);
    return /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(
      import_components2.__experimentalHStack,
      {
        className: clsx_default("fields-field__title", className),
        alignment: "center",
        justify: "flex-start",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)("span", { children: renderedTitle || (0, import_i18n6.__)("(no title)") }),
          children
        ]
      }
    );
  }
  function TitleView({ item }) {
    return /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(BaseTitleView, { item });
  }

  // packages/fields/build-module/fields/title/index.mjs
  var titleField = {
    type: "text",
    id: "title",
    label: (0, import_i18n7.__)("Title"),
    placeholder: (0, import_i18n7.__)("No title"),
    getValue: ({ item }) => getItemTitle(item),
    render: TitleView,
    enableHiding: true,
    enableGlobalSearch: true,
    filterBy: false
  };
  var title_default = titleField;

  // packages/fields/build-module/fields/page-title/index.mjs
  var import_i18n9 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/page-title/view.mjs
  var import_i18n8 = __toESM(require_i18n(), 1);
  var import_data8 = __toESM(require_data(), 1);
  var import_core_data4 = __toESM(require_core_data(), 1);
  var import_components3 = __toESM(require_components(), 1);

  // packages/fields/build-module/lock-unlock.mjs
  var import_private_apis4 = __toESM(require_private_apis(), 1);
  var { lock: lock3, unlock: unlock3 } = (0, import_private_apis4.__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/fields/page-title/view.mjs
  var import_jsx_runtime96 = __toESM(require_jsx_runtime(), 1);
  var { Badge: WCBadge } = unlock3(import_components3.privateApis);
  function PageTitleView({ item }) {
    const { frontPageId, postsPageId } = (0, import_data8.useSelect)((select9) => {
      const { getEntityRecord } = select9(import_core_data4.store);
      const siteSettings = getEntityRecord(
        "root",
        "site"
      );
      return {
        frontPageId: siteSettings?.page_on_front,
        postsPageId: siteSettings?.page_for_posts
      };
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(BaseTitleView, { item, className: "fields-field__page-title", children: [frontPageId, postsPageId].includes(item.id) && /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(WCBadge, { children: item.id === frontPageId ? (0, import_i18n8.__)("Homepage") : (0, import_i18n8.__)("Posts Page") }) });
  }

  // packages/fields/build-module/fields/page-title/index.mjs
  var pageTitleField = {
    type: "text",
    id: "title",
    label: (0, import_i18n9.__)("Title"),
    placeholder: (0, import_i18n9.__)("No title"),
    getValue: ({ item }) => getItemTitle(item),
    render: PageTitleView,
    enableHiding: false,
    enableGlobalSearch: true,
    filterBy: false
  };
  var page_title_default = pageTitleField;

  // packages/fields/build-module/fields/template-title/index.mjs
  var import_i18n10 = __toESM(require_i18n(), 1);
  var templateTitleField = {
    id: "title",
    type: "text",
    label: (0, import_i18n10.__)("Template"),
    placeholder: (0, import_i18n10.__)("No title"),
    getValue: ({ item }) => getItemTitle(item),
    render: TitleView,
    enableHiding: false,
    enableGlobalSearch: true,
    filterBy: false
  };
  var template_title_default = templateTitleField;

  // packages/fields/build-module/fields/pattern-title/index.mjs
  var import_i18n14 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/pattern-title/view.mjs
  var import_i18n13 = __toESM(require_i18n(), 1);
  var import_patterns = __toESM(require_patterns(), 1);

  // packages/ui/build-module/badge/badge.mjs
  var import_element15 = __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: state2 = "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 ${state2} 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"));
        }
      }, [state2, name2, controlled]);
      const {
        current: defaultValue2
      } = React.useRef(defaultProp);
      React.useEffect(() => {
        if (!isControlled && serializeToDevModeString(defaultValue2) !== serializeToDevModeString(defaultProp)) {
          error([`A component is changing the default ${state2} 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 noop2 = () => {
  };
  var useIsoLayoutEffect = typeof document !== "undefined" ? React4.useLayoutEffect : noop2;

  // 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/composite/list/CompositeList.mjs
  var React6 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/internals/composite/list/CompositeListContext.mjs
  var React5 = __toESM(require_react(), 1);
  var CompositeListContext = /* @__PURE__ */ React5.createContext({
    register: () => {
    },
    unregister: () => {
    },
    subscribeMapChange: () => {
      return () => {
      };
    },
    elementsRef: {
      current: []
    },
    nextIndexRef: {
      current: 0
    }
  });
  if (true) CompositeListContext.displayName = "CompositeListContext";
  function useCompositeListContext() {
    return React5.useContext(CompositeListContext);
  }

  // node_modules/@base-ui/react/internals/composite/list/CompositeList.mjs
  var import_jsx_runtime97 = __toESM(require_jsx_runtime(), 1);
  function CompositeList(props) {
    const {
      children,
      elementsRef,
      labelsRef,
      onMapChange: onMapChangeProp
    } = props;
    const onMapChange = useStableCallback(onMapChangeProp);
    const nextIndexRef = React6.useRef(0);
    const listeners2 = useRefWithInit(createListeners).current;
    const map = useRefWithInit(createMap).current;
    const [mapTick, setMapTick] = React6.useState(0);
    const lastTickRef = React6.useRef(mapTick);
    const register5 = useStableCallback((node, metadata) => {
      map.set(node, metadata ?? null);
      lastTickRef.current += 1;
      setMapTick(lastTickRef.current);
    });
    const unregister = useStableCallback((node) => {
      map.delete(node);
      lastTickRef.current += 1;
      setMapTick(lastTickRef.current);
    });
    const sortedMap = React6.useMemo(() => {
      disableEslintWarning(mapTick);
      const newMap = /* @__PURE__ */ new Map();
      const sortedNodes = Array.from(map.keys()).filter((node) => node.isConnected).sort(sortByDocumentPosition);
      sortedNodes.forEach((node, index2) => {
        const metadata = map.get(node) ?? {};
        newMap.set(node, {
          ...metadata,
          index: index2
        });
      });
      return newMap;
    }, [map, mapTick]);
    useIsoLayoutEffect(() => {
      if (typeof MutationObserver !== "function" || sortedMap.size === 0) {
        return void 0;
      }
      const mutationObserver = new MutationObserver((entries) => {
        const diff = /* @__PURE__ */ new Set();
        const updateDiff = (node) => diff.has(node) ? diff.delete(node) : diff.add(node);
        entries.forEach((entry) => {
          entry.removedNodes.forEach(updateDiff);
          entry.addedNodes.forEach(updateDiff);
        });
        if (diff.size === 0) {
          lastTickRef.current += 1;
          setMapTick(lastTickRef.current);
        }
      });
      sortedMap.forEach((_, node) => {
        if (node.parentElement) {
          mutationObserver.observe(node.parentElement, {
            childList: true
          });
        }
      });
      return () => {
        mutationObserver.disconnect();
      };
    }, [sortedMap]);
    useIsoLayoutEffect(() => {
      const shouldUpdateLengths = lastTickRef.current === mapTick;
      if (shouldUpdateLengths) {
        if (elementsRef.current.length !== sortedMap.size) {
          elementsRef.current.length = sortedMap.size;
        }
        if (labelsRef && labelsRef.current.length !== sortedMap.size) {
          labelsRef.current.length = sortedMap.size;
        }
        nextIndexRef.current = sortedMap.size;
      }
      onMapChange(sortedMap);
    }, [onMapChange, sortedMap, elementsRef, labelsRef, mapTick]);
    useIsoLayoutEffect(() => {
      return () => {
        elementsRef.current = [];
      };
    }, [elementsRef]);
    useIsoLayoutEffect(() => {
      return () => {
        if (labelsRef) {
          labelsRef.current = [];
        }
      };
    }, [labelsRef]);
    const subscribeMapChange = useStableCallback((fn) => {
      listeners2.add(fn);
      return () => {
        listeners2.delete(fn);
      };
    });
    useIsoLayoutEffect(() => {
      listeners2.forEach((l3) => l3(sortedMap));
    }, [listeners2, sortedMap]);
    const contextValue = React6.useMemo(() => ({
      register: register5,
      unregister,
      subscribeMapChange,
      elementsRef,
      labelsRef,
      nextIndexRef
    }), [register5, unregister, subscribeMapChange, elementsRef, labelsRef, nextIndexRef]);
    return /* @__PURE__ */ (0, import_jsx_runtime97.jsx)(CompositeListContext.Provider, {
      value: contextValue,
      children
    });
  }
  function createMap() {
    return /* @__PURE__ */ new Map();
  }
  function createListeners() {
    return /* @__PURE__ */ new Set();
  }
  function sortByDocumentPosition(a3, b3) {
    const position = a3.compareDocumentPosition(b3);
    if (position & Node.DOCUMENT_POSITION_FOLLOWING || position & Node.DOCUMENT_POSITION_CONTAINED_BY) {
      return -1;
    }
    if (position & Node.DOCUMENT_POSITION_PRECEDING || position & Node.DOCUMENT_POSITION_CONTAINS) {
      return 1;
    }
    return 0;
  }
  function disableEslintWarning(_) {
  }

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

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

  // node_modules/@base-ui/utils/useMergedRefs.mjs
  function useMergedRefs(a3, b3, c6, d3) {
    const forkRef = useRefWithInit(createForkRef).current;
    if (didChange(forkRef, a3, b3, c6, d3)) {
      update(forkRef, [a3, b3, c6, d3]);
    }
    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, a3, b3, c6, d3) {
    return forkRef.refs[0] !== a3 || forkRef.refs[1] !== b3 || forkRef.refs[2] !== c6 || forkRef.refs[3] !== d3;
  }
  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 i3 = 0; i3 < refs.length; i3 += 1) {
          const ref = refs[i3];
          if (ref == null) {
            continue;
          }
          switch (typeof ref) {
            case "function": {
              const refCleanup = ref(instance);
              if (typeof refCleanup === "function") {
                cleanupCallbacks[i3] = refCleanup;
              }
              break;
            }
            case "object": {
              ref.current = instance;
              break;
            }
            default:
          }
        }
        forkRef.cleanup = () => {
          for (let i3 = 0; i3 < refs.length; i3 += 1) {
            const ref = refs[i3];
            if (ref == null) {
              continue;
            }
            switch (typeof ref) {
              case "function": {
                const cleanupCallback = cleanupCallbacks[i3];
                if (typeof cleanupCallback === "function") {
                  cleanupCallback();
                } else {
                  ref(null);
                }
                break;
              }
              case "object": {
                ref.current = null;
                break;
              }
              default:
            }
          }
        };
      }
    };
  }

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

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

  // node_modules/@base-ui/utils/getReactElementRef.mjs
  function getReactElementRef(element) {
    if (!/* @__PURE__ */ React9.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(a3, b3) {
    if (a3 && !b3) {
      return a3;
    }
    if (!a3 && b3) {
      return b3;
    }
    if (a3 || b3) {
      return {
        ...a3,
        ...b3
      };
    }
    return void 0;
  }

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

  // node_modules/@base-ui/react/internals/getStateAttributesProps.mjs
  function getStateAttributesProps(state2, customMapping) {
    const props = {};
    for (const key in state2) {
      const value = state2[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, state2) {
    return typeof className === "function" ? className(state2) : className;
  }

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

  // node_modules/@base-ui/react/merge-props/mergeProps.mjs
  var EMPTY_PROPS = {};
  function mergeProps(a3, b3, c6, d3, e3) {
    if (!c6 && !d3 && !e3 && !a3) {
      return createInitialMergedProps(b3);
    }
    let merged = createInitialMergedProps(a3);
    if (b3) {
      merged = mergeInto(merged, b3);
    }
    if (c6) {
      merged = mergeInto(merged, c6);
    }
    if (d3) {
      merged = mergeInto(merged, d3);
    }
    if (e3) {
      merged = mergeInto(merged, e3);
    }
    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 i3 = 1; i3 < props.length; i3 += 1) {
      merged = mergeInto(merged, props[i3]);
    }
    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 state2 = params.state ?? EMPTY_OBJECT3;
    return evaluateRenderProp(element, renderProp, outProps, state2);
  }
  function useRenderElementProps(componentProps, params = {}) {
    const {
      className: classNameProp,
      style: styleProp,
      render: renderProp
    } = componentProps;
    const {
      state: state2 = EMPTY_OBJECT3,
      ref,
      props,
      stateAttributesMapping: stateAttributesMapping6,
      enabled = true
    } = params;
    const className = enabled ? resolveClassName(classNameProp, state2) : void 0;
    const style = enabled ? resolveStyle2(styleProp, state2) : void 0;
    const stateProps = enabled ? getStateAttributesProps(state2, stateAttributesMapping6) : EMPTY_OBJECT3;
    const resolvedProps = enabled && props ? resolveRenderFunctionProps(props) : void 0;
    const outProps = enabled ? mergeObjects(stateProps, resolvedProps) ?? {} : EMPTY_OBJECT3;
    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_OBJECT3;
    }
    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, render5, props, state2) {
    if (render5) {
      if (typeof render5 === "function") {
        if (true) {
          warnIfRenderPropLooksLikeComponent(render5);
        }
        return render5(props, state2);
      }
      const mergedProps = mergeProps(props, render5.props);
      mergedProps.ref = props.ref;
      let newElement = render5;
      if (newElement?.$$typeof === REACT_LAZY_TYPE) {
        const children = React10.Children.toArray(render5);
        newElement = children[0];
      }
      if (true) {
        if (!/* @__PURE__ */ React10.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__ */ React10.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__ */ React10.createElement(Tag, props);
  }

  // node_modules/@base-ui/utils/useId.mjs
  var React11 = __toESM(require_react(), 1);
  var globalId = 0;
  function useGlobalId(idOverride, prefix2 = "mui") {
    const [defaultId, setDefaultId] = React11.useState(idOverride);
    const id = idOverride || defaultId;
    React11.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 React14 = __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_OBJECT3;
    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 React13 = __toESM(require_react(), 1);

  // node_modules/@base-ui/utils/useOnMount.mjs
  var React12 = __toESM(require_react(), 1);
  var EMPTY = [];
  function useOnMount(fn) {
    React12.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 i3 = 0; i3 < currentCallbacks.length; i3 += 1) {
          currentCallbacks[i3]?.(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] = React13.useState(open && enableIdleState ? "idle" : void 0);
    const [mounted, setMounted] = React13.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] = React14.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 React14.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 React15 = __toESM(require_react(), 1);
  var CollapsibleRootContext = /* @__PURE__ */ React15.createContext(void 0);
  if (true) CollapsibleRootContext.displayName = "CollapsibleRootContext";
  function useCollapsibleRootContext() {
    const context = React15.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/composite/list/useCompositeListItem.mjs
  var React16 = __toESM(require_react(), 1);
  var IndexGuessBehavior = /* @__PURE__ */ (function(IndexGuessBehavior2) {
    IndexGuessBehavior2[IndexGuessBehavior2["None"] = 0] = "None";
    IndexGuessBehavior2[IndexGuessBehavior2["GuessFromOrder"] = 1] = "GuessFromOrder";
    return IndexGuessBehavior2;
  })({});
  function useCompositeListItem(params = {}) {
    const {
      label,
      metadata,
      textRef,
      indexGuessBehavior,
      index: externalIndex
    } = params;
    const {
      register: register5,
      unregister,
      subscribeMapChange,
      elementsRef,
      labelsRef,
      nextIndexRef
    } = useCompositeListContext();
    const indexRef = React16.useRef(-1);
    const [index2, setIndex] = React16.useState(externalIndex ?? (indexGuessBehavior === IndexGuessBehavior.GuessFromOrder ? () => {
      if (indexRef.current === -1) {
        const newIndex = nextIndexRef.current;
        nextIndexRef.current += 1;
        indexRef.current = newIndex;
      }
      return indexRef.current;
    } : -1));
    const componentRef = React16.useRef(null);
    const ref = React16.useCallback((node) => {
      componentRef.current = node;
      if (index2 !== -1 && node !== null) {
        elementsRef.current[index2] = node;
        if (labelsRef) {
          const isLabelDefined = label !== void 0;
          labelsRef.current[index2] = isLabelDefined ? label : textRef?.current?.textContent ?? node.textContent;
        }
      }
    }, [index2, elementsRef, labelsRef, label, textRef]);
    useIsoLayoutEffect(() => {
      if (externalIndex != null) {
        return void 0;
      }
      const node = componentRef.current;
      if (node) {
        register5(node, metadata);
        return () => {
          unregister(node);
        };
      }
      return void 0;
    }, [externalIndex, register5, unregister, metadata]);
    useIsoLayoutEffect(() => {
      if (externalIndex != null) {
        return void 0;
      }
      return subscribeMapChange((map) => {
        const i3 = componentRef.current ? map.get(componentRef.current)?.index : null;
        if (i3 != null) {
          setIndex(i3);
        }
      });
    }, [externalIndex, subscribeMapChange, setIndex]);
    return {
      ref,
      index: index2
    };
  }

  // 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 React19 = __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 React17 = __toESM(require_react(), 1);
  var CompositeRootContext = /* @__PURE__ */ React17.createContext(void 0);
  if (true) CompositeRootContext.displayName = "CompositeRootContext";
  function useCompositeRootContext(optional = false) {
    const context = React17.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 React18 = __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 = React18.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 = React19.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) {
      React19.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 = React19.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 = React19.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 React21 = __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 React20 = __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);
    React20.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 = React21.useRef(null);
    const animationTypeRef = React21.useRef(null);
    const [dimensions, setDimensionsUnwrapped] = React21.useState(EMPTY_DIMENSIONS);
    const lastMeasuredDimensionsRef = React21.useRef(EMPTY_DIMENSIONS);
    const shouldSkipNextOpenRef = React21.useRef(false);
    const shouldPreventMountAnimationRef = React21.useRef(open);
    const shouldPreventActivityResumeAnimationRef = React21.useRef(false);
    const [forcePanelIdle, setForcePanelIdle] = React21.useState(false);
    const pendingTemporaryStyleRestoreRef = React21.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]);
    React21.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);
      }
    });
    React21.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]);
    React21.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 React22 = __toESM(require_react(), 1);
  function useOnFirstRender(fn) {
    const ref = React22.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 React23 = __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_runtime98 = __toESM(require_jsx_runtime(), 1);
  var FloatingDelayGroupContext = /* @__PURE__ */ React23.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 = React23.useRef(delay);
    const initialDelayRef = React23.useRef(delay);
    const currentIdRef = React23.useRef(null);
    const currentContextRef = React23.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_runtime98.jsx)(FloatingDelayGroupContext.Provider, {
      value: React23.useMemo(() => ({
        hasProvider: true,
        delayRef,
        initialDelayRef,
        currentIdRef,
        timeoutMs,
        currentContextRef,
        timeout
      }), [timeoutMs, timeout]),
      children
    });
  }
  function useDelayGroup(context, options = {
    open: false
  }) {
    const {
      open
    } = options;
    const store4 = "rootStore" in context ? context.rootStore : context;
    const floatingId = store4.useState("floatingId");
    const groupContext = React23.useContext(FloatingDelayGroupContext);
    const {
      currentIdRef,
      delayRef,
      timeoutMs,
      initialDelayRef,
      currentContextRef,
      hasProvider,
      timeout
    } = groupContext;
    const [isInstantPhase, setIsInstantPhase] = React23.useState(false);
    const openRef = React23.useRef(open);
    const isUnmountedRef = React23.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 (store4.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, store4]);
    useIsoLayoutEffect(() => {
      if (!open) {
        return;
      }
      const prevContext = currentContextRef.current;
      const prevId = currentIdRef.current;
      timeout.clear();
      currentContextRef.current = {
        onOpenChange: store4.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, store4, 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 React23.useMemo(() => ({
      hasProvider,
      delayRef,
      isInstantPhase
    }), [hasProvider, delayRef, isInstantPhase]);
  }

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

  // node_modules/@base-ui/react/utils/FocusGuard.mjs
  var React24 = __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_runtime99 = __toESM(require_jsx_runtime(), 1);
  var FocusGuard = /* @__PURE__ */ React24.forwardRef(function FocusGuard2(props, ref) {
    const [role, setRole] = React24.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_runtime99.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 = (v3) => ({
    x: v3,
    y: v3
  });
  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 length2 = getAxisLength(alignmentAxis);
    let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top";
    if (rects.reference[length2] > rects.floating[length2]) {
      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: y3,
      width,
      height
    } = rect;
    return {
      width,
      height,
      top: y3,
      left: x2,
      right: x2 + width,
      bottom: y3 + height,
      x: x2,
      y: y3
    };
  }

  // node_modules/@base-ui/react/floating-ui-react/utils/composite.mjs
  function isIndexOutOfListBounds(list, index2) {
    return index2 < 0 || index2 >= list.length;
  }
  function getMinListIndex(listRef, disabledIndices) {
    return findNonDisabledListIndex(listRef.current, {
      disabledIndices
    });
  }
  function getMaxListIndex(listRef, disabledIndices) {
    return findNonDisabledListIndex(listRef.current, {
      decrement: true,
      startingIndex: listRef.current.length,
      disabledIndices
    });
  }
  function findNonDisabledListIndex(list, {
    startingIndex = -1,
    decrement = false,
    disabledIndices,
    amount = 1
  } = {}) {
    let index2 = startingIndex;
    do {
      index2 += decrement ? -amount : amount;
    } while (index2 >= 0 && index2 <= list.length - 1 && isListIndexDisabled(list, index2, disabledIndices));
    return index2;
  }
  function isListIndexDisabled(list, index2, disabledIndices) {
    const isExplicitlyDisabled = typeof disabledIndices === "function" ? disabledIndices(index2) : disabledIndices?.includes(index2) ?? false;
    if (isExplicitlyDisabled) {
      return true;
    }
    const element = list[index2];
    if (!element) {
      return false;
    }
    if (!isElementVisible(element)) {
      return true;
    }
    return !disabledIndices && (element.hasAttribute("disabled") || element.getAttribute("aria-disabled") === "true");
  }
  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 len2 = list.length;
    if (len2 === 0) {
      return void 0;
    }
    const active = activeElement(ownerDocument(container));
    const index2 = list.indexOf(active);
    const nextIndex = index2 === -1 ? dir === 1 ? 0 : len2 - 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 React25 = __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_runtime100 = __toESM(require_jsx_runtime(), 1);
  var PortalContext = /* @__PURE__ */ React25.createContext(null);
  if (true) PortalContext.displayName = "PortalContext";
  var usePortalContext = () => React25.useContext(PortalContext);
  var attr = createAttribute("portal");
  function useFloatingPortalNode(props = {}) {
    const {
      ref,
      container: containerProp,
      componentProps = EMPTY_OBJECT3,
      elementProps
    } = props;
    const uniqueId = useId();
    const portalContext = usePortalContext();
    const parentPortalNode = portalContext?.portalNode;
    const [containerElement, setContainerElement] = React25.useState(null);
    const [portalNode, setPortalNode] = React25.useState(null);
    const setPortalNodeRef = useStableCallback((node) => {
      if (node !== null) {
        setPortalNode(node);
      }
    });
    const containerRef = React25.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__ */ React25.forwardRef(function FloatingPortal2(componentProps, forwardedRef) {
    const {
      render: render5,
      className,
      style,
      children,
      container,
      renderGuards,
      ...elementProps
    } = componentProps;
    const {
      portalNode,
      portalSubtree
    } = useFloatingPortalNode({
      container,
      ref: forwardedRef,
      componentProps,
      elementProps
    });
    const beforeOutsideRef = React25.useRef(null);
    const afterOutsideRef = React25.useRef(null);
    const beforeInsideRef = React25.useRef(null);
    const afterInsideRef = React25.useRef(null);
    const [focusManagerState, setFocusManagerState] = React25.useState(null);
    const focusInsideDisabledRef = React25.useRef(false);
    const modal = focusManagerState?.modal;
    const open = focusManagerState?.open;
    const shouldRenderGuards = typeof renderGuards === "boolean" ? renderGuards : !!focusManagerState && !focusManagerState.modal && focusManagerState.open && !!portalNode;
    React25.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 = React25.useMemo(() => ({
      beforeOutsideRef,
      afterOutsideRef,
      beforeInsideRef,
      afterInsideRef,
      portalNode,
      setFocusManagerState
    }), [portalNode]);
    return /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(React25.Fragment, {
      children: [portalSubtree, /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(PortalContext.Provider, {
        value: portalContextValue,
        children: [shouldRenderGuards && portalNode && /* @__PURE__ */ (0, import_jsx_runtime100.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_runtime100.jsx)("span", {
          "aria-owns": portalNode.id,
          style: ownerVisuallyHidden
        }), portalNode && /* @__PURE__ */ ReactDOM2.createPortal(children, portalNode), shouldRenderGuards && portalNode && /* @__PURE__ */ (0, import_jsx_runtime100.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 React26 = __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_runtime101 = __toESM(require_jsx_runtime(), 1);
  var FloatingNodeContext = /* @__PURE__ */ React26.createContext(null);
  if (true) FloatingNodeContext.displayName = "FloatingNodeContext";
  var FloatingTreeContext = /* @__PURE__ */ React26.createContext(null);
  if (true) FloatingTreeContext.displayName = "FloatingTreeContext";
  var useFloatingParentNodeId = () => React26.useContext(FloatingNodeContext)?.id || null;
  var useFloatingTree = (externalTree) => {
    const contextTree = React26.useContext(FloatingTreeContext);
    return externalTree ?? contextTree;
  };

  // node_modules/@base-ui/react/floating-ui-react/hooks/useClientPoint.mjs
  var React27 = __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 y3 = 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;
        y3 -= 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;
          y3 = isYAxis && data.y != null ? data.y : y3;
        } 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: y3,
          top: y3,
          right: x2 + width,
          bottom: y3 + height,
          left: x2
        };
      }
    };
  }
  function isMouseBasedEvent(event) {
    return event != null && event.clientX != null;
  }
  function useClientPoint(context, props = {}) {
    const {
      enabled = true,
      axis = "both"
    } = props;
    const store4 = "rootStore" in context ? context.rootStore : context;
    const open = store4.useState("open");
    const floating = store4.useState("floatingElement");
    const domReference = store4.useState("domReferenceElement");
    const dataRef = store4.context.dataRef;
    const initialRef = React27.useRef(false);
    const cleanupListenerRef = React27.useRef(null);
    const [pointerType, setPointerType] = React27.useState();
    const [reactive, setReactive] = React27.useState([]);
    const resetReference = useStableCallback((reference2) => {
      store4.set("positionReference", reference2);
    });
    const setReference = useStableCallback((newX, newY, referenceElement) => {
      if (initialRef.current) {
        return;
      }
      if (dataRef.current.openEvent && !isMouseBasedEvent(dataRef.current.openEvent)) {
        return;
      }
      store4.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;
    React27.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, store4, setReference, resetReference, reactive]);
    React27.useEffect(() => () => {
      store4.set("positionReference", null);
    }, [store4]);
    React27.useEffect(() => {
      if (enabled && !floating) {
        initialRef.current = false;
      }
    }, [enabled, floating]);
    React27.useEffect(() => {
      if (!enabled && open) {
        initialRef.current = true;
      }
    }, [enabled, open]);
    const reference = React27.useMemo(() => {
      function setPointerTypeRef(event) {
        setPointerType(event.pointerType);
      }
      return {
        onPointerDown: setPointerTypeRef,
        onPointerEnter: setPointerTypeRef,
        onMouseMove: handleReferenceEnterOrMove,
        onMouseEnter: handleReferenceEnterOrMove
      };
    }, [handleReferenceEnterOrMove]);
    return React27.useMemo(() => enabled ? {
      reference,
      trigger: reference
    } : {}, [enabled, reference]);
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useDismiss.mjs
  var React28 = __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 store4 = "rootStore" in context ? context.rootStore : context;
    const open = store4.useState("open");
    const floatingElement = store4.useState("floatingElement");
    const {
      dataRef
    } = store4.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 = React28.useRef(false);
    const pressStartPreventedRef = React28.useRef(false);
    const suppressNextOutsideClickRef = React28.useRef(false);
    const isComposingRef = React28.useRef(false);
    const currentPointerTypeRef = React28.useRef("");
    const touchStateRef = React28.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, store4.select("floatingElement")) || isEventTargetWithin(event, store4.select("domReferenceElement"));
    });
    const closeOnReferencePress = useStableCallback((event) => {
      if (!referencePress()) {
        return;
      }
      store4.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);
      store4.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(store4.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;
      }
    });
    React28.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(store4.select("floatingElement"))).querySelectorAll(inertSelector));
        const triggers = store4.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, store4.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 isRTL24 = style.direction === "rtl";
          const pressedVerticalScrollbar = canScrollY && (isRTL24 ? 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;
        }
        store4.setOpen(false, createChangeEventDetails(reason_parts_exports.outsidePress, event));
        clearInsideReactTree();
      }
      function handlePointerDown(event) {
        if (getOutsidePressEvent() !== "sloppy" || event.pointerType === "touch" || !store4.select("open") || !enabled || isEventWithinOwnElements(event)) {
          return;
        }
        closeOnPressOutside(event);
      }
      function handleTouchStart(event) {
        if (getOutsidePressEvent() !== "sloppy" || !store4.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 distance2 = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
        if (distance2 > 5) {
          touchStateRef.current.dismissOnTouchEnd = true;
        }
        if (distance2 > 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, store4, cancelDismissOnEndTimeout]);
    React28.useEffect(clearInsideReactTree, [outsidePress2, clearInsideReactTree]);
    const reference = React28.useMemo(() => ({
      onKeyDown: closeOnEscapeKeyDown,
      onPointerDown: closeOnReferencePress,
      onClick: closeOnReferencePress
    }), [closeOnEscapeKeyDown, closeOnReferencePress]);
    const floating = React28.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 React28.useMemo(() => enabled ? {
      reference,
      floating,
      trigger: reference
    } : {}, [enabled, reference, floating]);
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useFloating.mjs
  var React36 = __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(state2, options) {
    var _await$platform$isEle;
    if (options === void 0) {
      options = {};
    }
    const {
      x: x2,
      y: y3,
      platform: platform3,
      rects,
      elements: elements2,
      strategy
    } = state2;
    const {
      boundary = "clippingAncestors",
      rootBoundary = "viewport",
      elementContext = "floating",
      altBoundary = false,
      padding = 0
    } = evaluate(options, state2);
    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: y3,
      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: y3
    } = computeCoordsFromPlacement(rects, placement, rtl);
    let statefulPlacement = placement;
    let resetCount = 0;
    const middlewareData = {};
    for (let i3 = 0; i3 < middleware.length; i3++) {
      const currentMiddleware = middleware[i3];
      if (!currentMiddleware) {
        continue;
      }
      const {
        name: name2,
        fn
      } = currentMiddleware;
      const {
        x: nextX,
        y: nextY,
        data,
        reset
      } = await fn({
        x: x2,
        y: y3,
        initialPlacement: placement,
        placement: statefulPlacement,
        strategy,
        middlewareData,
        rects,
        platform: platformWithDetectOverflow,
        elements: {
          reference,
          floating
        }
      });
      x2 = nextX != null ? nextX : x2;
      y3 = nextY != null ? nextY : y3;
      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: y3
          } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
        }
        i3 = -1;
      }
    }
    return {
      x: x2,
      y: y3,
      placement: statefulPlacement,
      strategy,
      middlewareData
    };
  };
  var flip = function(options) {
    if (options === void 0) {
      options = {};
    }
    return {
      name: "flip",
      options,
      async fn(state2) {
        var _middlewareData$arrow, _middlewareData$flip;
        const {
          placement,
          middlewareData,
          rects,
          initialPlacement,
          platform: platform3,
          elements: elements2
        } = state2;
        const {
          mainAxis: checkMainAxis = true,
          crossAxis: checkCrossAxis = true,
          fallbackPlacements: specifiedFallbackPlacements,
          fallbackStrategy = "bestFit",
          fallbackAxisSideDirection = "none",
          flipAlignment = true,
          ...detectOverflowOptions
        } = evaluate(options, state2);
        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(state2, detectOverflowOptions);
        const overflows = [];
        let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
        if (checkMainAxis) {
          overflows.push(overflow[side]);
        }
        if (checkCrossAxis) {
          const sides3 = getAlignmentSides(placement, rects, rtl);
          overflows.push(overflow[sides3[0]], overflow[sides3[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((d3) => getSideAxis(d3.placement) === initialSideAxis ? d3.overflows[0] > 0 : true)) {
              return {
                data: {
                  index: nextIndex,
                  overflows: overflowsData
                },
                reset: {
                  placement: nextPlacement
                }
              };
            }
          }
          let resetPlacement = (_overflowsData$filter = overflowsData.filter((d3) => d3.overflows[0] <= 0).sort((a3, b3) => a3.overflows[1] - b3.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
          if (!resetPlacement) {
            switch (fallbackStrategy) {
              case "bestFit": {
                var _overflowsData$filter2;
                const placement2 = (_overflowsData$filter2 = overflowsData.filter((d3) => {
                  if (hasFallbackAxisSideDirection) {
                    const currentSideAxis = getSideAxis(d3.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((d3) => [d3.placement, d3.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a3, b3) => a3[1] - b3[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(state2) {
        const {
          rects,
          platform: platform3
        } = state2;
        const {
          strategy = "referenceHidden",
          ...detectOverflowOptions
        } = evaluate(options, state2);
        switch (strategy) {
          case "referenceHidden": {
            const overflow = await platform3.detectOverflow(state2, {
              ...detectOverflowOptions,
              elementContext: "reference"
            });
            const offsets = getSideOffsets(overflow, rects.reference);
            return {
              data: {
                referenceHiddenOffsets: offsets,
                referenceHidden: isAnySideFullyClipped(offsets)
              }
            };
          }
          case "escaped": {
            const overflow = await platform3.detectOverflow(state2, {
              ...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(state2, options) {
    const {
      placement,
      platform: platform3,
      elements: elements2
    } = state2;
    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, state2);
    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(state2) {
        var _middlewareData$offse, _middlewareData$arrow;
        const {
          x: x2,
          y: y3,
          placement,
          middlewareData
        } = state2;
        const diffCoords = await convertValueToCoords(state2, 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: y3 + diffCoords.y,
          data: {
            ...diffCoords,
            placement
          }
        };
      }
    };
  };
  var shift = function(options) {
    if (options === void 0) {
      options = {};
    }
    return {
      name: "shift",
      options,
      async fn(state2) {
        const {
          x: x2,
          y: y3,
          placement,
          platform: platform3
        } = state2;
        const {
          mainAxis: checkMainAxis = true,
          crossAxis: checkCrossAxis = false,
          limiter = {
            fn: (_ref) => {
              let {
                x: x3,
                y: y4
              } = _ref;
              return {
                x: x3,
                y: y4
              };
            }
          },
          ...detectOverflowOptions
        } = evaluate(options, state2);
        const coords = {
          x: x2,
          y: y3
        };
        const overflow = await platform3.detectOverflow(state2, 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 min3 = mainAxisCoord + overflow[minSide];
          const max3 = mainAxisCoord - overflow[maxSide];
          mainAxisCoord = clamp(min3, mainAxisCoord, max3);
        }
        if (checkCrossAxis) {
          const minSide = crossAxis === "y" ? "top" : "left";
          const maxSide = crossAxis === "y" ? "bottom" : "right";
          const min3 = crossAxisCoord + overflow[minSide];
          const max3 = crossAxisCoord - overflow[maxSide];
          crossAxisCoord = clamp(min3, crossAxisCoord, max3);
        }
        const limitedCoords = limiter.fn({
          ...state2,
          [mainAxis]: mainAxisCoord,
          [crossAxis]: crossAxisCoord
        });
        return {
          ...limitedCoords,
          data: {
            x: limitedCoords.x - x2,
            y: limitedCoords.y - y3,
            enabled: {
              [mainAxis]: checkMainAxis,
              [crossAxis]: checkCrossAxis
            }
          }
        };
      }
    };
  };
  var limitShift = function(options) {
    if (options === void 0) {
      options = {};
    }
    return {
      options,
      fn(state2) {
        const {
          x: x2,
          y: y3,
          placement,
          rects,
          middlewareData
        } = state2;
        const {
          offset: offset4 = 0,
          mainAxis: checkMainAxis = true,
          crossAxis: checkCrossAxis = true
        } = evaluate(options, state2);
        const coords = {
          x: x2,
          y: y3
        };
        const crossAxis = getSideAxis(placement);
        const mainAxis = getOppositeAxis(crossAxis);
        let mainAxisCoord = coords[mainAxis];
        let crossAxisCoord = coords[crossAxis];
        const rawOffset = evaluate(offset4, state2);
        const computedOffset = typeof rawOffset === "number" ? {
          mainAxis: rawOffset,
          crossAxis: 0
        } : {
          mainAxis: 0,
          crossAxis: 0,
          ...rawOffset
        };
        if (checkMainAxis) {
          const len2 = mainAxis === "y" ? "height" : "width";
          const limitMin = rects.reference[mainAxis] - rects.floating[len2] + computedOffset.mainAxis;
          const limitMax = rects.reference[mainAxis] + rects.reference[len2] - computedOffset.mainAxis;
          if (mainAxisCoord < limitMin) {
            mainAxisCoord = limitMin;
          } else if (mainAxisCoord > limitMax) {
            mainAxisCoord = limitMax;
          }
        }
        if (checkCrossAxis) {
          var _middlewareData$offse, _middlewareData$offse2;
          const len2 = mainAxis === "y" ? "width" : "height";
          const isOriginSide = originSides.has(getSide(placement));
          const limitMin = rects.reference[crossAxis] - rects.floating[len2] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);
          const limitMax = rects.reference[crossAxis] + rects.reference[len2] + (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(state2) {
        var _state$middlewareData, _state$middlewareData2;
        const {
          placement,
          rects,
          platform: platform3,
          elements: elements2
        } = state2;
        const {
          apply = () => {
          },
          ...detectOverflowOptions
        } = evaluate(options, state2);
        const overflow = await platform3.detectOverflow(state2, 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 = !state2.middlewareData.shift;
        let availableHeight = overflowAvailableHeight;
        let availableWidth = overflowAvailableWidth;
        if ((_state$middlewareData = state2.middlewareData.shift) != null && _state$middlewareData.enabled.x) {
          availableWidth = maximumClippingWidth;
        }
        if ((_state$middlewareData2 = state2.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({
          ...state2,
          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 y3 = ($2 ? round(rect.height) : rect.height) / height;
    if (!x2 || !Number.isFinite(x2)) {
      x2 = 1;
    }
    if (!y3 || !Number.isFinite(y3)) {
      y3 = 1;
    }
    return {
      x: x2,
      y: y3
    };
  }
  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 scale3 = createCoords(1);
    if (includeScale) {
      if (offsetParent) {
        if (isElement(offsetParent)) {
          scale3 = getScale(offsetParent);
        }
      } else {
        scale3 = getScale(element);
      }
    }
    const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
    let x2 = (clientRect.left + visualOffsets.x) / scale3.x;
    let y3 = (clientRect.top + visualOffsets.y) / scale3.y;
    let width = clientRect.width / scale3.x;
    let height = clientRect.height / scale3.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;
        y3 *= iframeScale.y;
        width *= iframeScale.x;
        height *= iframeScale.y;
        x2 += left;
        y3 += top;
        currentWin = getWindow(currentIFrame);
        currentIFrame = getFrameElement(currentWin);
      }
    }
    return rectToClientRect({
      width,
      height,
      x: x2,
      y: y3
    });
  }
  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 y3 = htmlRect.top + scroll.scrollTop;
    return {
      x: x2,
      y: y3
    };
  }
  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 scale3 = 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);
        scale3 = 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 * scale3.x,
      height: rect.height * scale3.y,
      x: rect.x * scale3.x - scroll.scrollLeft * scale3.x + offsets.x + htmlOffset.x,
      y: rect.y * scale3.y - scroll.scrollTop * scale3.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 y3 = -scroll.scrollTop;
    if (getComputedStyle2(body).direction === "rtl") {
      x2 += max(html.clientWidth, body.clientWidth) - width;
    }
    return {
      width,
      height,
      x: x2,
      y: y3
    };
  }
  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 y3 = 0;
    if (visualViewport) {
      width = visualViewport.width;
      height = visualViewport.height;
      const visualViewportBased = isWebKit();
      if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
        x2 = visualViewport.offsetLeft;
        y3 = 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: y3
    };
  }
  function getInnerBoundingClientRect(element, strategy) {
    const clientRect = getBoundingClientRect(element, true, strategy === "fixed");
    const top = clientRect.top + element.clientTop;
    const left = clientRect.left + element.clientLeft;
    const scale3 = isHTMLElement(element) ? getScale(element) : createCoords(1);
    const width = element.clientWidth * scale3.x;
    const height = element.clientHeight * scale3.y;
    const x2 = left * scale3.x;
    const y3 = top * scale3.y;
    return {
      width,
      height,
      x: x2,
      y: y3
    };
  }
  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 i3 = 1; i3 < clippingAncestors.length; i3++) {
      const rect = getClientRectFromClippingAncestor(element, clippingAncestors[i3], 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 y3 = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;
    return {
      x: x2,
      y: y3,
      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(a3, b3) {
    return a3.x === b3.x && a3.y === b3.y && a3.width === b3.width && a3.height === b3.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 React29 = __toESM(require_react(), 1);
  var import_react2 = __toESM(require_react(), 1);
  var ReactDOM3 = __toESM(require_react_dom(), 1);
  var isClient = typeof document !== "undefined";
  var noop3 = function noop4() {
  };
  var index = isClient ? import_react2.useLayoutEffect : noop3;
  function deepEqual(a3, b3) {
    if (a3 === b3) {
      return true;
    }
    if (typeof a3 !== typeof b3) {
      return false;
    }
    if (typeof a3 === "function" && a3.toString() === b3.toString()) {
      return true;
    }
    let length2;
    let i3;
    let keys;
    if (a3 && b3 && typeof a3 === "object") {
      if (Array.isArray(a3)) {
        length2 = a3.length;
        if (length2 !== b3.length) return false;
        for (i3 = length2; i3-- !== 0; ) {
          if (!deepEqual(a3[i3], b3[i3])) {
            return false;
          }
        }
        return true;
      }
      keys = Object.keys(a3);
      length2 = keys.length;
      if (length2 !== Object.keys(b3).length) {
        return false;
      }
      for (i3 = length2; i3-- !== 0; ) {
        if (!{}.hasOwnProperty.call(b3, keys[i3])) {
          return false;
        }
      }
      for (i3 = length2; i3-- !== 0; ) {
        const key = keys[i3];
        if (key === "_owner" && a3.$$typeof) {
          continue;
        }
        if (!deepEqual(a3[key], b3[key])) {
          return false;
        }
      }
      return true;
    }
    return a3 !== a3 && b3 !== b3;
  }
  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 = React29.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] = React29.useState({
      x: 0,
      y: 0,
      strategy,
      placement,
      middlewareData: {},
      isPositioned: false
    });
    const [latestMiddleware, setLatestMiddleware] = React29.useState(middleware);
    if (!deepEqual(latestMiddleware, middleware)) {
      setLatestMiddleware(middleware);
    }
    const [_reference, _setReference] = React29.useState(null);
    const [_floating, _setFloating] = React29.useState(null);
    const setReference = React29.useCallback((node) => {
      if (node !== referenceRef.current) {
        referenceRef.current = node;
        _setReference(node);
      }
    }, []);
    const setFloating = React29.useCallback((node) => {
      if (node !== floatingRef.current) {
        floatingRef.current = node;
        _setFloating(node);
      }
    }, []);
    const referenceEl = externalReference || _reference;
    const floatingEl = externalFloating || _floating;
    const referenceRef = React29.useRef(null);
    const floatingRef = React29.useRef(null);
    const dataRef = React29.useRef(data);
    const hasWhileElementsMounted = whileElementsMounted != null;
    const whileElementsMountedRef = useLatestRef(whileElementsMounted);
    const platformRef = useLatestRef(platform3);
    const openRef = useLatestRef(open);
    const update4 = React29.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 = React29.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 = React29.useMemo(() => ({
      reference: referenceRef,
      floating: floatingRef,
      setReference,
      setFloating
    }), [setReference, setFloating]);
    const elements2 = React29.useMemo(() => ({
      reference: referenceEl,
      floating: floatingEl
    }), [referenceEl, floatingEl]);
    const floatingStyles = React29.useMemo(() => {
      const initialStyles = {
        position: strategy,
        left: 0,
        top: 0
      };
      if (!elements2.floating) {
        return initialStyles;
      }
      const x2 = roundByDPR(elements2.floating, data.x);
      const y3 = roundByDPR(elements2.floating, data.y);
      if (transform) {
        return {
          ...initialStyles,
          transform: "translate(" + x2 + "px, " + y3 + "px)",
          ...getDPR(elements2.floating) >= 1.5 && {
            willChange: "transform"
          }
        };
      }
      return {
        position: strategy,
        left: x2,
        top: y3
      };
    }, [strategy, transform, elements2.floating, data.x, data.y]);
    return React29.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 React35 = __toESM(require_react(), 1);
  var ReactDOM4 = __toESM(require_react_dom(), 1);

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

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

  // node_modules/@base-ui/utils/store/useStore.mjs
  var React31 = __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 React30 = __toESM(require_react(), 1);
  var hooks = [];
  var currentInstance = void 0;
  function getInstance() {
    return currentInstance;
  }
  function register(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__ */ React30.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(store4, selector2, a1, a22, a3) {
    return useStoreImplementation(store4, selector2, a1, a22, a3);
  }
  function useStoreR19(store4, selector2, a1, a22, a3) {
    const getSelection = React31.useCallback(() => selector2(store4.getSnapshot(), a1, a22, a3), [store4, selector2, a1, a22, a3]);
    return (0, import_shim.useSyncExternalStore)(store4.subscribe, getSelection, getSelection);
  }
  register({
    before(instance) {
      instance.syncIndex = 0;
      if (!instance.didInitialize) {
        instance.syncTick = 1;
        instance.syncHooks = [];
        instance.didChangeStore = true;
        instance.getSnapshot = () => {
          let didChange2 = false;
          for (let i3 = 0; i3 < instance.syncHooks.length; i3 += 1) {
            const hook = instance.syncHooks[i3];
            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 store4 of stores) {
              unsubscribes.push(store4.subscribe(onStoreChange));
            }
            return () => {
              for (const unsubscribe of unsubscribes) {
                unsubscribe();
              }
            };
          };
        }
        (0, import_shim.useSyncExternalStore)(instance.subscribe, instance.getSnapshot, instance.getSnapshot);
      }
    }
  });
  function useStoreFast(store4, selector2, a1, a22, a3) {
    const instance = getInstance();
    if (!instance) {
      return useStoreR19(store4, selector2, a1, a22, a3);
    }
    const index2 = instance.syncIndex;
    instance.syncIndex += 1;
    let hook;
    if (!instance.didInitialize) {
      hook = {
        store: store4,
        selector: selector2,
        a1,
        a2: a22,
        a3,
        value: selector2(store4.getSnapshot(), a1, a22, a3)
      };
      instance.syncHooks.push(hook);
    } else {
      hook = instance.syncHooks[index2];
      if (hook.store !== store4 || hook.selector !== selector2 || !Object.is(hook.a1, a1) || !Object.is(hook.a2, a22) || !Object.is(hook.a3, a3)) {
        if (hook.store !== store4) {
          instance.didChangeStore = true;
        }
        hook.store = store4;
        hook.selector = selector2;
        hook.a1 = a1;
        hook.a2 = a22;
        hook.a3 = a3;
        hook.value = selector2(store4.getSnapshot(), a1, a22, a3);
      }
    }
    return hook.value;
  }
  function useStoreLegacy(store4, selector2, a1, a22, a3) {
    return (0, import_with_selector.useSyncExternalStoreWithSelector)(store4.subscribe, store4.getSnapshot, store4.getSnapshot, (state2) => selector2(state2, a1, a22, 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(state2) {
      this.state = state2;
      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, a22, a3) {
      return useStore(this, selector2, a1, a22, a3);
    }
  };

  // node_modules/@base-ui/utils/store/ReactStore.mjs
  var React32 = __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(state2, context = {}, selectors3) {
      super(state2);
      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) {
      React32.useDebugValue(key);
      const store4 = this;
      useIsoLayoutEffect(() => {
        if (store4.state[key] !== value) {
          store4.set(key, value);
        }
      }, [store4, 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 store4 = this;
      useIsoLayoutEffect(() => {
        if (store4.state[key] !== value) {
          store4.set(key, value);
        }
        return () => {
          store4.set(key, void 0);
        };
      }, [store4, 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 store4 = this;
      if (true) {
        React32.useDebugValue(statePart, (p4) => Object.keys(p4));
        const keys = React32.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(() => {
        store4.update(statePart);
      }, [store4, ...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) {
      React32.useDebugValue(key);
      const store4 = this;
      const isControlled = controlled !== void 0;
      useIsoLayoutEffect(() => {
        if (isControlled && !Object.is(store4.state[key], controlled)) {
          store4.setState({
            ...store4.state,
            [key]: controlled
          });
        }
      }, [store4, 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, a22, a3) {
      const selector2 = this.selectors[key];
      return selector2(this.state, a1, a22, 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, a22, a3) {
      React32.useDebugValue(key);
      return useStore(this, this.selectors[key], a1, a22, 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) {
      React32.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 = React32.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/utils/useForcedRerendering.mjs
  var React33 = __toESM(require_react(), 1);
  function useForcedRerendering() {
    const [, setState] = React33.useState({});
    return React33.useCallback(() => {
      setState({});
    }, []);
  }

  // node_modules/@base-ui/react/floating-ui-react/components/FloatingRootStore.mjs
  var selectors = {
    open: createSelector3((state2) => state2.open),
    transitionStatus: createSelector3((state2) => state2.transitionStatus),
    domReferenceElement: createSelector3((state2) => state2.domReferenceElement),
    referenceElement: createSelector3((state2) => state2.positionReference ?? state2.referenceElement),
    floatingElement: createSelector3((state2) => state2.floatingElement),
    floatingId: createSelector3((state2) => state2.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 = React34.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 store4 = floatingRootContextProp ?? internalStoreRef.current;
    popupStore.useSyncedValue("floatingId", floatingId);
    useIsoLayoutEffect(() => {
      const valuesToSync = {
        open,
        floatingId,
        referenceElement,
        floatingElement
      };
      if (isElement(referenceElement)) {
        valuesToSync.domReferenceElement = referenceElement;
      }
      if (store4.state.positionReference === store4.state.referenceElement) {
        valuesToSync.positionReference = referenceElement;
      }
      store4.update(valuesToSync);
    }, [open, floatingId, referenceElement, floatingElement, store4]);
    store4.context.onOpenChange = handleOpenChange;
    store4.context.nested = nested;
    return store4;
  }

  // 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 = React35.useRef(null);
    if (externalStore === void 0 && internalStoreRef.current === null) {
      internalStoreRef.current = createStore2(floatingId, nested);
    }
    const store4 = externalStore ?? internalStoreRef.current;
    useSyncedFloatingRootContext({
      popupStore: store4,
      treatPopupAsFloatingElement,
      floatingRootContext: store4.state.floatingRootContext,
      floatingId,
      nested,
      onOpenChange: store4.setOpen
    });
    return {
      store: store4,
      internalStore: internalStoreRef.current
    };
  }
  function useTriggerRegistration(id, store4) {
    const registeredElementIdRef = React35.useRef(null);
    const registeredElementRef = React35.useRef(null);
    return React35.useCallback((element) => {
      if (id === void 0) {
        return;
      }
      let shouldSyncTriggerCount = false;
      if (registeredElementIdRef.current !== null) {
        const registeredId = registeredElementIdRef.current;
        const registeredElement = registeredElementRef.current;
        const currentElement = store4.context.triggerElements.getById(registeredId);
        if (registeredElement && currentElement === registeredElement) {
          store4.context.triggerElements.delete(registeredId);
          shouldSyncTriggerCount = true;
        }
        registeredElementIdRef.current = null;
        registeredElementRef.current = null;
      }
      if (element !== null) {
        registeredElementIdRef.current = id;
        registeredElementRef.current = element;
        store4.context.triggerElements.add(id, element);
        shouldSyncTriggerCount = true;
      }
      if (shouldSyncTriggerCount) {
        const triggerCount = store4.context.triggerElements.size;
        if (store4.select("open") && store4.state.triggerCount !== triggerCount) {
          store4.set("triggerCount", triggerCount);
        }
      }
    }, [store4, id]);
  }
  function setPopupOpenState(state2, open, trigger, preventUnmountOnClose = false) {
    if (open) {
      state2.preventUnmountingOnClose = false;
    } else if (preventUnmountOnClose) {
      state2.preventUnmountingOnClose = true;
    }
    const triggerId = trigger?.id ?? null;
    if (triggerId || open) {
      state2.activeTriggerId = triggerId;
      state2.activeTriggerElement = trigger ?? null;
    }
  }
  function attachPreventUnmountOnClose(eventDetails) {
    let preventUnmountOnClose = false;
    eventDetails.preventUnmountOnClose = () => {
      preventUnmountOnClose = true;
    };
    return () => preventUnmountOnClose;
  }
  function applyPopupOpenChange(store4, 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);
    store4.context.onOpenChange?.(nextOpen, eventDetails);
    if (eventDetails.isCanceled) {
      return;
    }
    options.onBeforeDispatch?.();
    store4.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());
      store4.update(updatedState);
    };
    if (isHover) {
      ReactDOM4.flushSync(changeState);
    } else {
      changeState();
    }
  }
  function useInitialOpenSync(store4, openProp, defaultOpen, defaultTriggerId) {
    useOnFirstRender(() => {
      if (openProp === void 0 && store4.state.open === false && defaultOpen) {
        store4.state = {
          ...store4.state,
          open: true,
          activeTriggerId: defaultTriggerId,
          preventUnmountingOnClose: false
        };
      }
    });
  }
  function useTriggerDataForwarding(triggerId, triggerElementRef, store4, stateUpdates) {
    const isMountedByThisTrigger = store4.useState("isMountedByTrigger", triggerId);
    const baseRegisterTrigger = useTriggerRegistration(triggerId, store4);
    const registerTrigger = useStableCallback((element) => {
      baseRegisterTrigger(element);
      if (!element) {
        return;
      }
      const open = store4.select("open");
      const activeTriggerId = store4.select("activeTriggerId");
      if (activeTriggerId === triggerId) {
        store4.update({
          activeTriggerElement: element,
          ...open ? stateUpdates : null
        });
        return;
      }
      if (activeTriggerId == null && open) {
        store4.update({
          activeTriggerId: triggerId,
          activeTriggerElement: element,
          ...stateUpdates
        });
      }
    });
    useIsoLayoutEffect(() => {
      if (isMountedByThisTrigger) {
        store4.update({
          activeTriggerElement: triggerElementRef.current,
          ...stateUpdates
        });
      }
    }, [isMountedByThisTrigger, store4, triggerElementRef, ...Object.values(stateUpdates)]);
    return {
      registerTrigger,
      isMountedByThisTrigger
    };
  }
  function useImplicitActiveTrigger(store4, options = {}) {
    const {
      closeOnActiveTriggerUnmount = false
    } = options;
    const open = store4.useState("open");
    const reactiveTriggerCount = store4.useState("triggerCount");
    useIsoLayoutEffect(() => {
      if (!open) {
        if (store4.state.triggerCount !== 0) {
          store4.set("triggerCount", 0);
        }
        return;
      }
      const triggerCount = store4.context.triggerElements.size;
      const stateUpdates = {};
      if (store4.state.triggerCount !== triggerCount) {
        stateUpdates.triggerCount = triggerCount;
      }
      const activeTriggerId = store4.select("activeTriggerId");
      let lostActiveTriggerId = null;
      if (activeTriggerId) {
        const activeTriggerElement = store4.context.triggerElements.getById(activeTriggerId);
        if (!activeTriggerElement) {
          lostActiveTriggerId = activeTriggerId;
        } else if (activeTriggerElement !== store4.state.activeTriggerElement) {
          stateUpdates.activeTriggerElement = activeTriggerElement;
        }
      }
      if (!lostActiveTriggerId && !activeTriggerId && triggerCount === 1) {
        const iteratorResult = store4.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) {
        store4.update(stateUpdates);
      }
      if (lostActiveTriggerId) {
        if (closeOnActiveTriggerUnmount) {
          queueMicrotask(() => {
            if (store4.select("open") && store4.select("activeTriggerId") === lostActiveTriggerId && !store4.context.triggerElements.getById(lostActiveTriggerId)) {
              const eventDetails = createChangeEventDetails(reason_parts_exports.none);
              store4.setOpen(false, eventDetails);
              if (!eventDetails.isCanceled) {
                store4.update({
                  activeTriggerId: null,
                  activeTriggerElement: null
                });
              }
            }
          });
        }
      }
    }, [open, store4, reactiveTriggerCount, closeOnActiveTriggerUnmount]);
  }
  function useOpenStateTransitions(open, store4, onUnmount) {
    const {
      mounted,
      setMounted,
      transitionStatus
    } = useTransitionStatus(open);
    const preventUnmountingOnClose = store4.useState("preventUnmountingOnClose");
    const syncedPreventUnmountingOnClose = open ? false : preventUnmountingOnClose;
    store4.useSyncedValues({
      mounted,
      transitionStatus,
      preventUnmountingOnClose: syncedPreventUnmountingOnClose
    });
    const forceUnmount = useStableCallback(() => {
      setMounted(false);
      store4.update({
        activeTriggerId: null,
        activeTriggerElement: null,
        mounted: false,
        preventUnmountingOnClose: false
      });
      onUnmount?.();
      store4.context.onOpenChangeComplete?.(false);
    });
    useOpenChangeComplete({
      enabled: mounted && !open && !syncedPreventUnmountingOnClose,
      open,
      ref: store4.context.popupRef,
      onComplete() {
        if (!open) {
          forceUnmount();
        }
      }
    });
    return {
      forceUnmount,
      transitionStatus
    };
  }
  function usePopupInteractionProps(store4, statePart) {
    store4.useSyncedValues(statePart);
    useIsoLayoutEffect(() => () => {
      store4.update({
        activeTriggerProps: EMPTY_OBJECT3,
        inactiveTriggerProps: EMPTY_OBJECT3,
        popupProps: EMPTY_OBJECT3
      });
    }, [store4]);
  }

  // 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_OBJECT3,
      inactiveTriggerProps: EMPTY_OBJECT3,
      popupProps: EMPTY_OBJECT3
    };
  }
  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 = createSelector3((state2) => state2.triggerIdProp ?? state2.activeTriggerId);
  var openSelector = createSelector3((state2) => state2.openProp ?? state2.open);
  var popupIdSelector = createSelector3((state2) => {
    const popupId = state2.popupElement?.id ?? state2.floatingId;
    return popupId || void 0;
  });
  function triggerOwnsOpenPopup(state2, triggerId) {
    return triggerId !== void 0 && openSelector(state2) && activeTriggerIdSelector(state2) === triggerId;
  }
  function triggerOwnsOpenPopupOrIsOnlyTrigger(state2, triggerId) {
    if (triggerOwnsOpenPopup(state2, triggerId)) {
      return true;
    }
    return triggerId !== void 0 && openSelector(state2) && activeTriggerIdSelector(state2) == null && state2.triggerCount === 1;
  }
  var popupStoreSelectors = {
    open: openSelector,
    mounted: createSelector3((state2) => state2.mounted),
    transitionStatus: createSelector3((state2) => state2.transitionStatus),
    floatingRootContext: createSelector3((state2) => state2.floatingRootContext),
    triggerCount: createSelector3((state2) => state2.triggerCount),
    preventUnmountingOnClose: createSelector3((state2) => state2.preventUnmountingOnClose),
    payload: createSelector3((state2) => state2.payload),
    activeTriggerId: activeTriggerIdSelector,
    activeTriggerElement: createSelector3((state2) => state2.mounted ? state2.activeTriggerElement : null),
    popupId: popupIdSelector,
    /**
     * Whether the trigger with the given ID was used to open the popup.
     */
    isTriggerActive: createSelector3((state2, triggerId) => triggerId !== void 0 && activeTriggerIdSelector(state2) === triggerId),
    /**
     * Whether the popup is open and was activated by a trigger with the given ID.
     */
    isOpenedByTrigger: createSelector3((state2, triggerId) => triggerOwnsOpenPopup(state2, triggerId)),
    /**
     * Whether the popup is mounted and was activated by a trigger with the given ID.
     */
    isMountedByTrigger: createSelector3((state2, triggerId) => triggerId !== void 0 && activeTriggerIdSelector(state2) === triggerId && state2.mounted),
    triggerProps: createSelector3((state2, isActive) => isActive ? state2.activeTriggerProps : state2.inactiveTriggerProps),
    /**
     * Popup id for the trigger that currently owns the open popup.
     */
    triggerPopupId: createSelector3((state2, triggerId) => triggerOwnsOpenPopupOrIsOnlyTrigger(state2, triggerId) ? popupIdSelector(state2) : void 0),
    popupProps: createSelector3((state2) => state2.popupProps),
    popupElement: createSelector3((state2) => state2.popupElement),
    positionerElement: createSelector3((state2) => state2.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 store4 = 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;
      }
      store4.update(valuesToSync);
    }, [open, floatingId, elements2.reference, elements2.floating, store4]);
    store4.context.onOpenChange = onOpenChange;
    store4.context.nested = nested;
    return store4;
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useFloating.mjs
  function useFloating2(options = {}) {
    const {
      nodeId,
      externalTree
    } = options;
    const internalStore = useFloatingRootContext(options);
    const store4 = options.rootContext || internalStore;
    const referenceElement = store4.useState("referenceElement");
    const floatingElement = store4.useState("floatingElement");
    const domReferenceElement = store4.useState("domReferenceElement");
    const open = store4.useState("open");
    const floatingId = store4.useState("floatingId");
    const [positionReference, setPositionReferenceRaw] = React36.useState(null);
    const [localDomReference, setLocalDomReference] = React36.useState(void 0);
    const [localFloatingElement, setLocalFloatingElement] = React36.useState(void 0);
    const domReferenceRef = React36.useRef(null);
    const tree = useFloatingTree(externalTree);
    const storeElements = React36.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 ? store4.state.floatingElement : localFloatingElement;
    store4.useSyncedValue("referenceElement", localDomReference ?? null);
    store4.useSyncedValue("domReferenceElement", localDomReference === void 0 ? domReferenceElement : localDomReferenceElement);
    store4.useSyncedValue("floatingElement", syncedFloatingElement);
    const setPositionReference = React36.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 = React36.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 = React36.useCallback((node) => {
      setLocalFloatingElement(node);
      position.refs.setFloating(node);
    }, [position.refs]);
    const refs = React36.useMemo(() => ({
      ...position.refs,
      setReference,
      setFloating,
      setPositionReference,
      domReference: domReferenceRef
    }), [position.refs, setReference, setFloating, setPositionReference]);
    const elements2 = React36.useMemo(() => ({
      ...position.elements,
      domReference: domReferenceElement
    }), [position.elements, domReferenceElement]);
    const context = React36.useMemo(() => ({
      ...position,
      dataRef: store4.context.dataRef,
      open,
      onOpenChange: store4.setOpen,
      events: store4.context.events,
      floatingId,
      refs,
      elements: elements2,
      nodeId,
      rootStore: store4
    }), [position, refs, elements2, nodeId, store4, open, floatingId]);
    useIsoLayoutEffect(() => {
      if (domReferenceElement) {
        domReferenceRef.current = domReferenceElement;
      }
    }, [domReferenceElement]);
    useIsoLayoutEffect(() => {
      store4.context.dataRef.current.floatingContext = context;
      const node = tree?.nodesRef.current.find((n3) => n3.id === nodeId);
      if (node) {
        node.context = context;
      }
    });
    return React36.useMemo(() => ({
      ...position,
      context,
      refs,
      elements: elements2,
      rootStore: store4
    }), [position, refs, elements2, context, store4]);
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useFocus.mjs
  var React37 = __toESM(require_react(), 1);
  var isMacSafari = parts_exports.os.mac && parts_exports.engine.webkit;
  function useFocus(context, props = {}) {
    const {
      enabled = true,
      delay
    } = props;
    const store4 = "rootStore" in context ? context.rootStore : context;
    const {
      events,
      dataRef
    } = store4.context;
    const blockFocusRef = React37.useRef(false);
    const blockedReferenceRef = React37.useRef(null);
    const keyboardModalityRef = React37.useRef(true);
    const timeout = useTimeout();
    React37.useEffect(() => {
      const domReference = store4.select("domReferenceElement");
      if (!enabled) {
        return void 0;
      }
      const win = getWindow(domReference);
      function onBlur() {
        const currentDomReference = store4.select("domReferenceElement");
        if (!store4.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));
    }, [store4, enabled]);
    React37.useEffect(() => {
      if (!enabled) {
        return void 0;
      }
      function onOpenChangeLocal(details) {
        if (details.reason === reason_parts_exports.triggerPress || details.reason === reason_parts_exports.escapeKey) {
          const referenceElement = store4.select("domReferenceElement");
          if (isElement(referenceElement)) {
            blockedReferenceRef.current = referenceElement;
            blockFocusRef.current = true;
          }
        }
      }
      events.on("openchange", onOpenChangeLocal);
      return () => {
        events.off("openchange", onOpenChangeLocal);
      };
    }, [events, enabled, store4]);
    const reference = React37.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, store4.context.triggerElements);
          const {
            nativeEvent,
            currentTarget
          } = event;
          const delayValue = typeof delay === "function" ? delay() : delay;
          if (store4.select("open") && movedFromOtherEnabledTrigger || delayValue === 0 || delayValue === void 0) {
            store4.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerFocus, nativeEvent, currentTarget));
            return;
          }
          timeout.start(delayValue, () => {
            if (blockFocusRef.current) {
              return;
            }
            store4.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 = store4.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, store4.context.triggerElements)) {
              return;
            }
            store4.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerFocus, nativeEvent));
          });
        }
      };
    }, [dataRef, delay, store4, timeout]);
    return React37.useMemo(() => enabled ? {
      reference,
      trigger: reference
    } : {}, [enabled, reference]);
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useHoverFloatingInteraction.mjs
  var React38 = __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(store4) {
    const data = store4.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 store4 = "rootStore" in context ? context.rootStore : context;
    const open = store4.useState("open");
    const floatingElement = store4.useState("floatingElement");
    const domReferenceElement = store4.useState("domReferenceElement");
    const {
      dataRef
    } = store4.context;
    const tree = useFloatingTree();
    const parentId = useFloatingParentNodeId();
    const instance = useHoverInteractionSharedState(store4);
    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]);
    React38.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]);
    React38.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 = () => {
          store4.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, store4.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);
          store4.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, store4, dataRef, closeDelayProp, nodeIdProp, isHoverOpen, isClickLikeOpenEvent2, clearPointerEvents, instance, tree, parentId, childClosedTimeout]);
  }

  // node_modules/@base-ui/react/floating-ui-react/hooks/useHoverReferenceInteraction.mjs
  var React39 = __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 store4 = "rootStore" in context ? context.rootStore : context;
    const {
      dataRef,
      events
    } = store4.context;
    const tree = useFloatingTree(externalTree);
    const instance = useHoverInteractionSharedState(store4);
    const isHoverCloseActiveRef = React39.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 = store4.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(store4.select("domReferenceElement"));
      doc.removeEventListener("mousemove", instance.handler);
      instance.handler = void 0;
    });
    const clearPointerEvents = useStableCallback(() => {
      clearSafePolygonPointerEventsMutation(instance);
    });
    if (isActiveTrigger) {
      instance.handleCloseOptions = handleCloseRef.current?.__options;
    }
    React39.useEffect(() => cleanupMouseMoveHandler, [cleanupMouseMoveHandler]);
    React39.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]);
    React39.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, () => {
            store4.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
            tree?.events.emit("floating.closed", event);
          });
        } else if (runElseBranch) {
          instance.openChangeTimeout.clear();
          store4.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
          tree?.events.emit("floating.closed", event);
        }
      }
      const trigger = triggerElementRef.current ?? (isActiveTrigger ? store4.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 = store4.select("domReferenceElement");
        let triggerNode = currentTarget;
        if (isElement(eventTarget) && !store4.context.triggerElements.hasElement(eventTarget)) {
          for (const triggerElement of store4.context.triggerElements.elements()) {
            if (contains(triggerElement, eventTarget)) {
              triggerNode = triggerElement;
              break;
            }
          }
        }
        if (isElement(currentTarget) && isElement(currentDomReference) && !store4.context.triggerElements.hasElement(currentTarget) && contains(currentTarget, currentDomReference)) {
          triggerNode = currentDomReference;
        }
        const isOverInactive = triggerNode == null ? false : isOverInactiveTrigger(currentDomReference, triggerNode, eventTarget);
        const isOpen2 = store4.select("open");
        const isInClosingTransition = isClosingRef.current?.() ?? store4.select("transitionStatus") === "ending";
        const isHoverCloseTransition = !isOpen2 && isInClosingTransition && isHoverCloseActiveRef.current;
        const isReenteringSameTriggerDuringCloseTransition = !isOverInactive && isElement(triggerNode) && isElement(currentDomReference) && contains(currentDomReference, triggerNode) && isHoverCloseTransition;
        const isRestOnlyDelay = restMsValue > 0 && !openDelay;
        const shouldOpenImmediately = isOverInactive && (isOpen2 || isHoverCloseTransition) || isReenteringSameTriggerDuringCloseTransition;
        const shouldOpen = !isOpen2 || isOverInactive;
        if (shouldOpenImmediately) {
          if (checkShouldOpen()) {
            store4.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerNode));
          }
          return;
        }
        if (isRestOnlyDelay) {
          return;
        }
        if (openDelay) {
          instance.openChangeTimeout.start(openDelay, () => {
            if (shouldOpen && checkShouldOpen()) {
              store4.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerNode));
            }
          });
        } else if (shouldOpen) {
          if (checkShouldOpen()) {
            store4.setOpen(true, createChangeEventDetails(reason_parts_exports.triggerHover, event, triggerNode));
          }
        }
      }
      function onMouseLeave(event) {
        if (isClickLikeOpenEvent2()) {
          clearPointerEvents();
          return;
        }
        cleanupMouseMoveHandler();
        const domReferenceElement = store4.select("domReferenceElement");
        const doc = ownerDocument(domReferenceElement);
        instance.restTimeout.clear();
        instance.restTimeoutPending = false;
        const handleCloseContextBase = dataRef.current.floatingContext ?? getHandleCloseContext?.();
        if (isTargetInsideEnabledTrigger(event.relatedTarget, store4.context.triggerElements)) {
          return;
        }
        if (handleCloseRef.current && handleCloseContextBase) {
          if (!store4.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 === store4.select("domReferenceElement")) {
                closeWithDelay(event, true);
              }
            }
          });
          doc.addEventListener("mousemove", instance.handler);
          instance.handler(event);
          return;
        }
        const shouldClose = instance.pointerType === "touch" ? !contains(store4.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, store4, enabled, handleCloseRef, instance, isActiveTrigger, isOverInactiveTrigger, isClickLikeOpenEvent2, mouseOnly, move, restMsRef, triggerElementRef, tree, enabledRef, getHandleCloseContext, isClosingRef, checkShouldOpen]);
    return React39.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 = store4.select("domReferenceElement");
          const currentOpen = store4.select("open");
          const isOverInactive = isOverInactiveTrigger(currentDomReference, trigger, event.target);
          if (mouseOnly && !isMouseLikePointerType(instance.pointerType)) {
            return;
          }
          if (currentOpen && isOverInactive && instance.handleCloseOptions?.blockPointerEvents) {
            const floatingElement = store4.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 = store4.select("open");
            if (!instance.blockMouseMove && (!latestOpen || isOverInactive) && checkShouldOpen()) {
              store4.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, store4, 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, y22, x3, y3, x4, y4) {
    let isInsideValue = false;
    if (hasIntersectingEdge(pointX, pointY, x1, y1, x2, y22)) {
      isInsideValue = !isInsideValue;
    }
    if (hasIntersectingEdge(pointX, pointY, x2, y22, 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, y22) {
    const minX = Math.min(x1, x2);
    const maxX = Math.max(x1, x2);
    const minY = Math.min(y1, y22);
    const maxY = Math.max(y1, y22);
    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: y3,
      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 || y3 == 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 = y3 > 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" && y3 >= refRect.bottom - 1 || side === "bottom" && y3 <= 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 = y3 + 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 = y3 - 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 ? y3 + cursorYOffset : cursorLeaveFromBottom ? y3 + cursorYOffset : y3 - cursorYOffset;
            const cursorPointTwoY = isFloatingTaller ? y3 - cursorYOffset : cursorLeaveFromBottom ? y3 + cursorYOffset : y3 - 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 ? y3 + cursorYOffset : cursorLeaveFromBottom ? y3 + cursorYOffset : y3 - cursorYOffset;
            const cursorPointTwoY = isFloatingTaller ? y3 - cursorYOffset : cursorLeaveFromBottom ? y3 + cursorYOffset : y3 - 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/react/internals/composite/composite.mjs
  var ARROW_UP = "ArrowUp";
  var ARROW_DOWN = "ArrowDown";
  var ARROW_LEFT = "ArrowLeft";
  var ARROW_RIGHT = "ArrowRight";
  var HOME = "Home";
  var END = "End";
  var HORIZONTAL_KEYS = /* @__PURE__ */ new Set([ARROW_LEFT, ARROW_RIGHT]);
  var HORIZONTAL_KEYS_WITH_EXTRA_KEYS = /* @__PURE__ */ new Set([ARROW_LEFT, ARROW_RIGHT, HOME, END]);
  var VERTICAL_KEYS = /* @__PURE__ */ new Set([ARROW_UP, ARROW_DOWN]);
  var VERTICAL_KEYS_WITH_EXTRA_KEYS = /* @__PURE__ */ new Set([ARROW_UP, ARROW_DOWN, HOME, END]);
  var ARROW_KEYS = /* @__PURE__ */ new Set([...HORIZONTAL_KEYS, ...VERTICAL_KEYS]);
  var COMPOSITE_KEYS = /* @__PURE__ */ new Set([...ARROW_KEYS, HOME, END]);
  var SHIFT = "Shift";
  var CONTROL = "Control";
  var ALT = "Alt";
  var META = "Meta";
  var MODIFIER_KEYS = /* @__PURE__ */ new Set([SHIFT, CONTROL, ALT, META]);
  function isInputElement(element) {
    return isHTMLElement(element) && element.tagName === "INPUT";
  }
  function isNativeInput(element) {
    if (isInputElement(element) && element.selectionStart != null) {
      return true;
    }
    if (isHTMLElement(element) && element.tagName === "TEXTAREA") {
      return true;
    }
    return false;
  }
  function scrollIntoViewIfNeeded(scrollContainer, element, direction, orientation) {
    if (!scrollContainer || !element || !element.scrollTo) {
      return;
    }
    let targetX = scrollContainer.scrollLeft;
    let targetY = scrollContainer.scrollTop;
    const isOverflowingX = scrollContainer.clientWidth < scrollContainer.scrollWidth;
    const isOverflowingY = scrollContainer.clientHeight < scrollContainer.scrollHeight;
    if (isOverflowingX && orientation !== "vertical") {
      const elementOffsetLeft = getOffset(scrollContainer, element, "left");
      const containerStyles = getStyles(scrollContainer);
      const elementStyles = getStyles(element);
      if (direction === "ltr") {
        if (elementOffsetLeft + element.offsetWidth + elementStyles.scrollMarginRight > scrollContainer.scrollLeft + scrollContainer.clientWidth - containerStyles.scrollPaddingRight) {
          targetX = elementOffsetLeft + element.offsetWidth + elementStyles.scrollMarginRight - scrollContainer.clientWidth + containerStyles.scrollPaddingRight;
        } else if (elementOffsetLeft - elementStyles.scrollMarginLeft < scrollContainer.scrollLeft + containerStyles.scrollPaddingLeft) {
          targetX = elementOffsetLeft - elementStyles.scrollMarginLeft - containerStyles.scrollPaddingLeft;
        }
      }
      if (direction === "rtl") {
        if (elementOffsetLeft - elementStyles.scrollMarginRight < scrollContainer.scrollLeft + containerStyles.scrollPaddingLeft) {
          targetX = elementOffsetLeft - elementStyles.scrollMarginLeft - containerStyles.scrollPaddingLeft;
        } else if (elementOffsetLeft + element.offsetWidth + elementStyles.scrollMarginRight > scrollContainer.scrollLeft + scrollContainer.clientWidth - containerStyles.scrollPaddingRight) {
          targetX = elementOffsetLeft + element.offsetWidth + elementStyles.scrollMarginRight - scrollContainer.clientWidth + containerStyles.scrollPaddingRight;
        }
      }
    }
    if (isOverflowingY && orientation !== "horizontal") {
      const elementOffsetTop = getOffset(scrollContainer, element, "top");
      const containerStyles = getStyles(scrollContainer);
      const elementStyles = getStyles(element);
      if (elementOffsetTop - elementStyles.scrollMarginTop < scrollContainer.scrollTop + containerStyles.scrollPaddingTop) {
        targetY = elementOffsetTop - elementStyles.scrollMarginTop - containerStyles.scrollPaddingTop;
      } else if (elementOffsetTop + element.offsetHeight + elementStyles.scrollMarginBottom > scrollContainer.scrollTop + scrollContainer.clientHeight - containerStyles.scrollPaddingBottom) {
        targetY = elementOffsetTop + element.offsetHeight + elementStyles.scrollMarginBottom - scrollContainer.clientHeight + containerStyles.scrollPaddingBottom;
      }
    }
    scrollContainer.scrollTo({
      left: targetX,
      top: targetY,
      behavior: "auto"
    });
  }
  function getOffset(ancestor, element, side) {
    const propName = side === "left" ? "offsetLeft" : "offsetTop";
    let result = 0;
    while (element.offsetParent) {
      result += element[propName];
      if (element.offsetParent === ancestor) {
        break;
      }
      element = element.offsetParent;
    }
    return result;
  }
  function getStyles(element) {
    const styles = getComputedStyle(element);
    return {
      scrollMarginTop: parseFloat(styles.scrollMarginTop) || 0,
      scrollMarginRight: parseFloat(styles.scrollMarginRight) || 0,
      scrollMarginBottom: parseFloat(styles.scrollMarginBottom) || 0,
      scrollMarginLeft: parseFloat(styles.scrollMarginLeft) || 0,
      scrollPaddingTop: parseFloat(styles.scrollPaddingTop) || 0,
      scrollPaddingRight: parseFloat(styles.scrollPaddingRight) || 0,
      scrollPaddingBottom: parseFloat(styles.scrollPaddingBottom) || 0,
      scrollPaddingLeft: parseFloat(styles.scrollPaddingLeft) || 0
    };
  }

  // 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 React40 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/floating-ui-react/middleware/arrow.mjs
  var baseArrow = (options) => ({
    name: "arrow",
    options,
    async fn(state2) {
      const {
        x: x2,
        y: y3,
        placement,
        rects,
        platform: platform3,
        elements: elements2,
        middlewareData
      } = state2;
      const {
        element,
        padding = 0,
        offsetParent = "real"
      } = evaluate(options, state2) || {};
      if (element == null) {
        return {};
      }
      const paddingObject = getPaddingObject(padding);
      const coords = {
        x: x2,
        y: y3
      };
      const axis = getAlignmentAxis(placement);
      const length2 = 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[length2] + rects.reference[axis] - coords[axis] - rects.floating[length2];
      const startDiff = coords[axis] - rects.reference[axis];
      const arrowOffsetParent = offsetParent === "real" ? await platform3.getOffsetParent?.(element) : elements2.floating;
      let clientSize = elements2.floating[clientProp] || rects.floating[length2];
      if (!clientSize || !await platform3.isElement?.(arrowOffsetParent)) {
        clientSize = elements2.floating[clientProp] || rects.floating[length2];
      }
      const centerToReference = endDiff / 2 - startDiff / 2;
      const largestPossiblePadding = clientSize / 2 - arrowDimensions[length2] / 2 - 1;
      const minPadding = Math.min(paddingObject[minProp], largestPossiblePadding);
      const maxPadding = Math.min(paddingObject[maxProp], largestPossiblePadding);
      const min3 = minPadding;
      const max3 = clientSize - arrowDimensions[length2] - maxPadding;
      const center = clientSize / 2 - arrowDimensions[length2] / 2 + centerToReference;
      const offset4 = clamp(min3, center, max3);
      const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset4 && rects.reference[length2] / 2 - (center < min3 ? minPadding : maxPadding) - arrowDimensions[length2] / 2 < 0;
      const alignmentOffset = shouldAddOffset ? center < min3 ? center - min3 : center - max3 : 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(state2) {
      const {
        width,
        height,
        x: x2,
        y: y3
      } = state2.rects.reference;
      const anchorHidden = width === 0 && height === 0 && x2 === 0 && y3 === 0;
      const nativeHideResult = await nativeHideFn(state2);
      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(state2) {
      const {
        x: rawX,
        y: rawY,
        rects: {
          floating: floatRect
        },
        elements: {
          floating
        },
        platform: platform3,
        strategy,
        placement
      } = state2;
      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 y3 = rawY;
      if (currentSide === "left") {
        x2 = offsetDimensions.width - (rawX + floatRect.width);
      }
      if (currentSide === "top") {
        y3 = 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: y3,
        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(state2, sideParam, isRtl) {
    const {
      rects,
      placement
    } = state2;
    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] = React40.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 = React40.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((state2) => {
      const data = getOffsetData(state2, 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: y4,
          width,
          height
        } = rects.reference;
        const anchorWidth = (Math.round((x3 + width) * dpr) - Math.round(x3 * dpr)) / dpr;
        const anchorHeight = (Math.round((y4 + height) * dpr) - Math.round(y4 * dpr)) / dpr;
        floatingStyle.setProperty("--anchor-width", `${anchorWidth}px`);
        floatingStyle.setProperty("--anchor-height", `${anchorHeight}px`);
      }
    }), arrow4((state2) => ({
      // `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(state2.elements.floating).createElement("div"),
      padding: arrowPadding,
      offsetParent: "floating"
    }), [arrowPadding]), {
      name: "transformOrigin",
      fn(state2) {
        const {
          elements: elements3,
          middlewareData: middlewareData2,
          placement: renderedPlacement2,
          rects,
          y: y4
        } = state2;
        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(state2, 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 - y4}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 = React40.useMemo(() => ({
      elementResize: !disableAnchorTracking && typeof ResizeObserver !== "undefined",
      layoutShift: !disableAnchorTracking && typeof IntersectionObserver !== "undefined"
    }), [disableAnchorTracking]);
    const {
      refs,
      elements: elements2,
      x: x2,
      y: y3,
      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 = React40.useMemo(() => {
      const base = adaptiveOrigin2 ? {
        position: resolvedPosition,
        [sideX]: x2,
        [sideY]: y3
      } : {
        position: resolvedPosition,
        ...originalFloatingStyles
      };
      if (!isPositioned) {
        base.opacity = 0;
      }
      return base;
    }, [adaptiveOrigin2, resolvedPosition, sideX, x2, sideY, y3, originalFloatingStyles, isPositioned]);
    const registeredPositionReferenceRef = React40.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]);
    React40.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]);
    React40.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 = React40.useMemo(() => ({
      position: "absolute",
      top: middlewareData.arrow?.y,
      left: middlewareData.arrow?.x
    }), [middlewareData.arrow]);
    const arrowUncentered = middlewareData.arrow?.centerOffset !== 0;
    return React40.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_OBJECT3;
  }

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

  // node_modules/@base-ui/react/button/Button.mjs
  var React41 = __toESM(require_react(), 1);
  var Button2 = /* @__PURE__ */ React41.forwardRef(function Button3(componentProps, forwardedRef) {
    const {
      render: render5,
      className,
      disabled: disabled2 = false,
      focusableWhenDisabled = false,
      nativeButton = true,
      style,
      ...elementProps
    } = componentProps;
    const {
      getButtonProps,
      buttonRef
    } = useButton({
      disabled: disabled2,
      focusableWhenDisabled,
      native: nativeButton
    });
    const state2 = {
      disabled: disabled2
    };
    return useRenderElement("button", componentProps, {
      state: state2,
      ref: [forwardedRef, buttonRef],
      props: [elementProps, getButtonProps]
    });
  });
  if (true) Button2.displayName = "Button";

  // 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 React42 = __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_runtime102 = __toESM(require_jsx_runtime(), 1);
  var CollapsibleRoot = /* @__PURE__ */ React42.forwardRef(function CollapsibleRoot2(componentProps, forwardedRef) {
    const {
      render: render5,
      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 state2 = React42.useMemo(() => ({
      open: collapsible.open,
      disabled: collapsible.disabled,
      transitionStatus: collapsible.transitionStatus
    }), [collapsible.open, collapsible.disabled, collapsible.transitionStatus]);
    const contextValue = React42.useMemo(() => ({
      ...collapsible,
      onOpenChange,
      state: state2
    }), [collapsible, onOpenChange, state2]);
    const element = useRenderElement("div", componentProps, {
      state: state2,
      ref: forwardedRef,
      props: elementProps,
      stateAttributesMapping: collapsibleStateAttributesMapping
    });
    return /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(CollapsibleRootContext.Provider, {
      value: contextValue,
      children: element
    });
  });
  if (true) CollapsibleRoot.displayName = "CollapsibleRoot";

  // node_modules/@base-ui/react/collapsible/trigger/CollapsibleTrigger.mjs
  var React43 = __toESM(require_react(), 1);
  var stateAttributesMapping = {
    ...triggerOpenStateMapping,
    ...transitionStatusMapping
  };
  var CollapsibleTrigger = /* @__PURE__ */ React43.forwardRef(function CollapsibleTrigger2(componentProps, forwardedRef) {
    const {
      panelId,
      open,
      handleTrigger,
      state: state2,
      disabled: contextDisabled
    } = useCollapsibleRootContext();
    const {
      className,
      disabled: disabled2 = contextDisabled,
      render: render5,
      nativeButton = true,
      style,
      ...elementProps
    } = componentProps;
    const {
      getButtonProps,
      buttonRef
    } = useButton({
      disabled: disabled2,
      focusableWhenDisabled: true,
      native: nativeButton
    });
    const element = useRenderElement("button", componentProps, {
      state: state2,
      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 React44 = __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__ */ React44.forwardRef(function CollapsiblePanel2(componentProps, forwardedRef) {
    const {
      className,
      hiddenUntilFound: hiddenUntilFoundProp,
      keepMounted: keepMountedProp,
      render: render5,
      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: state2,
      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 = {
      ...state2,
      transitionStatus: panelTransitionStatus
    };
    const resolvedStyle = resolveStyle2(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/internals/composite/item/useCompositeItem.mjs
  var React45 = __toESM(require_react(), 1);
  function useCompositeItem(params = {}) {
    const {
      highlightItemOnHover,
      highlightedIndex,
      onHighlightedIndexChange
    } = useCompositeRootContext();
    const {
      ref,
      index: index2
    } = useCompositeListItem(params);
    const isHighlighted = highlightedIndex === index2;
    const itemRef = React45.useRef(null);
    const mergedRef = useMergedRefs(ref, itemRef);
    const compositeProps = {
      tabIndex: isHighlighted ? 0 : -1,
      onFocus() {
        onHighlightedIndexChange(index2);
      },
      onMouseMove() {
        const item = itemRef.current;
        if (!highlightItemOnHover || !item) {
          return;
        }
        const disabled2 = item.hasAttribute("disabled") || item.ariaDisabled === "true";
        if (!isHighlighted && !disabled2) {
          item.focus();
        }
      }
    };
    return {
      compositeProps,
      compositeRef: mergedRef,
      index: index2
    };
  }

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

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

  // node_modules/@base-ui/react/utils/usePopupAutoResize.mjs
  var React47 = __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 = React47.useRef(null);
    const isInitialRenderRef = React47.useRef(true);
    const restoreAnchoringStylesRef = React47.useRef(NOOP);
    const onMeasureLayout = useStableCallback(onMeasureLayoutParam);
    const onMeasureLayoutComplete = useStableCallback(onMeasureLayoutCompleteParam);
    const anchoringStyles = React47.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_OBJECT3;
    }, [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_runtime103 = __toESM(require_jsx_runtime(), 1);
  function usePopupViewport(parameters) {
    const {
      store: store4,
      side,
      cssVars,
      children
    } = parameters;
    const direction = useDirection();
    const activeTrigger = store4.useState("activeTriggerElement");
    const activeTriggerId = store4.useState("activeTriggerId");
    const open = store4.useState("open");
    const payload = store4.useState("payload");
    const mounted = store4.useState("mounted");
    const popupElement = store4.useState("popupElement");
    const positionerElement = store4.useState("positionerElement");
    const previousActiveTrigger = usePreviousValue(open ? activeTrigger : null);
    const currentContentKey = usePopupContentKey(activeTriggerId, payload);
    const capturedNodeRef = React48.useRef(null);
    const [previousContentNode, setPreviousContentNode] = React48.useState(null);
    const [newTriggerOffset, setNewTriggerOffset] = React48.useState(null);
    const currentContainerRef = React48.useRef(null);
    const previousContainerRef = React48.useRef(null);
    const onAnimationsFinished = useAnimationsFinished(currentContainerRef, true, false);
    const cleanupFrame = useAnimationFrame();
    const [previousContentDimensions, setPreviousContentDimensions] = React48.useState(null);
    const [showStartingStyleAttribute, setShowStartingStyleAttribute] = React48.useState(false);
    useIsoLayoutEffect(() => {
      store4.set("hasViewport", true);
      return () => {
        store4.set("hasViewport", false);
      };
    }, [store4]);
    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 = React48.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_runtime103.jsx)("div", {
        "data-current": true,
        ref: currentContainerRef,
        children
      }, currentContentKey);
    } else {
      childrenToRender = /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)(React48.Fragment, {
        children: [/* @__PURE__ */ (0, import_jsx_runtime103.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_runtime103.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 state2 = {
      activationDirection: getActivationDirection(newTriggerOffset),
      transitioning: isTransitioning
    };
    return {
      children: childrenToRender,
      state: state2
    };
  }
  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] = React48.useState(0);
    const previousActiveTriggerIdRef = React48.useRef(activeTriggerId);
    const previousPayloadRef = React48.useRef(payload);
    const pendingPayloadUpdateRef = React48.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/utils/isElementDisabled.mjs
  function isElementDisabled(element) {
    return element == null || element.hasAttribute("disabled") || element.getAttribute("aria-disabled") === "true";
  }

  // node_modules/@base-ui/react/internals/csp-context/CSPContext.mjs
  var React49 = __toESM(require_react(), 1);
  var CSPContext = /* @__PURE__ */ React49.createContext(void 0);
  if (true) CSPContext.displayName = "CSPContext";
  var DEFAULT_CSP_CONTEXT_VALUE = {
    disableStyleElements: false
  };
  function useCSPContext() {
    return React49.useContext(CSPContext) ?? DEFAULT_CSP_CONTEXT_VALUE;
  }

  // node_modules/@base-ui/react/internals/composite/root/CompositeRoot.mjs
  var React51 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/internals/composite/root/useCompositeRoot.mjs
  var React50 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/internals/composite/constants.mjs
  var ACTIVE_COMPOSITE_ITEM = "data-composite-item-active";

  // node_modules/@base-ui/react/internals/composite/root/useCompositeRoot.mjs
  var EMPTY_ARRAY4 = [];
  function useCompositeRoot(params) {
    const {
      loopFocus = true,
      orientation = "both",
      grid,
      onLoop,
      direction,
      highlightedIndex: externalHighlightedIndex,
      onHighlightedIndexChange: externalSetHighlightedIndex,
      rootRef: externalRef,
      enableHomeAndEndKeys = false,
      stopEventPropagation = false,
      disabledIndices,
      modifierKeys = EMPTY_ARRAY4
    } = params;
    const [internalHighlightedIndex, internalSetHighlightedIndex] = React50.useState(0);
    const isGrid2 = grid != null;
    const rootRef = React50.useRef(null);
    const mergedRef = useMergedRefs(rootRef, externalRef);
    const elementsRef = React50.useRef([]);
    const hasSetDefaultIndexRef = React50.useRef(false);
    const highlightedIndex = externalHighlightedIndex ?? internalHighlightedIndex;
    const onHighlightedIndexChange = useStableCallback((index2, shouldScrollIntoView = false) => {
      (externalSetHighlightedIndex ?? internalSetHighlightedIndex)(index2);
      if (shouldScrollIntoView) {
        const newActiveItem = elementsRef.current[index2];
        scrollIntoViewIfNeeded(rootRef.current, newActiveItem, direction, orientation);
      }
    });
    const onMapChange = useStableCallback((map) => {
      if (map.size === 0 || hasSetDefaultIndexRef.current) {
        return;
      }
      hasSetDefaultIndexRef.current = true;
      const sortedElements = Array.from(map.keys());
      const activeItem = sortedElements.find((compositeElement) => compositeElement?.hasAttribute(ACTIVE_COMPOSITE_ITEM)) ?? null;
      const activeIndex = activeItem ? sortedElements.indexOf(activeItem) : -1;
      if (activeIndex !== -1) {
        onHighlightedIndexChange(activeIndex);
      } else if (isListIndexDisabled(sortedElements, highlightedIndex, disabledIndices)) {
        const firstEnabledIndex = findNonDisabledListIndex(sortedElements, {
          disabledIndices
        });
        if (!isIndexOutOfListBounds(sortedElements, firstEnabledIndex)) {
          onHighlightedIndexChange(firstEnabledIndex);
        }
      }
      scrollIntoViewIfNeeded(rootRef.current, activeItem, direction, orientation);
    });
    useIsoLayoutEffect(() => {
      if (disabledIndices == null || externalHighlightedIndex != null || !hasSetDefaultIndexRef.current) {
        return;
      }
      const elements2 = elementsRef.current;
      if (isListIndexDisabled(elements2, highlightedIndex, disabledIndices)) {
        const firstEnabledIndex = findNonDisabledListIndex(elements2, {
          disabledIndices
        });
        if (!isIndexOutOfListBounds(elements2, firstEnabledIndex)) {
          onHighlightedIndexChange(firstEnabledIndex);
        }
      }
    }, [disabledIndices, externalHighlightedIndex, highlightedIndex, elementsRef, onHighlightedIndexChange]);
    const wrappedOnLoop = useStableCallback((event, prevIndex, nextIndex) => {
      if (!onLoop) {
        return nextIndex;
      }
      return onLoop(event, prevIndex, nextIndex, elementsRef);
    });
    const onKeyDown = useStableCallback((event) => {
      const RELEVANT_KEYS = enableHomeAndEndKeys ? COMPOSITE_KEYS : ARROW_KEYS;
      if (!RELEVANT_KEYS.has(event.key)) {
        return;
      }
      if (isModifierKeySet(event, modifierKeys)) {
        return;
      }
      const element = rootRef.current;
      if (!element) {
        return;
      }
      const isRtl = direction === "rtl";
      const horizontalForwardKey = isRtl ? ARROW_LEFT : ARROW_RIGHT;
      const forwardKey = {
        horizontal: horizontalForwardKey,
        vertical: ARROW_DOWN,
        both: horizontalForwardKey
      }[orientation];
      const horizontalBackwardKey = isRtl ? ARROW_RIGHT : ARROW_LEFT;
      const backwardKey = {
        horizontal: horizontalBackwardKey,
        vertical: ARROW_UP,
        both: horizontalBackwardKey
      }[orientation];
      const target = getTarget(event.nativeEvent);
      if (target != null && isNativeInput(target) && !isElementDisabled(target)) {
        const selectionStart = target.selectionStart;
        const selectionEnd = target.selectionEnd;
        const textContent = target.value ?? "";
        if (selectionStart == null || event.shiftKey || selectionStart !== selectionEnd) {
          return;
        }
        if (event.key !== backwardKey && selectionStart < textContent.length) {
          return;
        }
        if (event.key !== forwardKey && selectionStart > 0) {
          return;
        }
      }
      let nextIndex = highlightedIndex;
      const minIndex = getMinListIndex(elementsRef, disabledIndices);
      const maxIndex = getMaxListIndex(elementsRef, disabledIndices);
      if (grid != null) {
        nextIndex = grid({
          disabledIndices,
          elementsRef,
          event,
          highlightedIndex,
          loopFocus,
          maxIndex,
          minIndex,
          onLoop: wrappedOnLoop,
          orientation,
          rtl: isRtl
        });
      }
      const forwardKeys = {
        horizontal: [horizontalForwardKey],
        vertical: [ARROW_DOWN],
        both: [horizontalForwardKey, ARROW_DOWN]
      }[orientation];
      const backwardKeys = {
        horizontal: [horizontalBackwardKey],
        vertical: [ARROW_UP],
        both: [horizontalBackwardKey, ARROW_UP]
      }[orientation];
      const preventedKeys = isGrid2 ? RELEVANT_KEYS : {
        horizontal: enableHomeAndEndKeys ? HORIZONTAL_KEYS_WITH_EXTRA_KEYS : HORIZONTAL_KEYS,
        vertical: enableHomeAndEndKeys ? VERTICAL_KEYS_WITH_EXTRA_KEYS : VERTICAL_KEYS,
        both: RELEVANT_KEYS
      }[orientation];
      if (enableHomeAndEndKeys) {
        if (event.key === HOME) {
          nextIndex = minIndex;
        } else if (event.key === END) {
          nextIndex = maxIndex;
        }
      }
      if (nextIndex === highlightedIndex && (forwardKeys.includes(event.key) || backwardKeys.includes(event.key))) {
        if (loopFocus && nextIndex === maxIndex && forwardKeys.includes(event.key)) {
          nextIndex = minIndex;
          if (onLoop) {
            nextIndex = onLoop(event, highlightedIndex, nextIndex, elementsRef);
          }
        } else if (loopFocus && nextIndex === minIndex && backwardKeys.includes(event.key)) {
          nextIndex = maxIndex;
          if (onLoop) {
            nextIndex = onLoop(event, highlightedIndex, nextIndex, elementsRef);
          }
        } else {
          nextIndex = findNonDisabledListIndex(elementsRef.current, {
            startingIndex: nextIndex,
            decrement: backwardKeys.includes(event.key),
            disabledIndices
          });
        }
      }
      if (nextIndex !== highlightedIndex && !isIndexOutOfListBounds(elementsRef.current, nextIndex)) {
        if (stopEventPropagation) {
          event.stopPropagation();
        }
        if (preventedKeys.has(event.key)) {
          event.preventDefault();
        }
        onHighlightedIndexChange(nextIndex, true);
        queueMicrotask(() => {
          elementsRef.current[nextIndex]?.focus();
        });
      }
    });
    const props = {
      ref: mergedRef,
      onFocus(event) {
        const element = rootRef.current;
        const target = getTarget(event.nativeEvent);
        if (!element || target == null || !isNativeInput(target)) {
          return;
        }
        target.setSelectionRange(0, target.value.length ?? 0);
      },
      onKeyDown
    };
    return {
      props,
      highlightedIndex,
      onHighlightedIndexChange,
      elementsRef,
      disabledIndices,
      onMapChange,
      relayKeyboardEvent: onKeyDown
    };
  }
  function isModifierKeySet(event, ignoredModifierKeys) {
    for (const key of MODIFIER_KEYS.values()) {
      if (ignoredModifierKeys.includes(key)) {
        continue;
      }
      if (event.getModifierState(key)) {
        return true;
      }
    }
    return false;
  }

  // node_modules/@base-ui/react/internals/composite/root/CompositeRoot.mjs
  var import_jsx_runtime104 = __toESM(require_jsx_runtime(), 1);
  function CompositeRoot(componentProps) {
    const {
      render: render5,
      className,
      style,
      refs = EMPTY_ARRAY3,
      props = EMPTY_ARRAY3,
      state: state2 = EMPTY_OBJECT3,
      stateAttributesMapping: stateAttributesMapping6,
      highlightedIndex: highlightedIndexProp,
      onHighlightedIndexChange: onHighlightedIndexChangeProp,
      orientation,
      grid,
      loopFocus,
      onLoop,
      enableHomeAndEndKeys,
      onMapChange: onMapChangeProp,
      stopEventPropagation = true,
      rootRef,
      disabledIndices,
      modifierKeys,
      highlightItemOnHover = false,
      tag = "div",
      ...elementProps
    } = componentProps;
    const direction = useDirection();
    const {
      props: defaultProps,
      highlightedIndex,
      onHighlightedIndexChange,
      elementsRef,
      onMapChange: onMapChangeUnwrapped,
      relayKeyboardEvent
    } = useCompositeRoot({
      grid,
      loopFocus,
      onLoop,
      orientation,
      highlightedIndex: highlightedIndexProp,
      onHighlightedIndexChange: onHighlightedIndexChangeProp,
      rootRef,
      stopEventPropagation,
      enableHomeAndEndKeys,
      direction,
      disabledIndices,
      modifierKeys
    });
    const element = useRenderElement(tag, componentProps, {
      state: state2,
      ref: refs,
      props: [defaultProps, ...props, elementProps],
      stateAttributesMapping: stateAttributesMapping6
    });
    const contextValue = React51.useMemo(() => ({
      highlightedIndex,
      onHighlightedIndexChange,
      highlightItemOnHover,
      relayKeyboardEvent
    }), [highlightedIndex, onHighlightedIndexChange, highlightItemOnHover, relayKeyboardEvent]);
    return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(CompositeRootContext.Provider, {
      value: contextValue,
      children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(CompositeList, {
        elementsRef,
        onMapChange: (newMap) => {
          onMapChangeProp?.(newMap);
          onMapChangeUnwrapped(newMap);
        },
        children: element
      })
    });
  }

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

  // node_modules/@base-ui/react/utils/useIsHydrating.mjs
  var import_shim2 = __toESM(require_shim(), 1);
  function subscribe2() {
    return NOOP;
  }
  function getSnapshot() {
    return false;
  }
  function getServerSnapshot() {
    return true;
  }
  function useIsHydrating() {
    return (0, import_shim2.useSyncExternalStore)(subscribe2, getSnapshot, getServerSnapshot);
  }

  // node_modules/@base-ui/react/tabs/index.parts.mjs
  var index_parts_exports2 = {};
  __export(index_parts_exports2, {
    Indicator: () => TabsIndicator,
    List: () => TabsList,
    Panel: () => TabsPanel,
    Root: () => TabsRoot,
    Tab: () => TabsTab
  });

  // node_modules/@base-ui/react/tabs/root/TabsRoot.mjs
  var React54 = __toESM(require_react(), 1);

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

  // node_modules/@base-ui/react/tabs/root/TabsRootDataAttributes.mjs
  var TabsRootDataAttributes = /* @__PURE__ */ (function(TabsRootDataAttributes2) {
    TabsRootDataAttributes2["activationDirection"] = "data-activation-direction";
    TabsRootDataAttributes2["orientation"] = "data-orientation";
    return TabsRootDataAttributes2;
  })({});

  // node_modules/@base-ui/react/tabs/root/stateAttributesMapping.mjs
  var tabsStateAttributesMapping = {
    tabActivationDirection: (dir) => ({
      [TabsRootDataAttributes.activationDirection]: dir
    })
  };

  // node_modules/@base-ui/react/tabs/root/TabsRoot.mjs
  var import_jsx_runtime106 = __toESM(require_jsx_runtime(), 1);
  var TabsRoot = /* @__PURE__ */ React54.forwardRef(function TabsRoot2(componentProps, forwardedRef) {
    const {
      className,
      defaultValue: defaultValueProp = 0,
      onValueChange: onValueChangeProp,
      orientation = "horizontal",
      render: render5,
      value: valueProp,
      style,
      ...elementProps
    } = componentProps;
    const hasExplicitDefaultValueProp = componentProps.defaultValue !== void 0;
    const tabPanelRefs = React54.useRef([]);
    const [mountedTabPanels, setMountedTabPanels] = React54.useState(() => /* @__PURE__ */ new Map());
    const [value, setValue] = useControlled({
      controlled: valueProp,
      default: defaultValueProp,
      name: "Tabs",
      state: "value"
    });
    const isControlled = valueProp !== void 0;
    const [tabMap, setTabMap] = React54.useState(() => /* @__PURE__ */ new Map());
    const lastKnownTabElementRef = React54.useRef(void 0);
    const getTabElementBySelectedValue = React54.useCallback((selectedValue) => {
      if (selectedValue === void 0) {
        return null;
      }
      for (const [tabElement, tabMetadata] of tabMap.entries()) {
        if (tabMetadata != null && selectedValue === (tabMetadata.value ?? tabMetadata.index)) {
          return tabElement;
        }
      }
      return null;
    }, [tabMap]);
    const [activationDirectionState, setActivationDirectionState] = React54.useState(() => ({
      previousValue: value,
      tabActivationDirection: "none"
    }));
    const {
      previousValue,
      tabActivationDirection: committedTabActivationDirection
    } = activationDirectionState;
    let tabActivationDirection = committedTabActivationDirection;
    let directionComputationIncomplete = false;
    if (previousValue !== value) {
      tabActivationDirection = computeActivationDirection(previousValue, value, orientation, tabMap);
      directionComputationIncomplete = previousValue != null && value != null && getTabElementBySelectedValue(value) == null;
    }
    const nextPreviousValue = directionComputationIncomplete ? previousValue : value;
    const shouldSyncActivationDirectionState = previousValue !== nextPreviousValue || committedTabActivationDirection !== tabActivationDirection;
    useIsoLayoutEffect(() => {
      if (!shouldSyncActivationDirectionState) {
        return;
      }
      setActivationDirectionState({
        previousValue: nextPreviousValue,
        tabActivationDirection
      });
    }, [nextPreviousValue, shouldSyncActivationDirectionState, tabActivationDirection]);
    const onValueChange = useStableCallback((newValue, eventDetails) => {
      const activationDirection = computeActivationDirection(value, newValue, orientation, tabMap);
      eventDetails.activationDirection = activationDirection;
      onValueChangeProp?.(newValue, eventDetails);
      if (eventDetails.isCanceled) {
        return;
      }
      setValue(newValue);
    });
    const notifyAutomaticValueChange = useStableCallback((nextValue, reason) => {
      onValueChangeProp?.(nextValue, createChangeEventDetails(reason, void 0, void 0, {
        activationDirection: "none"
      }));
    });
    const registerMountedTabPanel = useStableCallback((panelValue, panelId) => {
      setMountedTabPanels((prev) => {
        if (prev.get(panelValue) === panelId) {
          return prev;
        }
        const next = new Map(prev);
        next.set(panelValue, panelId);
        return next;
      });
    });
    const unregisterMountedTabPanel = useStableCallback((panelValue, panelId) => {
      setMountedTabPanels((prev) => {
        if (!prev.has(panelValue) || prev.get(panelValue) !== panelId) {
          return prev;
        }
        const next = new Map(prev);
        next.delete(panelValue);
        return next;
      });
    });
    const getTabPanelIdByValue = React54.useCallback((tabValue) => {
      return mountedTabPanels.get(tabValue);
    }, [mountedTabPanels]);
    const getTabIdByPanelValue = React54.useCallback((tabPanelValue) => {
      for (const tabMetadata of tabMap.values()) {
        if (tabPanelValue === tabMetadata?.value) {
          return tabMetadata?.id;
        }
      }
      return void 0;
    }, [tabMap]);
    const tabsContextValue = React54.useMemo(() => ({
      getTabElementBySelectedValue,
      getTabIdByPanelValue,
      getTabPanelIdByValue,
      onValueChange,
      orientation,
      registerMountedTabPanel,
      setTabMap,
      unregisterMountedTabPanel,
      tabActivationDirection,
      value
    }), [getTabElementBySelectedValue, getTabIdByPanelValue, getTabPanelIdByValue, onValueChange, orientation, registerMountedTabPanel, setTabMap, unregisterMountedTabPanel, tabActivationDirection, value]);
    const selectedTabMetadata = React54.useMemo(() => {
      for (const tabMetadata of tabMap.values()) {
        if (tabMetadata != null && tabMetadata.value === value) {
          return tabMetadata;
        }
      }
      return void 0;
    }, [tabMap, value]);
    const firstEnabledTabValue = React54.useMemo(() => {
      for (const tabMetadata of tabMap.values()) {
        if (tabMetadata != null && !tabMetadata.disabled) {
          return tabMetadata.value;
        }
      }
      return void 0;
    }, [tabMap]);
    const shouldNotifyInitialValueChangeRef = React54.useRef(!hasExplicitDefaultValueProp);
    const initialDefaultValueRef = React54.useRef(defaultValueProp);
    const shouldHonorDisabledDefaultValueRef = React54.useRef(hasExplicitDefaultValueProp);
    const didRegisterTabsRef = React54.useRef(false);
    useIsoLayoutEffect(() => {
      if (isControlled) {
        return;
      }
      function commitAutomaticValueChange(fallbackValue, fallbackReason) {
        setValue(fallbackValue);
        setActivationDirectionState((prev) => {
          if (prev.previousValue === fallbackValue && prev.tabActivationDirection === "none") {
            return prev;
          }
          return {
            previousValue: fallbackValue,
            tabActivationDirection: "none"
          };
        });
        notifyAutomaticValueChange(fallbackValue, fallbackReason);
        shouldNotifyInitialValueChangeRef.current = false;
      }
      if (tabMap.size === 0) {
        if (didRegisterTabsRef.current && value !== null && !lastKnownTabElementRef.current?.isConnected) {
          commitAutomaticValueChange(null, reason_parts_exports.missing);
        }
        return;
      }
      didRegisterTabsRef.current = true;
      lastKnownTabElementRef.current = tabMap.keys().next().value;
      const selectionIsDisabled = selectedTabMetadata?.disabled;
      const selectionIsMissing = selectedTabMetadata == null && value !== null;
      if (!selectionIsDisabled && value === initialDefaultValueRef.current) {
        shouldHonorDisabledDefaultValueRef.current = false;
      }
      if (shouldHonorDisabledDefaultValueRef.current && selectionIsDisabled && value === initialDefaultValueRef.current) {
        return;
      }
      const shouldNotifyInitialValueChange = shouldNotifyInitialValueChangeRef.current;
      if (selectionIsDisabled || selectionIsMissing) {
        const fallbackValue = firstEnabledTabValue ?? null;
        if (value === fallbackValue) {
          shouldNotifyInitialValueChangeRef.current = false;
          return;
        }
        let fallbackReason = reason_parts_exports.missing;
        if (shouldNotifyInitialValueChange) {
          fallbackReason = reason_parts_exports.initial;
        } else if (selectionIsDisabled) {
          fallbackReason = reason_parts_exports.disabled;
        }
        commitAutomaticValueChange(fallbackValue, fallbackReason);
        return;
      }
      if (shouldNotifyInitialValueChange && selectedTabMetadata != null) {
        notifyAutomaticValueChange(value, reason_parts_exports.initial);
        shouldNotifyInitialValueChangeRef.current = false;
      }
    }, [firstEnabledTabValue, isControlled, notifyAutomaticValueChange, selectedTabMetadata, setValue, tabMap, value]);
    const state2 = {
      orientation,
      tabActivationDirection
    };
    const element = useRenderElement("div", componentProps, {
      state: state2,
      ref: forwardedRef,
      props: elementProps,
      stateAttributesMapping: tabsStateAttributesMapping
    });
    return /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(TabsRootContext.Provider, {
      value: tabsContextValue,
      children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(CompositeList, {
        elementsRef: tabPanelRefs,
        children: element
      })
    });
  });
  if (true) TabsRoot.displayName = "TabsRoot";
  function computeActivationDirection(oldValue, newValue, orientation, tabMap) {
    if (oldValue == null || newValue == null) {
      return "none";
    }
    let oldTab = null;
    let newTab = null;
    for (const [tabElement, tabMetadata] of tabMap.entries()) {
      if (tabMetadata == null) {
        continue;
      }
      const tabValue = tabMetadata.value ?? tabMetadata.index;
      if (oldValue === tabValue) {
        oldTab = tabElement;
      }
      if (newValue === tabValue) {
        newTab = tabElement;
      }
      if (oldTab != null && newTab != null) {
        break;
      }
    }
    if (oldTab == null || newTab == null) {
      if (oldTab !== newTab && (typeof oldValue === "number" || typeof oldValue === "string") && typeof oldValue === typeof newValue) {
        if (orientation === "horizontal") {
          return newValue > oldValue ? "right" : "left";
        }
        return newValue > oldValue ? "down" : "up";
      }
      return "none";
    }
    const oldRect = oldTab.getBoundingClientRect();
    const newRect = newTab.getBoundingClientRect();
    if (orientation === "horizontal") {
      if (newRect.left < oldRect.left) {
        return "left";
      }
      if (newRect.left > oldRect.left) {
        return "right";
      }
    } else {
      if (newRect.top < oldRect.top) {
        return "up";
      }
      if (newRect.top > oldRect.top) {
        return "down";
      }
    }
    return "none";
  }

  // node_modules/@base-ui/react/tabs/tab/TabsTab.mjs
  var React56 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/tabs/list/TabsListContext.mjs
  var React55 = __toESM(require_react(), 1);
  var TabsListContext = /* @__PURE__ */ React55.createContext(void 0);
  if (true) TabsListContext.displayName = "TabsListContext";
  function useTabsListContext() {
    const context = React55.useContext(TabsListContext);
    if (context === void 0) {
      throw new Error(true ? "Base UI: TabsListContext is missing. TabsList parts must be placed within <Tabs.List>." : formatErrorMessage_default(65));
    }
    return context;
  }

  // node_modules/@base-ui/react/tabs/tab/TabsTab.mjs
  var TabsTab = /* @__PURE__ */ React56.forwardRef(function TabsTab2(componentProps, forwardedRef) {
    const {
      className,
      disabled: disabled2 = false,
      render: render5,
      value,
      id: idProp,
      nativeButton = true,
      style,
      ...elementProps
    } = componentProps;
    const {
      value: activeTabValue,
      getTabPanelIdByValue,
      orientation,
      tabActivationDirection
    } = useTabsRootContext();
    const {
      activateOnFocus,
      highlightedTabIndex,
      onTabActivation,
      registerTabResizeObserverElement,
      setHighlightedTabIndex,
      tabsListElement
    } = useTabsListContext();
    const id = useBaseUiId(idProp);
    const tabMetadata = React56.useMemo(() => ({
      disabled: disabled2,
      id,
      value
    }), [disabled2, id, value]);
    const {
      compositeProps,
      compositeRef,
      index: index2
      // hook is used instead of the CompositeItem component
      // because the index is needed for Tab internals
    } = useCompositeItem({
      metadata: tabMetadata
    });
    const active = value === activeTabValue;
    const isNavigatingRef = React56.useRef(false);
    const tabElementRef = React56.useRef(null);
    useIsoLayoutEffect(() => {
      const tabElement = tabElementRef.current;
      if (!tabElement) {
        return void 0;
      }
      return registerTabResizeObserverElement(tabElement);
    }, [registerTabResizeObserverElement]);
    useIsoLayoutEffect(() => {
      if (isNavigatingRef.current) {
        isNavigatingRef.current = false;
        return;
      }
      if (!(active && index2 > -1 && highlightedTabIndex !== index2)) {
        return;
      }
      const listElement = tabsListElement;
      if (listElement != null) {
        const activeEl = activeElement(ownerDocument(listElement));
        if (activeEl && contains(listElement, activeEl)) {
          return;
        }
      }
      if (!disabled2) {
        setHighlightedTabIndex(index2);
      }
    }, [active, index2, highlightedTabIndex, setHighlightedTabIndex, disabled2, tabsListElement]);
    const {
      getButtonProps,
      buttonRef
    } = useButton({
      disabled: disabled2,
      native: nativeButton,
      focusableWhenDisabled: true
    });
    const tabPanelId = getTabPanelIdByValue(value);
    const isPressingRef = React56.useRef(false);
    const isMainButtonRef = React56.useRef(false);
    function onClick(event) {
      if (active || disabled2) {
        return;
      }
      onTabActivation(value, createChangeEventDetails(reason_parts_exports.none, event.nativeEvent, void 0, {
        activationDirection: "none"
      }));
    }
    function onFocus(event) {
      if (active) {
        return;
      }
      if (index2 > -1 && !disabled2) {
        setHighlightedTabIndex(index2);
      }
      if (disabled2) {
        return;
      }
      if (activateOnFocus && (!isPressingRef.current || // keyboard or touch focus
      isPressingRef.current && isMainButtonRef.current)) {
        onTabActivation(value, createChangeEventDetails(reason_parts_exports.none, event.nativeEvent, void 0, {
          activationDirection: "none"
        }));
      }
    }
    function onPointerDown(event) {
      if (active || disabled2) {
        return;
      }
      isPressingRef.current = true;
      function handlePointerUp() {
        isPressingRef.current = false;
        isMainButtonRef.current = false;
      }
      if (!event.button || event.button === 0) {
        isMainButtonRef.current = true;
        const doc = ownerDocument(event.currentTarget);
        doc.addEventListener("pointerup", handlePointerUp, {
          once: true
        });
      }
    }
    const state2 = {
      disabled: disabled2,
      active,
      orientation,
      tabActivationDirection
    };
    const element = useRenderElement("button", componentProps, {
      state: state2,
      ref: [forwardedRef, buttonRef, compositeRef, tabElementRef],
      props: [compositeProps, {
        role: "tab",
        "aria-controls": tabPanelId,
        "aria-selected": active,
        id,
        onClick,
        onFocus,
        onPointerDown,
        [ACTIVE_COMPOSITE_ITEM]: active ? "" : void 0,
        onKeyDownCapture() {
          isNavigatingRef.current = true;
        }
      }, elementProps, getButtonProps],
      stateAttributesMapping: tabsStateAttributesMapping
    });
    return element;
  });
  if (true) TabsTab.displayName = "TabsTab";

  // node_modules/@base-ui/react/tabs/indicator/TabsIndicator.mjs
  var React57 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/tabs/indicator/prehydrationScript.min.mjs
  var script = '!function(){const t=document.currentScript.previousElementSibling;if(!t)return;const e=t.closest(\'[role="tablist"]\');if(!e)return;const i=e.querySelector("[data-active]");if(!i)return;if(0===i.offsetWidth||0===e.offsetWidth)return;let o=0,n=0,h=0,l=0,r=0,f=0;function s(t){const e=getComputedStyle(t);let i=parseFloat(e.width)||0,o=parseFloat(e.height)||0;return(Math.round(i)!==t.offsetWidth||Math.round(o)!==t.offsetHeight)&&(i=t.offsetWidth,o=t.offsetHeight),{width:i,height:o}}if(null!=i&&null!=e){const{width:t,height:c}=s(i),{width:u,height:d}=s(e),a=i.getBoundingClientRect(),g=e.getBoundingClientRect(),p=u>0?g.width/u:1,b=d>0?g.height/d:1;if(Math.abs(p)>Number.EPSILON&&Math.abs(b)>Number.EPSILON){const t=a.left-g.left,i=a.top-g.top;o=t/p+e.scrollLeft-e.clientLeft,h=i/b+e.scrollTop-e.clientTop}else o=i.offsetLeft,h=i.offsetTop;r=t,f=c,n=e.scrollWidth-o-r,l=e.scrollHeight-h-f}function c(e,i){t.style.setProperty(`--active-tab-${e}`,`${i}px`)}c("left",o),c("right",n),c("top",h),c("bottom",l),c("width",r),c("height",f),r>0&&f>0&&t.removeAttribute("hidden")}();';

  // node_modules/@base-ui/react/tabs/indicator/TabsIndicatorCssVars.mjs
  var TabsIndicatorCssVars = /* @__PURE__ */ (function(TabsIndicatorCssVars2) {
    TabsIndicatorCssVars2["activeTabLeft"] = "--active-tab-left";
    TabsIndicatorCssVars2["activeTabRight"] = "--active-tab-right";
    TabsIndicatorCssVars2["activeTabTop"] = "--active-tab-top";
    TabsIndicatorCssVars2["activeTabBottom"] = "--active-tab-bottom";
    TabsIndicatorCssVars2["activeTabWidth"] = "--active-tab-width";
    TabsIndicatorCssVars2["activeTabHeight"] = "--active-tab-height";
    return TabsIndicatorCssVars2;
  })({});

  // node_modules/@base-ui/react/tabs/indicator/TabsIndicator.mjs
  var import_jsx_runtime107 = __toESM(require_jsx_runtime(), 1);
  var stateAttributesMapping2 = {
    ...tabsStateAttributesMapping,
    activeTabPosition: () => null,
    activeTabSize: () => null
  };
  var TabsIndicator = /* @__PURE__ */ React57.forwardRef(function TabsIndicator2(componentProps, forwardedRef) {
    const {
      className,
      render: render5,
      renderBeforeHydration = false,
      style: styleProp,
      ...elementProps
    } = componentProps;
    const {
      nonce
    } = useCSPContext();
    const {
      getTabElementBySelectedValue,
      orientation,
      tabActivationDirection,
      value
    } = useTabsRootContext();
    const {
      tabsListElement,
      registerIndicatorUpdateListener
    } = useTabsListContext();
    const isHydrating = useIsHydrating();
    const rerender = useForcedRerendering();
    React57.useEffect(() => {
      return registerIndicatorUpdateListener(rerender);
    }, [registerIndicatorUpdateListener, rerender]);
    let left = 0;
    let right = 0;
    let top = 0;
    let bottom = 0;
    let width = 0;
    let height = 0;
    let isTabSelected = false;
    if (value != null && tabsListElement != null) {
      const activeTab = getTabElementBySelectedValue(value);
      if (activeTab != null) {
        isTabSelected = true;
        const {
          width: computedWidth,
          height: computedHeight
        } = getCssDimensions2(activeTab);
        const {
          width: tabListWidth,
          height: tabListHeight
        } = getCssDimensions2(tabsListElement);
        const tabRect = activeTab.getBoundingClientRect();
        const tabsListRect = tabsListElement.getBoundingClientRect();
        const scaleX = tabListWidth > 0 ? tabsListRect.width / tabListWidth : 1;
        const scaleY = tabListHeight > 0 ? tabsListRect.height / tabListHeight : 1;
        const hasNonZeroScale = Math.abs(scaleX) > Number.EPSILON && Math.abs(scaleY) > Number.EPSILON;
        if (hasNonZeroScale) {
          const tabLeftDelta = tabRect.left - tabsListRect.left;
          const tabTopDelta = tabRect.top - tabsListRect.top;
          left = tabLeftDelta / scaleX + tabsListElement.scrollLeft - tabsListElement.clientLeft;
          top = tabTopDelta / scaleY + tabsListElement.scrollTop - tabsListElement.clientTop;
        } else {
          left = activeTab.offsetLeft;
          top = activeTab.offsetTop;
        }
        width = computedWidth;
        height = computedHeight;
        right = tabsListElement.scrollWidth - left - width;
        bottom = tabsListElement.scrollHeight - top - height;
      }
    }
    const activeTabPosition = isTabSelected ? {
      left,
      right,
      top,
      bottom
    } : null;
    const activeTabSize = isTabSelected ? {
      width,
      height
    } : null;
    const style = isTabSelected ? {
      [TabsIndicatorCssVars.activeTabLeft]: `${left}px`,
      [TabsIndicatorCssVars.activeTabRight]: `${right}px`,
      [TabsIndicatorCssVars.activeTabTop]: `${top}px`,
      [TabsIndicatorCssVars.activeTabBottom]: `${bottom}px`,
      [TabsIndicatorCssVars.activeTabWidth]: `${width}px`,
      [TabsIndicatorCssVars.activeTabHeight]: `${height}px`
    } : void 0;
    const displayIndicator = isTabSelected && width > 0 && height > 0;
    const state2 = {
      orientation,
      activeTabPosition,
      activeTabSize,
      tabActivationDirection
    };
    const element = useRenderElement("span", componentProps, {
      state: state2,
      ref: forwardedRef,
      props: [{
        role: "presentation",
        style,
        hidden: !displayIndicator
        // do not display the indicator before the layout is settled
      }, elementProps, {
        suppressHydrationWarning: true
      }],
      stateAttributesMapping: stateAttributesMapping2
    });
    if (value == null) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(React57.Fragment, {
      children: [element, isHydrating && renderBeforeHydration && /* @__PURE__ */ (0, import_jsx_runtime107.jsx)("script", {
        nonce,
        dangerouslySetInnerHTML: {
          __html: script
        },
        suppressHydrationWarning: true
      })]
    });
  });
  if (true) TabsIndicator.displayName = "TabsIndicator";

  // node_modules/@base-ui/react/tabs/panel/TabsPanel.mjs
  var React58 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/tabs/panel/TabsPanelDataAttributes.mjs
  var TabsPanelDataAttributes = (function(TabsPanelDataAttributes2) {
    TabsPanelDataAttributes2["index"] = "data-index";
    TabsPanelDataAttributes2["activationDirection"] = "data-activation-direction";
    TabsPanelDataAttributes2["orientation"] = "data-orientation";
    TabsPanelDataAttributes2["hidden"] = "data-hidden";
    TabsPanelDataAttributes2[TabsPanelDataAttributes2["startingStyle"] = TransitionStatusDataAttributes.startingStyle] = "startingStyle";
    TabsPanelDataAttributes2[TabsPanelDataAttributes2["endingStyle"] = TransitionStatusDataAttributes.endingStyle] = "endingStyle";
    return TabsPanelDataAttributes2;
  })({});

  // node_modules/@base-ui/react/tabs/panel/TabsPanel.mjs
  var stateAttributesMapping3 = {
    ...tabsStateAttributesMapping,
    ...transitionStatusMapping
  };
  var TabsPanel = /* @__PURE__ */ React58.forwardRef(function TabsPanel2(componentProps, forwardedRef) {
    const {
      className,
      value,
      render: render5,
      keepMounted = false,
      style,
      ...elementProps
    } = componentProps;
    const {
      value: selectedValue,
      getTabIdByPanelValue,
      orientation,
      tabActivationDirection,
      registerMountedTabPanel,
      unregisterMountedTabPanel
    } = useTabsRootContext();
    const id = useBaseUiId();
    const metadata = React58.useMemo(() => ({
      id,
      value
    }), [id, value]);
    const {
      ref: listItemRef,
      index: index2
    } = useCompositeListItem({
      metadata
    });
    const open = value === selectedValue;
    const {
      mounted,
      transitionStatus,
      setMounted
    } = useTransitionStatus(open);
    const hidden = !mounted;
    const correspondingTabId = getTabIdByPanelValue(value);
    const state2 = {
      hidden,
      orientation,
      tabActivationDirection,
      transitionStatus
    };
    const panelRef = React58.useRef(null);
    const element = useRenderElement("div", componentProps, {
      state: state2,
      ref: [forwardedRef, listItemRef, panelRef],
      props: [{
        "aria-labelledby": correspondingTabId,
        hidden,
        id,
        role: "tabpanel",
        tabIndex: open ? 0 : -1,
        inert: inertValue(!open),
        [TabsPanelDataAttributes.index]: index2
      }, elementProps],
      stateAttributesMapping: stateAttributesMapping3
    });
    useOpenChangeComplete({
      open,
      ref: panelRef,
      onComplete() {
        if (!open) {
          setMounted(false);
        }
      }
    });
    useIsoLayoutEffect(() => {
      if (hidden && !keepMounted) {
        return void 0;
      }
      if (id == null) {
        return void 0;
      }
      registerMountedTabPanel(value, id);
      return () => {
        unregisterMountedTabPanel(value, id);
      };
    }, [hidden, keepMounted, value, id, registerMountedTabPanel, unregisterMountedTabPanel]);
    const shouldRender = keepMounted || mounted;
    if (!shouldRender) {
      return null;
    }
    return element;
  });
  if (true) TabsPanel.displayName = "TabsPanel";

  // node_modules/@base-ui/react/tabs/list/TabsList.mjs
  var React59 = __toESM(require_react(), 1);
  var import_jsx_runtime108 = __toESM(require_jsx_runtime(), 1);
  var TabsList = /* @__PURE__ */ React59.forwardRef(function TabsList2(componentProps, forwardedRef) {
    const {
      activateOnFocus = false,
      className,
      loopFocus = true,
      render: render5,
      style,
      ...elementProps
    } = componentProps;
    const {
      onValueChange,
      orientation,
      value,
      setTabMap,
      tabActivationDirection
    } = useTabsRootContext();
    const [highlightedTabIndex, setHighlightedTabIndex] = React59.useState(0);
    const [tabsListElement, setTabsListElement] = React59.useState(null);
    const indicatorUpdateListenersRef = React59.useRef(/* @__PURE__ */ new Set());
    const tabResizeObserverElementsRef = React59.useRef(/* @__PURE__ */ new Set());
    const resizeObserverRef = React59.useRef(null);
    useIsoLayoutEffect(() => {
      if (typeof ResizeObserver === "undefined") {
        return void 0;
      }
      const resizeObserver = new ResizeObserver(() => {
        indicatorUpdateListenersRef.current.forEach((listener) => {
          listener();
        });
      });
      resizeObserverRef.current = resizeObserver;
      if (tabsListElement) {
        resizeObserver.observe(tabsListElement);
      }
      tabResizeObserverElementsRef.current.forEach((element) => {
        resizeObserver.observe(element);
      });
      return () => {
        resizeObserver.disconnect();
        resizeObserverRef.current = null;
      };
    }, [tabsListElement]);
    const registerIndicatorUpdateListener = useStableCallback((listener) => {
      indicatorUpdateListenersRef.current.add(listener);
      return () => {
        indicatorUpdateListenersRef.current.delete(listener);
      };
    });
    const registerTabResizeObserverElement = useStableCallback((element) => {
      tabResizeObserverElementsRef.current.add(element);
      resizeObserverRef.current?.observe(element);
      return () => {
        tabResizeObserverElementsRef.current.delete(element);
        resizeObserverRef.current?.unobserve(element);
      };
    });
    const onTabActivation = useStableCallback((newValue, eventDetails) => {
      if (newValue !== value) {
        onValueChange(newValue, eventDetails);
      }
    });
    const state2 = {
      orientation,
      tabActivationDirection
    };
    const defaultProps = {
      "aria-orientation": orientation === "vertical" ? "vertical" : void 0,
      role: "tablist"
    };
    const tabsListContextValue = React59.useMemo(() => ({
      activateOnFocus,
      highlightedTabIndex,
      registerIndicatorUpdateListener,
      registerTabResizeObserverElement,
      onTabActivation,
      setHighlightedTabIndex,
      tabsListElement
    }), [activateOnFocus, highlightedTabIndex, registerIndicatorUpdateListener, registerTabResizeObserverElement, onTabActivation, setHighlightedTabIndex, tabsListElement]);
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(TabsListContext.Provider, {
      value: tabsListContextValue,
      children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(CompositeRoot, {
        render: render5,
        className,
        style,
        state: state2,
        refs: [forwardedRef, setTabsListElement],
        props: [defaultProps, elementProps],
        stateAttributesMapping: tabsStateAttributesMapping,
        highlightedIndex: highlightedTabIndex,
        enableHomeAndEndKeys: true,
        loopFocus,
        orientation,
        onHighlightedIndexChange: setHighlightedTabIndex,
        onMapChange: setTabMap,
        disabledIndices: EMPTY_ARRAY3
      })
    });
  });
  if (true) TabsList.displayName = "TabsList";

  // node_modules/@base-ui/react/tooltip/index.parts.mjs
  var index_parts_exports3 = {};
  __export(index_parts_exports3, {
    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 React62 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/tooltip/root/TooltipRootContext.mjs
  var React60 = __toESM(require_react(), 1);
  var TooltipRootContext = /* @__PURE__ */ React60.createContext(void 0);
  if (true) TooltipRootContext.displayName = "TooltipRootContext";
  function useTooltipRootContext(optional) {
    const context = React60.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 React61 = __toESM(require_react(), 1);
  var selectors2 = {
    ...popupStoreSelectors,
    disabled: createSelector3((state2) => state2.disabled),
    instantType: createSelector3((state2) => state2.instantType),
    isInstantPhase: createSelector3((state2) => state2.isInstantPhase),
    trackCursorAxis: createSelector3((state2) => state2.trackCursorAxis),
    disableHoverablePopup: createSelector3((state2) => state2.disableHoverablePopup),
    lastOpenChangeReason: createSelector3((state2) => state2.openChangeReason),
    closeOnClick: createSelector3((state2) => state2.closeOnClick),
    closeDelay: createSelector3((state2) => state2.closeDelay),
    hasViewport: createSelector3((state2) => state2.hasViewport)
  };
  var TooltipStore = class _TooltipStore extends ReactStore {
    constructor(initialState, floatingId, nested = false) {
      const triggerElements = new PopupTriggerMap();
      const state2 = {
        ...createInitialState(),
        ...initialState
      };
      state2.floatingRootContext = createPopupFloatingRootContext(triggerElements, floatingId, nested);
      super(state2, {
        popupRef: /* @__PURE__ */ React61.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 store4 = usePopupStore(externalStore, (floatingId, nested) => new _TooltipStore(initialState, floatingId, nested)).store;
      return store4;
    }
  };
  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_runtime109 = __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 store4 = TooltipStore.useStore(handle?.store, {
      open: defaultOpen,
      openProp,
      activeTriggerId: defaultTriggerIdProp,
      triggerIdProp
    });
    useInitialOpenSync(store4, openProp, defaultOpen, defaultTriggerIdProp);
    store4.useControlledProp("openProp", openProp);
    store4.useControlledProp("triggerIdProp", triggerIdProp);
    store4.useContextCallback("onOpenChange", onOpenChange);
    store4.useContextCallback("onOpenChangeComplete", onOpenChangeComplete);
    const openState = store4.useState("open");
    const open = !disabled2 && openState;
    const activeTriggerId = store4.useState("activeTriggerId");
    const mounted = store4.useState("mounted");
    const payload = store4.useState("payload");
    store4.useSyncedValues({
      trackCursorAxis,
      disableHoverablePopup
    });
    store4.useSyncedValue("disabled", disabled2);
    useImplicitActiveTrigger(store4, {
      closeOnActiveTriggerUnmount: true
    });
    const {
      forceUnmount,
      transitionStatus
    } = useOpenStateTransitions(open, store4);
    const isInstantPhase = store4.useState("isInstantPhase");
    const instantType = store4.useState("instantType");
    const lastOpenChangeReason = store4.useState("lastOpenChangeReason");
    const previousInstantTypeRef = React62.useRef(null);
    useIsoLayoutEffect(() => {
      if (openState && disabled2) {
        store4.setOpen(false, createChangeEventDetails(reason_parts_exports.disabled));
      }
    }, [openState, disabled2, store4]);
    useIsoLayoutEffect(() => {
      if (transitionStatus === "ending" && lastOpenChangeReason === reason_parts_exports.none || transitionStatus !== "ending" && isInstantPhase) {
        if (instantType !== "delay") {
          previousInstantTypeRef.current = instantType;
        }
        store4.set("instantType", "delay");
      } else if (previousInstantTypeRef.current !== null) {
        store4.set("instantType", previousInstantTypeRef.current);
        previousInstantTypeRef.current = null;
      }
    }, [transitionStatus, isInstantPhase, lastOpenChangeReason, instantType, store4]);
    useIsoLayoutEffect(() => {
      if (open) {
        if (activeTriggerId == null) {
          store4.set("payload", void 0);
        }
      }
    }, [store4, activeTriggerId, open]);
    const handleImperativeClose = React62.useCallback(() => {
      store4.setOpen(false, createChangeEventDetails(reason_parts_exports.imperativeAction));
    }, [store4]);
    React62.useImperativeHandle(actionsRef, () => ({
      unmount: forceUnmount,
      close: handleImperativeClose
    }), [forceUnmount, handleImperativeClose]);
    const shouldRenderInteractions = open || mounted || !disabled2 && trackCursorAxis !== "none";
    return /* @__PURE__ */ (0, import_jsx_runtime109.jsxs)(TooltipRootContext.Provider, {
      value: store4,
      children: [shouldRenderInteractions && /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(TooltipInteractions, {
        store: store4,
        disabled: disabled2,
        trackCursorAxis
      }), typeof children === "function" ? children({
        payload
      }) : children]
    });
  });
  if (true) TooltipRoot.displayName = "TooltipRoot";
  function TooltipInteractions({
    store: store4,
    disabled: disabled2,
    trackCursorAxis
  }) {
    const floatingRootContext = store4.useState("floatingRootContext");
    const dismiss = useDismiss(floatingRootContext, {
      enabled: !disabled2,
      referencePress: () => store4.select("closeOnClick")
    });
    const clientPoint = useClientPoint(floatingRootContext, {
      enabled: !disabled2 && trackCursorAxis !== "none",
      axis: trackCursorAxis === "none" ? void 0 : trackCursorAxis
    });
    const activeTriggerProps = React62.useMemo(() => mergeProps(clientPoint.reference, dismiss.reference), [clientPoint.reference, dismiss.reference]);
    const inactiveTriggerProps = React62.useMemo(() => mergeProps(clientPoint.trigger, dismiss.trigger), [clientPoint.trigger, dismiss.trigger]);
    const popupProps = React62.useMemo(() => mergeProps(FOCUSABLE_POPUP_PROPS, clientPoint.floating, dismiss.floating), [clientPoint.floating, dismiss.floating]);
    usePopupInteractionProps(store4, {
      activeTriggerProps,
      inactiveTriggerProps,
      popupProps
    });
    return null;
  }

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

  // node_modules/@base-ui/react/tooltip/provider/TooltipProviderContext.mjs
  var React63 = __toESM(require_react(), 1);
  var TooltipProviderContext = /* @__PURE__ */ React63.createContext(void 0);
  if (true) TooltipProviderContext.displayName = "TooltipProviderContext";
  function useTooltipProviderContext() {
    return React63.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 i3 = 0; i3 < path.length; i3 += 1) {
        const element = path[i3];
        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: render5,
      className,
      style,
      handle,
      payload,
      disabled: disabledProp,
      delay,
      closeOnClick = true,
      closeDelay,
      id: idProp,
      ...elementProps
    } = componentProps;
    const rootContext = useTooltipRootContext(true);
    const store4 = handle?.store ?? rootContext;
    if (!store4) {
      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 = store4.useState("isTriggerActive", thisTriggerId);
    const isOpenedByThisTrigger = store4.useState("isOpenedByTrigger", thisTriggerId);
    const floatingRootContext = store4.useState("floatingRootContext");
    const triggerElementRef = React64.useRef(null);
    const delayWithDefault = delay ?? OPEN_DELAY;
    const closeDelayWithDefault = closeDelay ?? 0;
    const {
      registerTrigger,
      isMountedByThisTrigger
    } = useTriggerDataForwarding(thisTriggerId, triggerElementRef, store4, {
      payload,
      closeOnClick,
      closeDelay: closeDelayWithDefault
    });
    const providerContext = useTooltipProviderContext();
    const {
      delayRef,
      isInstantPhase,
      hasProvider
    } = useDelayGroup(floatingRootContext, {
      open: isOpenedByThisTrigger
    });
    const hoverInteraction = useHoverInteractionSharedState(floatingRootContext);
    store4.useSyncedValue("isInstantPhase", isInstantPhase);
    const rootDisabled = store4.useState("disabled");
    const disabled2 = disabledProp ?? rootDisabled;
    const disabledRef = useValueAsRef(disabled2);
    const trackCursorAxis = store4.useState("trackCursorAxis");
    const disableHoverablePopup = store4.useState("disableHoverablePopup");
    const isNestedTriggerHoveredRef = React64.useRef(false);
    const nestedTriggerOpenTimeout = useTimeout();
    const pointerTypeRef = React64.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: () => store4.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 && store4.select("open") && store4.select("lastOpenChangeReason") === reason_parts_exports.triggerHover) {
        store4.setOpen(false, createChangeEventDetails(reason_parts_exports.triggerHover, event));
        return;
      }
      if (wasNestedTriggerHovered && !nestedTriggerHovered && targetInsideTrigger && !disabledRef.current && !store4.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 && !store4.select("open")) {
            store4.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 = store4.useState("triggerProps", isMountedByThisTrigger);
    const shouldApplyRootTriggerProps = isMountedByThisTrigger || trackCursorAxis !== "none";
    const state2 = {
      open: isOpenedByThisTrigger
    };
    const element = useRenderElement("button", componentProps, {
      state: state2,
      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;
          store4.set("closeOnClick", closeOnClick);
          if (closeOnClick && !store4.select("open")) {
            store4.cancelPendingOpen(event.nativeEvent);
          }
        },
        onClick(event) {
          if (closeOnClick && !store4.select("open")) {
            store4.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 React66 = __toESM(require_react(), 1);

  // node_modules/@base-ui/react/tooltip/portal/TooltipPortalContext.mjs
  var React65 = __toESM(require_react(), 1);
  var TooltipPortalContext = /* @__PURE__ */ React65.createContext(void 0);
  if (true) TooltipPortalContext.displayName = "TooltipPortalContext";
  function useTooltipPortalContext() {
    const value = React65.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_runtime110 = __toESM(require_jsx_runtime(), 1);
  var TooltipPortal = /* @__PURE__ */ React66.forwardRef(function TooltipPortal2(props, forwardedRef) {
    const {
      keepMounted = false,
      ...portalProps
    } = props;
    const store4 = useTooltipRootContext();
    const mounted = store4.useState("mounted");
    const shouldRender = mounted || keepMounted;
    if (!shouldRender) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(TooltipPortalContext.Provider, {
      value: keepMounted,
      children: /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(FloatingPortalLite, {
        ref: forwardedRef,
        ...portalProps
      })
    });
  });
  if (true) TooltipPortal.displayName = "TooltipPortal";

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

  // node_modules/@base-ui/react/tooltip/positioner/TooltipPositionerContext.mjs
  var React67 = __toESM(require_react(), 1);
  var TooltipPositionerContext = /* @__PURE__ */ React67.createContext(void 0);
  if (true) TooltipPositionerContext.displayName = "TooltipPositionerContext";
  function useTooltipPositionerContext() {
    const context = React67.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_runtime111 = __toESM(require_jsx_runtime(), 1);
  var TooltipPositioner = /* @__PURE__ */ React68.forwardRef(function TooltipPositioner2(componentProps, forwardedRef) {
    const {
      render: render5,
      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 store4 = useTooltipRootContext();
    const keepMounted = useTooltipPortalContext();
    const open = store4.useState("open");
    const mounted = store4.useState("mounted");
    const trackCursorAxis = store4.useState("trackCursorAxis");
    const disableHoverablePopup = store4.useState("disableHoverablePopup");
    const floatingRootContext = store4.useState("floatingRootContext");
    const instantType = store4.useState("instantType");
    const transitionStatus = store4.useState("transitionStatus");
    const hasViewport = store4.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 state2 = React68.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, state2, {
      styles: positioning.positionerStyles,
      transitionStatus,
      props: elementProps,
      refs: [forwardedRef, store4.useStateSetter("positionerElement")],
      hidden: !mounted,
      inert: !open || trackCursorAxis === "both" || disableHoverablePopup
    });
    return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(TooltipPositionerContext.Provider, {
      value: positioning,
      children: element
    });
  });
  if (true) TooltipPositioner.displayName = "TooltipPositioner";

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

  // node_modules/@base-ui/react/tooltip/arrow/TooltipArrow.mjs
  var React70 = __toESM(require_react(), 1);
  var TooltipArrow = /* @__PURE__ */ React70.forwardRef(function TooltipArrow2(componentProps, forwardedRef) {
    const {
      render: render5,
      className,
      style,
      ...elementProps
    } = componentProps;
    const store4 = useTooltipRootContext();
    const {
      arrowRef,
      side,
      align,
      arrowUncentered,
      arrowStyles
    } = useTooltipPositionerContext();
    const open = store4.useState("open");
    const instantType = store4.useState("instantType");
    const state2 = {
      open,
      side,
      align,
      uncentered: arrowUncentered,
      instant: instantType
    };
    const element = useRenderElement("div", componentProps, {
      state: state2,
      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 React71 = __toESM(require_react(), 1);
  var import_jsx_runtime112 = __toESM(require_jsx_runtime(), 1);
  var TooltipProvider = function TooltipProvider2(props) {
    const {
      delay,
      closeDelay,
      timeout = 400
    } = props;
    const contextValue = React71.useMemo(() => ({
      delay,
      closeDelay
    }), [delay, closeDelay]);
    const delayValue = React71.useMemo(() => ({
      open: delay,
      close: closeDelay
    }), [delay, closeDelay]);
    return /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(TooltipProviderContext.Provider, {
      value: contextValue,
      children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(FloatingDelayGroup, {
        delay: delayValue,
        timeoutMs: timeout,
        children: props.children
      })
    });
  };
  if (true) TooltipProvider.displayName = "TooltipProvider";

  // node_modules/@base-ui/react/tooltip/viewport/TooltipViewport.mjs
  var React72 = __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 stateAttributesMapping5 = {
    activationDirection: (value) => value ? {
      "data-activation-direction": value
    } : null
  };
  var TooltipViewport = /* @__PURE__ */ React72.forwardRef(function TooltipViewport2(componentProps, forwardedRef) {
    const {
      render: render5,
      className,
      style,
      children,
      ...elementProps
    } = componentProps;
    const store4 = useTooltipRootContext();
    const positioner = useTooltipPositionerContext();
    const instantType = store4.useState("instantType");
    const {
      children: childrenToRender,
      state: viewportState
    } = usePopupViewport({
      store: store4,
      side: positioner.side,
      cssVars: TooltipViewportCssVars,
      children
    });
    const state2 = {
      activationDirection: viewportState.activationDirection,
      transitioning: viewportState.transitioning,
      instant: instantType
    };
    return useRenderElement("div", componentProps, {
      state: state2,
      ref: forwardedRef,
      props: [elementProps, {
        children: childrenToRender
      }],
      stateAttributesMapping: stateAttributesMapping5
    });
  });
  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_element14 = __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_element14.forwardRef)(function Text2({ variant = "body-md", render: render5, className, ...props }, ref) {
    const element = useRender({
      render: render5,
      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_runtime113 = __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_element15.forwardRef)(function Badge2({ intent = "none", className, ...props }, ref) {
    return /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(
      Text,
      {
        ref,
        className: clsx_default(
          style_default2.badge,
          style_default2[`is-${intent}-intent`],
          className
        ),
        ...props,
        variant: "body-sm"
      }
    );
  });

  // packages/ui/build-module/button/button.mjs
  var import_a11y = __toESM(require_a11y(), 1);
  var import_element16 = __toESM(require_element(), 1);
  var import_i18n11 = __toESM(require_i18n(), 1);
  var import_jsx_runtime114 = __toESM(require_jsx_runtime(), 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("b74f1ac304", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._97b0fc33c028be1a__button,.abbb272e2ce49bd6__is-unstyled{appearance:none;padding:0}._97b0fc33c028be1a__button{--wp-ui-button-font-weight:var(--wpds-typography-font-weight-emphasis,600);--wp-ui-button-background-color:var(--wpds-color-background-interactive-brand-strong,var(--wp-admin-theme-color,#3858e9));--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-brand-strong-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 93%,#000));--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-brand-strong-disabled,#e6e6e6);--wp-ui-button-foreground-color:var(--wpds-color-foreground-interactive-brand-strong,#fff);--wp-ui-button-foreground-color-active:var(--wpds-color-foreground-interactive-brand-strong-active,#fff);--wp-ui-button-foreground-color-disabled:var(--wpds-color-foreground-interactive-brand-strong-disabled,#8d8d8d);--wp-ui-button-padding-block:var(--wpds-dimension-padding-xs,4px);--wp-ui-button-padding-inline:var(--wpds-dimension-padding-md,12px);--wp-ui-button-height:var(--wpds-dimension-size-lg,40px);--wp-ui-button-aspect-ratio:auto;--wp-ui-button-font-size:var(--wpds-typography-font-size-md,13px);--wp-ui-button-min-width:calc(4ch + var(--wp-ui-button-padding-inline)*2);--wp-ui-button-icon-margin:calc((var(--wpds-dimension-size-2xs, 16px) - var(--wpds-dimension-size-sm, 24px))/2);--wp-ui-button-border-color:var(--wp-ui-button-background-color);--wp-ui-button-border-color-active:var(--wp-ui-button-background-color-active);--wp-ui-button-border-color-disabled:var(--wp-ui-button-background-color-disabled);--_gcd-button-font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);--_gcd-button-font-size:var(--wp-ui-button-font-size);--_gcd-button-font-weight:var(--wp-ui-button-font-weight);align-items:center;aspect-ratio:var(--wp-ui-button-aspect-ratio);background-clip:border-box;background-color:var(--wp-ui-button-background-color);border-color:var(--wp-ui-button-border-color);border-radius:var(--wpds-border-radius-sm,2px);border-style:solid;border-width:1px;color:var(--wp-ui-button-foreground-color);display:inline-flex;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(--wp-ui-button-font-size);font-weight:var(--wp-ui-button-font-weight);gap:var(--wpds-dimension-gap-sm,8px);justify-content:center;line-height:var(--wpds-typography-line-height-sm,20px);max-width:100%;min-height:var(--wp-ui-button-height);min-width:var(--wp-ui-button-min-width);overflow-wrap:anywhere;padding-block:var(--wp-ui-button-padding-block);padding-inline:var(--wp-ui-button-padding-inline);position:relative;text-align:center;text-decoration:none;&:not([data-disabled]){cursor:var(--wpds-cursor-control,pointer)}@media not (prefers-reduced-motion){transition:color .1s ease-out;*{transition:opacity .1s ease-out}}&[href]{cursor:pointer}[href]{color:inherit;text-decoration:inherit}&:not([data-disabled]):is(:hover,:active,:focus){background-color:var(--wp-ui-button-background-color-active);border-color:var(--wp-ui-button-border-color-active);color:var(--wp-ui-button-foreground-color-active)}&[data-disabled]:not(._914b42f315c0e580__is-loading){background-color:var(--wp-ui-button-background-color-disabled);border-color:var(--wp-ui-button-border-color-disabled);color:var(--wp-ui-button-foreground-color-disabled);@media (forced-colors:active){border-bottom-color:GrayText;border-left-color:GrayText;border-right-color:GrayText;border-top-color:GrayText;color:GrayText}}&:before{aspect-ratio:1;border:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid;border-block-end-color:transparent;border-block-start-color:var(--wp-ui-button-foreground-color);border-inline-end-color:var(--wp-ui-button-foreground-color);border-inline-start-color:transparent;border-radius:50%;box-sizing:border-box;content:"";display:block;height:var(--wp-ui-button-font-size);inset-inline-start:50%;opacity:0;pointer-events:none;position:absolute;top:50%;transform:translate(-50%,-50%);@media not (prefers-reduced-motion){transition:opacity .1s ease-out}@media (forced-colors:active){border-block-end-style:none;border-bottom-color:ButtonText;border-inline-start-style:none;border-left-color:ButtonText;border-right-color:ButtonText;border-top-color:ButtonText}}}._908205475f9f2a92__is-small{--wp-ui-button-padding-block:0px;--wp-ui-button-padding-inline:var(--wpds-dimension-padding-sm,8px);--wp-ui-button-height:var(--wpds-dimension-size-sm,24px)}._9f6fc6553aeb36fe__icon{margin:var(--wp-ui-button-icon-margin)}.dd460c965226cc77__is-brand{&._62d5a778b7b258ee__is-outline,&.ad0619a3217c6a5b__is-minimal{--wp-ui-button-foreground-color:var(--wpds-color-foreground-interactive-brand,var(--wp-admin-theme-color,#3858e9));--wp-ui-button-foreground-color-active:var(--wpds-color-foreground-interactive-brand-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 52%,#000));--wp-ui-button-foreground-color-disabled:var(--wpds-color-foreground-interactive-brand-disabled,#8d8d8d)}&._62d5a778b7b258ee__is-outline{--wp-ui-button-background-color:var(--wpds-color-background-interactive-brand-weak,#0000);--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-brand-weak-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 12%,#fff));--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-brand-weak-disabled,#0000);--wp-ui-button-border-color:var(--wpds-color-stroke-interactive-brand,var(--wp-admin-theme-color,#3858e9));--wp-ui-button-border-color-active:var(--wpds-color-stroke-interactive-brand-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 85%,#000));--wp-ui-button-border-color-disabled:var(--wpds-color-stroke-interactive-brand-disabled,#dbdbdb)}&.ad0619a3217c6a5b__is-minimal{--wp-ui-button-background-color:var(--wpds-color-background-interactive-brand-weak,#0000);--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-brand-weak-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 12%,#fff));--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-brand-weak-disabled,#0000)}}.e722a8f96726aa99__is-neutral{&.ad0619a3217c6a5b__is-minimal[aria-pressed=true],&.b50b3358c5fb4d0b__is-solid{--wp-ui-button-background-color:var(--wpds-color-background-interactive-neutral-strong,#2d2d2d);--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-neutral-strong-active,#1e1e1e);--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-neutral-strong-disabled,#e6e6e6);--wp-ui-button-foreground-color:var(--wpds-color-foreground-interactive-neutral-strong,#f0f0f0);--wp-ui-button-foreground-color-active:var(--wpds-color-foreground-interactive-neutral-strong-active,#f0f0f0);--wp-ui-button-foreground-color-disabled:var(--wpds-color-foreground-interactive-neutral-strong-disabled,#8d8d8d)}&._62d5a778b7b258ee__is-outline,&.ad0619a3217c6a5b__is-minimal:not([aria-pressed=true]){--wp-ui-button-foreground-color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);--wp-ui-button-foreground-color-active:var(--wpds-color-foreground-interactive-neutral-active,#1e1e1e);--wp-ui-button-foreground-color-disabled:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d)}&._62d5a778b7b258ee__is-outline{--wp-ui-button-background-color:var(--wpds-color-background-interactive-neutral-weak,#0000);--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-neutral-weak-active,#ededed);--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-neutral-weak-disabled,#0000);--wp-ui-button-border-color:var(--wpds-color-stroke-interactive-neutral,#8d8d8d);--wp-ui-button-border-color-active:var(--wpds-color-stroke-interactive-neutral-active,#6e6e6e);--wp-ui-button-border-color-disabled:var(--wpds-color-stroke-interactive-neutral-disabled,#dbdbdb)}&.ad0619a3217c6a5b__is-minimal:not([aria-pressed=true]){--wp-ui-button-background-color:var(--wpds-color-background-interactive-neutral-weak,#0000);--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-neutral-weak-active,#ededed);--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-neutral-weak-disabled,#0000)}}.abbb272e2ce49bd6__is-unstyled{background:none;border:none;min-width:unset}.cf59cf1b69629838__is-compact{--wp-ui-button-height:var(--wpds-dimension-size-md,32px)}._914b42f315c0e580__is-loading:not(.abbb272e2ce49bd6__is-unstyled){color:transparent;&:not([data-disabled]):is(:hover,:active,:focus){color:transparent}@media (forced-colors:active){color:ButtonFace}*{opacity:0}&:before{opacity:1;transition-delay:.05s;@media not (prefers-reduced-motion){animation:_5a1d53da6f830c8d__loading-animation 1s linear infinite}}}}@keyframes _5a1d53da6f830c8d__loading-animation{0%{transform:translate(-50%,-50%) rotate(0deg)}to{transform:translate(-50%,-50%) rotate(1turn)}}}');
  }
  var style_default3 = { "button": "_97b0fc33c028be1a__button", "is-unstyled": "abbb272e2ce49bd6__is-unstyled", "is-loading": "_914b42f315c0e580__is-loading", "is-small": "_908205475f9f2a92__is-small", "icon": "_9f6fc6553aeb36fe__icon", "is-brand": "dd460c965226cc77__is-brand", "is-outline": "_62d5a778b7b258ee__is-outline", "is-minimal": "ad0619a3217c6a5b__is-minimal", "is-neutral": "e722a8f96726aa99__is-neutral", "is-solid": "b50b3358c5fb4d0b__is-solid", "is-compact": "cf59cf1b69629838__is-compact", "loading-animation": "_5a1d53da6f830c8d__loading-animation" };
  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("da99a163ac", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._08e8a2e44959f892__outset-ring--focus:focus,.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,: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))}._970d04df7376df67__outset-ring--focus-within-except-active:focus-within,.e25b2bdd7aa21721__outset-ring--focus-except-active:focus{outline:none}._970d04df7376df67__outset-ring--focus-within-except-active:focus-within:not(:has(:active)),.e25b2bdd7aa21721__outset-ring--focus-except-active:focus:not(:active){@include mixins.focus-ring()}}}");
  }
  var focus_default = { "outset-ring--focus": "_08e8a2e44959f892__outset-ring--focus", "outset-ring--focus-visible": "d0541bc9dd9dc7b6__outset-ring--focus-visible", "outset-ring--focus-within": "cd83dfc2126a0846__outset-ring--focus-within", "outset-ring--focus-within-visible": "c5cb3ee4bddaa8e4__outset-ring--focus-within-visible", "outset-ring--focus-parent-visible": "ecadb9e080e2dfa5__outset-ring--focus-parent-visible", "outset-ring--focus-except-active": "e25b2bdd7aa21721__outset-ring--focus-except-active", "outset-ring--focus-within-except-active": "_970d04df7376df67__outset-ring--focus-within-except-active" };
  if (typeof process === "undefined" || true) {
    registerStyle3("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" };
  var Button4 = (0, import_element16.forwardRef)(
    function Button22({
      tone = "brand",
      variant = "solid",
      size: size4 = "default",
      className,
      focusableWhenDisabled = true,
      disabled: disabled2,
      loading,
      loadingAnnouncement = (0, import_i18n11.__)("Loading"),
      children,
      ...props
    }, ref) {
      const mergedClassName = clsx_default(
        global_css_defense_default2.button,
        resets_default["box-sizing"],
        focus_default["outset-ring--focus-except-active"],
        variant !== "unstyled" && style_default3.button,
        style_default3[`is-${tone}`],
        style_default3[`is-${variant}`],
        style_default3[`is-${size4}`],
        loading && style_default3["is-loading"],
        className
      );
      (0, import_element16.useEffect)(() => {
        if (loading && loadingAnnouncement) {
          (0, import_a11y.speak)(loadingAnnouncement);
        }
      }, [loading, loadingAnnouncement]);
      return /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(
        Button2,
        {
          ref,
          className: mergedClassName,
          focusableWhenDisabled,
          disabled: disabled2 ?? loading,
          ...props,
          children
        }
      );
    }
  );

  // packages/ui/build-module/button/icon.mjs
  var import_element18 = __toESM(require_element(), 1);

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

  // packages/ui/build-module/button/icon.mjs
  var import_jsx_runtime116 = __toESM(require_jsx_runtime(), 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("b74f1ac304", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._97b0fc33c028be1a__button,.abbb272e2ce49bd6__is-unstyled{appearance:none;padding:0}._97b0fc33c028be1a__button{--wp-ui-button-font-weight:var(--wpds-typography-font-weight-emphasis,600);--wp-ui-button-background-color:var(--wpds-color-background-interactive-brand-strong,var(--wp-admin-theme-color,#3858e9));--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-brand-strong-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 93%,#000));--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-brand-strong-disabled,#e6e6e6);--wp-ui-button-foreground-color:var(--wpds-color-foreground-interactive-brand-strong,#fff);--wp-ui-button-foreground-color-active:var(--wpds-color-foreground-interactive-brand-strong-active,#fff);--wp-ui-button-foreground-color-disabled:var(--wpds-color-foreground-interactive-brand-strong-disabled,#8d8d8d);--wp-ui-button-padding-block:var(--wpds-dimension-padding-xs,4px);--wp-ui-button-padding-inline:var(--wpds-dimension-padding-md,12px);--wp-ui-button-height:var(--wpds-dimension-size-lg,40px);--wp-ui-button-aspect-ratio:auto;--wp-ui-button-font-size:var(--wpds-typography-font-size-md,13px);--wp-ui-button-min-width:calc(4ch + var(--wp-ui-button-padding-inline)*2);--wp-ui-button-icon-margin:calc((var(--wpds-dimension-size-2xs, 16px) - var(--wpds-dimension-size-sm, 24px))/2);--wp-ui-button-border-color:var(--wp-ui-button-background-color);--wp-ui-button-border-color-active:var(--wp-ui-button-background-color-active);--wp-ui-button-border-color-disabled:var(--wp-ui-button-background-color-disabled);--_gcd-button-font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,"Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue",sans-serif);--_gcd-button-font-size:var(--wp-ui-button-font-size);--_gcd-button-font-weight:var(--wp-ui-button-font-weight);align-items:center;aspect-ratio:var(--wp-ui-button-aspect-ratio);background-clip:border-box;background-color:var(--wp-ui-button-background-color);border-color:var(--wp-ui-button-border-color);border-radius:var(--wpds-border-radius-sm,2px);border-style:solid;border-width:1px;color:var(--wp-ui-button-foreground-color);display:inline-flex;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(--wp-ui-button-font-size);font-weight:var(--wp-ui-button-font-weight);gap:var(--wpds-dimension-gap-sm,8px);justify-content:center;line-height:var(--wpds-typography-line-height-sm,20px);max-width:100%;min-height:var(--wp-ui-button-height);min-width:var(--wp-ui-button-min-width);overflow-wrap:anywhere;padding-block:var(--wp-ui-button-padding-block);padding-inline:var(--wp-ui-button-padding-inline);position:relative;text-align:center;text-decoration:none;&:not([data-disabled]){cursor:var(--wpds-cursor-control,pointer)}@media not (prefers-reduced-motion){transition:color .1s ease-out;*{transition:opacity .1s ease-out}}&[href]{cursor:pointer}[href]{color:inherit;text-decoration:inherit}&:not([data-disabled]):is(:hover,:active,:focus){background-color:var(--wp-ui-button-background-color-active);border-color:var(--wp-ui-button-border-color-active);color:var(--wp-ui-button-foreground-color-active)}&[data-disabled]:not(._914b42f315c0e580__is-loading){background-color:var(--wp-ui-button-background-color-disabled);border-color:var(--wp-ui-button-border-color-disabled);color:var(--wp-ui-button-foreground-color-disabled);@media (forced-colors:active){border-bottom-color:GrayText;border-left-color:GrayText;border-right-color:GrayText;border-top-color:GrayText;color:GrayText}}&:before{aspect-ratio:1;border:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid;border-block-end-color:transparent;border-block-start-color:var(--wp-ui-button-foreground-color);border-inline-end-color:var(--wp-ui-button-foreground-color);border-inline-start-color:transparent;border-radius:50%;box-sizing:border-box;content:"";display:block;height:var(--wp-ui-button-font-size);inset-inline-start:50%;opacity:0;pointer-events:none;position:absolute;top:50%;transform:translate(-50%,-50%);@media not (prefers-reduced-motion){transition:opacity .1s ease-out}@media (forced-colors:active){border-block-end-style:none;border-bottom-color:ButtonText;border-inline-start-style:none;border-left-color:ButtonText;border-right-color:ButtonText;border-top-color:ButtonText}}}._908205475f9f2a92__is-small{--wp-ui-button-padding-block:0px;--wp-ui-button-padding-inline:var(--wpds-dimension-padding-sm,8px);--wp-ui-button-height:var(--wpds-dimension-size-sm,24px)}._9f6fc6553aeb36fe__icon{margin:var(--wp-ui-button-icon-margin)}.dd460c965226cc77__is-brand{&._62d5a778b7b258ee__is-outline,&.ad0619a3217c6a5b__is-minimal{--wp-ui-button-foreground-color:var(--wpds-color-foreground-interactive-brand,var(--wp-admin-theme-color,#3858e9));--wp-ui-button-foreground-color-active:var(--wpds-color-foreground-interactive-brand-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 52%,#000));--wp-ui-button-foreground-color-disabled:var(--wpds-color-foreground-interactive-brand-disabled,#8d8d8d)}&._62d5a778b7b258ee__is-outline{--wp-ui-button-background-color:var(--wpds-color-background-interactive-brand-weak,#0000);--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-brand-weak-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 12%,#fff));--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-brand-weak-disabled,#0000);--wp-ui-button-border-color:var(--wpds-color-stroke-interactive-brand,var(--wp-admin-theme-color,#3858e9));--wp-ui-button-border-color-active:var(--wpds-color-stroke-interactive-brand-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 85%,#000));--wp-ui-button-border-color-disabled:var(--wpds-color-stroke-interactive-brand-disabled,#dbdbdb)}&.ad0619a3217c6a5b__is-minimal{--wp-ui-button-background-color:var(--wpds-color-background-interactive-brand-weak,#0000);--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-brand-weak-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 12%,#fff));--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-brand-weak-disabled,#0000)}}.e722a8f96726aa99__is-neutral{&.ad0619a3217c6a5b__is-minimal[aria-pressed=true],&.b50b3358c5fb4d0b__is-solid{--wp-ui-button-background-color:var(--wpds-color-background-interactive-neutral-strong,#2d2d2d);--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-neutral-strong-active,#1e1e1e);--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-neutral-strong-disabled,#e6e6e6);--wp-ui-button-foreground-color:var(--wpds-color-foreground-interactive-neutral-strong,#f0f0f0);--wp-ui-button-foreground-color-active:var(--wpds-color-foreground-interactive-neutral-strong-active,#f0f0f0);--wp-ui-button-foreground-color-disabled:var(--wpds-color-foreground-interactive-neutral-strong-disabled,#8d8d8d)}&._62d5a778b7b258ee__is-outline,&.ad0619a3217c6a5b__is-minimal:not([aria-pressed=true]){--wp-ui-button-foreground-color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);--wp-ui-button-foreground-color-active:var(--wpds-color-foreground-interactive-neutral-active,#1e1e1e);--wp-ui-button-foreground-color-disabled:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d)}&._62d5a778b7b258ee__is-outline{--wp-ui-button-background-color:var(--wpds-color-background-interactive-neutral-weak,#0000);--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-neutral-weak-active,#ededed);--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-neutral-weak-disabled,#0000);--wp-ui-button-border-color:var(--wpds-color-stroke-interactive-neutral,#8d8d8d);--wp-ui-button-border-color-active:var(--wpds-color-stroke-interactive-neutral-active,#6e6e6e);--wp-ui-button-border-color-disabled:var(--wpds-color-stroke-interactive-neutral-disabled,#dbdbdb)}&.ad0619a3217c6a5b__is-minimal:not([aria-pressed=true]){--wp-ui-button-background-color:var(--wpds-color-background-interactive-neutral-weak,#0000);--wp-ui-button-background-color-active:var(--wpds-color-background-interactive-neutral-weak-active,#ededed);--wp-ui-button-background-color-disabled:var(--wpds-color-background-interactive-neutral-weak-disabled,#0000)}}.abbb272e2ce49bd6__is-unstyled{background:none;border:none;min-width:unset}.cf59cf1b69629838__is-compact{--wp-ui-button-height:var(--wpds-dimension-size-md,32px)}._914b42f315c0e580__is-loading:not(.abbb272e2ce49bd6__is-unstyled){color:transparent;&:not([data-disabled]):is(:hover,:active,:focus){color:transparent}@media (forced-colors:active){color:ButtonFace}*{opacity:0}&:before{opacity:1;transition-delay:.05s;@media not (prefers-reduced-motion){animation:_5a1d53da6f830c8d__loading-animation 1s linear infinite}}}}@keyframes _5a1d53da6f830c8d__loading-animation{0%{transform:translate(-50%,-50%) rotate(0deg)}to{transform:translate(-50%,-50%) rotate(1turn)}}}');
  }
  var style_default4 = { "button": "_97b0fc33c028be1a__button", "is-unstyled": "abbb272e2ce49bd6__is-unstyled", "is-loading": "_914b42f315c0e580__is-loading", "is-small": "_908205475f9f2a92__is-small", "icon": "_9f6fc6553aeb36fe__icon", "is-brand": "dd460c965226cc77__is-brand", "is-outline": "_62d5a778b7b258ee__is-outline", "is-minimal": "ad0619a3217c6a5b__is-minimal", "is-neutral": "e722a8f96726aa99__is-neutral", "is-solid": "b50b3358c5fb4d0b__is-solid", "is-compact": "cf59cf1b69629838__is-compact", "loading-animation": "_5a1d53da6f830c8d__loading-animation" };
  var ButtonIcon = (0, import_element18.forwardRef)(
    function ButtonIcon2({ className, icon, ...props }, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(
        Icon,
        {
          ref,
          icon,
          className: clsx_default(style_default4.icon, className),
          size: 24,
          ...props
        }
      );
    }
  );

  // packages/ui/build-module/button/index.mjs
  ButtonIcon.displayName = "Button.Icon";
  var Button5 = Object.assign(Button4, {
    /**
     * An icon component specifically designed to work well when rendered inside
     * a `Button` component.
     */
    Icon: ButtonIcon
  });

  // 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_element19 = __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("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) {
    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 Root = (0, import_element19.forwardRef)(function Card({ render: render5, ...restProps }, ref) {
    const mergedClassName = clsx_default(style_default5.root, resets_default2["box-sizing"]);
    const element = useRender({
      defaultTagName: "div",
      render: render5,
      ref,
      props: mergeProps({ className: mergedClassName }, restProps)
    });
    return element;
  });

  // packages/ui/build-module/card/header.mjs
  var import_element20 = __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 Header = (0, import_element20.forwardRef)(
    function CardHeader({ render: render5, ...props }, ref) {
      const element = useRender({
        defaultTagName: "div",
        render: render5,
        ref,
        props: mergeProps({ className: style_default6.header }, props)
      });
      return element;
    }
  );

  // packages/ui/build-module/card/content.mjs
  var import_element21 = __toESM(require_element(), 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("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_default7 = { "root": "_02872bf298eadc43__root", "header": "bbccc92e6ba5662d__header", "content": "_5dffdaf2a6e669ac__content", "fullbleed": "c1fa192587e1b4a6__fullbleed" };
  var Content = (0, import_element21.forwardRef)(
    function CardContent({ render: render5, ...props }, ref) {
      const element = useRender({
        defaultTagName: "div",
        render: render5,
        ref,
        props: mergeProps({ className: style_default7.content }, props)
      });
      return element;
    }
  );

  // packages/ui/build-module/card/full-bleed.mjs
  var import_element22 = __toESM(require_element(), 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("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_default8 = { "root": "_02872bf298eadc43__root", "header": "bbccc92e6ba5662d__header", "content": "_5dffdaf2a6e669ac__content", "fullbleed": "c1fa192587e1b4a6__fullbleed" };
  var FullBleed = (0, import_element22.forwardRef)(
    function CardFullBleed({ render: render5, ...props }, ref) {
      const element = useRender({
        defaultTagName: "div",
        render: render5,
        ref,
        props: mergeProps(
          { className: style_default8.fullbleed },
          props
        )
      });
      return element;
    }
  );

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

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

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

  // packages/ui/build-module/collapsible/trigger.mjs
  var import_element26 = __toESM(require_element(), 1);
  var import_jsx_runtime120 = __toESM(require_jsx_runtime(), 1);
  var Trigger = (0, import_element26.forwardRef)(
    function CollapsibleTrigger3(props, forwardedRef) {
      return /* @__PURE__ */ (0, import_jsx_runtime120.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_element27 = __toESM(require_element(), 1);
  var import_jsx_runtime121 = __toESM(require_jsx_runtime(), 1);
  var Root3 = (0, import_element27.forwardRef)(
    function CollapsibleCardRoot({ render: render5, ...restProps }, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(
        Root2,
        {
          ref,
          render: /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(Root, { render: render5 }),
          ...restProps
        }
      );
    }
  );

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

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

  // packages/ui/build-module/collapsible-card/header.mjs
  var import_jsx_runtime122 = __toESM(require_jsx_runtime(), 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("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_default9 = { "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) {
    registerStyle9("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_default3 = { "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) {
    registerStyle9("da99a163ac", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._08e8a2e44959f892__outset-ring--focus:focus,.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,: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))}._970d04df7376df67__outset-ring--focus-within-except-active:focus-within,.e25b2bdd7aa21721__outset-ring--focus-except-active:focus{outline:none}._970d04df7376df67__outset-ring--focus-within-except-active:focus-within:not(:has(:active)),.e25b2bdd7aa21721__outset-ring--focus-except-active:focus:not(:active){@include mixins.focus-ring()}}}");
  }
  var focus_default2 = { "outset-ring--focus": "_08e8a2e44959f892__outset-ring--focus", "outset-ring--focus-visible": "d0541bc9dd9dc7b6__outset-ring--focus-visible", "outset-ring--focus-within": "cd83dfc2126a0846__outset-ring--focus-within", "outset-ring--focus-within-visible": "c5cb3ee4bddaa8e4__outset-ring--focus-within-visible", "outset-ring--focus-parent-visible": "ecadb9e080e2dfa5__outset-ring--focus-parent-visible", "outset-ring--focus-except-active": "e25b2bdd7aa21721__outset-ring--focus-except-active", "outset-ring--focus-within-except-active": "_970d04df7376df67__outset-ring--focus-within-except-active" };
  var Header2 = (0, import_element29.forwardRef)(
    function CollapsibleCardHeader({ children, className, render: render5, ...restProps }, ref) {
      const [descriptionId, setDescriptionId] = (0, import_element29.useState)();
      const contextValue = (0, import_element29.useMemo)(
        () => ({ setDescriptionId }),
        [setDescriptionId]
      );
      return useRender({
        defaultTagName: "div",
        render: render5,
        ref,
        props: mergeProps(restProps, {
          className: clsx_default(
            global_css_defense_default3.heading,
            style_default9["heading-wrapper"],
            className
          ),
          children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(HeaderDescriptionIdContext.Provider, { value: contextValue, children: /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(
            Trigger,
            {
              className: style_default9.header,
              render: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Header, {}),
              nativeButton: false,
              "aria-describedby": descriptionId,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime122.jsx)("div", { className: style_default9["header-content"], children }),
                /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(
                  "div",
                  {
                    className: clsx_default(
                      style_default9["header-trigger-positioner"]
                    ),
                    children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(
                      "div",
                      {
                        className: clsx_default(
                          style_default9["header-trigger-wrapper"],
                          global_css_defense_default3.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_default2["outset-ring--focus-parent-visible"]
                        ),
                        children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(
                          Icon,
                          {
                            icon: chevron_down_default,
                            className: style_default9["header-trigger"]
                          }
                        )
                      }
                    )
                  }
                )
              ]
            }
          ) })
        })
      });
    }
  );

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

  // packages/ui/build-module/collapsible-card/content.mjs
  var import_element31 = __toESM(require_element(), 1);
  var import_jsx_runtime124 = __toESM(require_jsx_runtime(), 1);
  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("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_default10 = { "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_element31.forwardRef)(
    function CollapsibleCardContent({ className, render: render5, children, hiddenUntilFound = true, ...restProps }, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
        Panel,
        {
          ref,
          className: (state2) => clsx_default(
            style_default10.content,
            state2.open && state2.transitionStatus === "idle" && style_default10["overflow-visible"],
            className
          ),
          hiddenUntilFound,
          ...restProps,
          children: /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
            Content,
            {
              className: style_default10["content-inner"],
              render: render5,
              children
            }
          )
        }
      );
    }
  );

  // packages/ui/build-module/utils/render-slot-with-children.mjs
  var import_element32 = __toESM(require_element(), 1);
  function renderSlotWithChildren(slot, defaultSlot, children) {
    return (0, import_element32.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_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/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 unlock4(
      themePackage.privateApis
    ).ThemeProvider;
  }
  var ThemeProvider = getThemeProvider();

  // packages/ui/build-module/stack/stack.mjs
  var import_element33 = __toESM(require_element(), 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("32aba35fe1", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._19ce0419607e1896__stack{display:flex}}}");
  }
  var style_default11 = { "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_element33.forwardRef)(function Stack2({ direction, gap, align, justify, wrap, render: render5, ...props }, ref) {
    const style = {
      gap: gap && gapTokens[gap],
      alignItems: align,
      justifyContent: justify,
      flexDirection: direction,
      flexWrap: wrap
    };
    const element = useRender({
      render: render5,
      ref,
      props: mergeProps(props, { style, className: style_default11.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_element36 = __toESM(require_element(), 1);

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

  // packages/ui/build-module/utils/wp-compat-overlay-slot.mjs
  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("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_runtime125 = __toESM(require_jsx_runtime(), 1);
  var Portal = (0, import_element34.forwardRef)(
    function TooltipPortal3({ container, ...restProps }, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
        index_parts_exports3.Portal,
        {
          container: container ?? getWpCompatOverlaySlot(),
          ...restProps,
          ref
        }
      );
    }
  );

  // packages/ui/build-module/tooltip/positioner.mjs
  var import_element35 = __toESM(require_element(), 1);
  var import_jsx_runtime126 = __toESM(require_jsx_runtime(), 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("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) {
    registerStyle13("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_default12 = { "positioner": "_480b748dd3510e64__positioner", "popup": "_50096b232db7709d__popup" };
  var Positioner = (0, import_element35.forwardRef)(
    function TooltipPositioner3({ align = "center", className, side = "top", sideOffset = 4, ...props }, ref) {
      return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
        index_parts_exports3.Positioner,
        {
          ref,
          align,
          side,
          sideOffset,
          ...props,
          className: clsx_default(
            resets_default3["box-sizing"],
            style_default12.positioner,
            className
          )
        }
      );
    }
  );

  // packages/ui/build-module/tooltip/popup.mjs
  var import_jsx_runtime127 = __toESM(require_jsx_runtime(), 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("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_default13 = { "positioner": "_480b748dd3510e64__positioner", "popup": "_50096b232db7709d__popup" };
  var POPUP_COLOR = { background: "#1e1e1e" };
  var Popup = (0, import_element36.forwardRef)(function TooltipPopup3({ portal, positioner, children, className, ...props }, ref) {
    const popupContent = /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(ThemeProvider, { color: POPUP_COLOR, children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(
      index_parts_exports3.Popup,
      {
        ref,
        className: clsx_default(style_default13.popup, className),
        ...props,
        children
      }
    ) });
    const positionedPopup = renderSlotWithChildren(
      positioner,
      /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Positioner, {}),
      popupContent
    );
    return renderSlotWithChildren(portal, /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Portal, {}), positionedPopup);
  });

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

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

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

  // packages/ui/build-module/utils/use-schedule-validation.mjs
  var import_element38 = __toESM(require_element(), 1);
  function useScheduleValidation(validate) {
    const validateRef = (0, import_element38.useRef)(validate);
    validateRef.current = validate;
    const timerRef = (0, import_element38.useRef)(null);
    const unmountedRef = (0, import_element38.useRef)(false);
    const scheduleValidation = (0, import_element38.useCallback)(() => {
      if (unmountedRef.current) {
        return;
      }
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
      timerRef.current = setTimeout(() => {
        validateRef.current();
        timerRef.current = null;
      }, 0);
    }, []);
    (0, import_element38.useEffect)(() => {
      unmountedRef.current = false;
      return () => {
        unmountedRef.current = true;
        if (timerRef.current) {
          clearTimeout(timerRef.current);
        }
      };
    }, []);
    return scheduleValidation;
  }

  // packages/ui/build-module/visually-hidden/visually-hidden.mjs
  var import_element39 = __toESM(require_element(), 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("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_default14 = { "visually-hidden": "f37b9e2e191ebd66__visually-hidden" };
  var VisuallyHidden = (0, import_element39.forwardRef)(
    function VisuallyHidden2({ render: render5, ...restProps }, ref) {
      const element = useRender({
        render: render5,
        ref,
        props: mergeProps(
          { className: style_default14["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/link/link.mjs
  var import_element40 = __toESM(require_element(), 1);
  var import_i18n12 = __toESM(require_i18n(), 1);
  var import_jsx_runtime131 = __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("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_default4 = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
  if (typeof process === "undefined" || true) {
    registerStyle16("da99a163ac", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._08e8a2e44959f892__outset-ring--focus:focus,.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,: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))}._970d04df7376df67__outset-ring--focus-within-except-active:focus-within,.e25b2bdd7aa21721__outset-ring--focus-except-active:focus{outline:none}._970d04df7376df67__outset-ring--focus-within-except-active:focus-within:not(:has(:active)),.e25b2bdd7aa21721__outset-ring--focus-except-active:focus:not(:active){@include mixins.focus-ring()}}}");
  }
  var focus_default3 = { "outset-ring--focus": "_08e8a2e44959f892__outset-ring--focus", "outset-ring--focus-visible": "d0541bc9dd9dc7b6__outset-ring--focus-visible", "outset-ring--focus-within": "cd83dfc2126a0846__outset-ring--focus-within", "outset-ring--focus-within-visible": "c5cb3ee4bddaa8e4__outset-ring--focus-within-visible", "outset-ring--focus-parent-visible": "ecadb9e080e2dfa5__outset-ring--focus-parent-visible", "outset-ring--focus-except-active": "e25b2bdd7aa21721__outset-ring--focus-except-active", "outset-ring--focus-within-except-active": "_970d04df7376df67__outset-ring--focus-within-except-active" };
  if (typeof process === "undefined" || true) {
    registerStyle16("e8e6a9be37", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{.d4250949359b05ce__link{text-decoration-thickness:from-font;text-underline-offset:.2em}.c6055659b8e2cd2c__is-brand,.c6055659b8e2cd2c__is-brand:visited{--_gcd-a-color:var(--wpds-color-foreground-interactive-brand,var(--wp-admin-theme-color,#3858e9));color:var(--wpds-color-foreground-interactive-brand,var(--wp-admin-theme-color,#3858e9))}.c6055659b8e2cd2c__is-brand:active,.c6055659b8e2cd2c__is-brand:hover{--_gcd-a-color:var(--wpds-color-foreground-interactive-brand-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 52%,#000));color:var(--wpds-color-foreground-interactive-brand-active,color-mix(in oklch,var(--wp-admin-theme-color,#3858e9) 52%,#000))}._92e0dfcaeee15b88__is-neutral,._92e0dfcaeee15b88__is-neutral:visited{--_gcd-a-color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);text-decoration-color:var(--wpds-color-stroke-interactive-neutral,#8d8d8d)}._92e0dfcaeee15b88__is-neutral:active,._92e0dfcaeee15b88__is-neutral:hover{--_gcd-a-color:var(--wpds-color-foreground-interactive-neutral-active,#1e1e1e);color:var(--wpds-color-foreground-interactive-neutral-active,#1e1e1e)}.cf122a9bf1035d42__is-unstyled{--_gcd-a-color:inherit;color:inherit;text-decoration:none}._0cb411afac4c86c7__link-icon{display:inline-block;font-weight:var(--wpds-typography-font-weight-default,400);line-height:1;margin-inline-start:var(--wpds-dimension-padding-xs,4px);text-decoration:none}._0cb411afac4c86c7__link-icon:after{content:"\\2197"}._0cb411afac4c86c7__link-icon:dir(rtl):after{content:"\\2196"}}}');
  }
  var style_default15 = { "link": "d4250949359b05ce__link", "is-brand": "c6055659b8e2cd2c__is-brand", "is-neutral": "_92e0dfcaeee15b88__is-neutral", "is-unstyled": "cf122a9bf1035d42__is-unstyled", "link-icon": "_0cb411afac4c86c7__link-icon" };
  if (typeof process === "undefined" || true) {
    registerStyle16("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_default4 = { "button": "_6defc79820e382c6__button", "input": "d2cff2e5dea83bd1__input", "textarea": "_547d86373d02e108__textarea", "div": "_8c15fd0ed9f28ba4__div", "p": "_43cec3e1eec1066d__p", "heading": "e97669c6d9a38497__heading", "a": "_2c0831b0499dbd6e__a" };
  var Link = (0, import_element40.forwardRef)(function Link2({
    children,
    variant = "default",
    tone = "brand",
    openInNewTab = false,
    render: render5,
    className,
    ...props
  }, ref) {
    const element = useRender({
      render: render5,
      defaultTagName: "a",
      ref,
      props: mergeProps(props, {
        className: clsx_default(
          global_css_defense_default4.a,
          resets_default4["box-sizing"],
          focus_default3["outset-ring--focus-except-active"],
          variant !== "unstyled" && style_default15.link,
          variant !== "unstyled" && style_default15[`is-${tone}`],
          variant === "unstyled" && style_default15["is-unstyled"],
          className
        ),
        target: openInNewTab ? "_blank" : void 0,
        children: /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(import_jsx_runtime131.Fragment, { children: [
          children,
          openInNewTab && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(
            "span",
            {
              className: style_default15["link-icon"],
              role: "img",
              "aria-label": (
                /* translators: accessibility text appended to link text */
                (0, import_i18n12.__)("(opens in a new tab)")
              )
            }
          )
        ] })
      })
    });
    return element;
  });

  // packages/ui/build-module/skeleton/skeleton.mjs
  var import_element41 = __toESM(require_element(), 1);
  var STYLE_HASH_ATTRIBUTE17 = "data-wp-hash";
  function getRuntime17() {
    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") {
      registerDocument17(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash17(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE17}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE17) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle17(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime17();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash17(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE17, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument17(targetDocument) {
    const runtime = getRuntime17();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle17(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 registerStyle17(hash, css) {
    const runtime = getRuntime17();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle17(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle17("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_default5 = { "box-sizing": "_336cd3e4e743482f__box-sizing" };
  if (typeof process === "undefined" || true) {
    registerStyle17("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_default16 = { "skeleton": "b20cc1690085c2f0__skeleton", "pulse": "_9b143194fdb45f93__pulse", "skeleton-pulse": "e2b9fe0690281bc8__skeleton-pulse" };
  var Skeleton = (0, import_element41.forwardRef)(
    function Skeleton2({ render: render5, ...props }, ref) {
      return useRender({
        render: render5,
        ref,
        props: mergeProps(
          {
            className: clsx_default(
              style_default16.skeleton,
              style_default16.pulse,
              resets_default5["box-sizing"]
            ),
            // Decorative by default; consumers mark the loading
            // region with aria-busy / role="status".
            "aria-hidden": true
          },
          props
        )
      });
    }
  );

  // packages/ui/build-module/tabs/index.mjs
  var tabs_exports = {};
  __export(tabs_exports, {
    List: () => List,
    Panel: () => Panel2,
    Root: () => Root5,
    Tab: () => Tab
  });

  // packages/ui/build-module/tabs/list.mjs
  var import_element42 = __toESM(require_element(), 1);
  var import_compose2 = __toESM(require_compose(), 1);
  var import_jsx_runtime132 = __toESM(require_jsx_runtime(), 1);
  var STYLE_HASH_ATTRIBUTE18 = "data-wp-hash";
  function getRuntime18() {
    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") {
      registerDocument18(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash18(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE18}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE18) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle18(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime18();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash18(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE18, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument18(targetDocument) {
    const runtime = getRuntime18();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle18(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 registerStyle18(hash, css) {
    const runtime = getRuntime18();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle18(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle18("bb8cbb8f31", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._7313adbc8a112e90__tablist{--direction-factor:1;--direction-start:left;--direction-end:right;align-items:stretch;display:flex;overflow-inline:auto;overscroll-behavior-inline:none;position:relative;&:dir(rtl){--direction-factor:-1;--direction-start:right;--direction-end:left}&[data-orientation=horizontal]{--fade-width:4rem;--fade-gradient-base:transparent 0%,#000 var(--fade-width);--fade-gradient-composed:var(--fade-gradient-base),#000 60%,transparent 50%;width:fit-content;&._9f2ac729c68a735a__is-overflowing-first{mask-image:linear-gradient(to var(--direction-end),var(--fade-gradient-base))}&._81c799c1f3cdd261__is-overflowing-last{mask-image:linear-gradient(to var(--direction-start),var(--fade-gradient-base))}&._9f2ac729c68a735a__is-overflowing-first._81c799c1f3cdd261__is-overflowing-last{mask-image:linear-gradient(to right,var(--fade-gradient-composed)),linear-gradient(to left,var(--fade-gradient-composed))}&._59228b5227f38a99__is-minimal-variant{gap:1rem}}&[data-orientation=vertical]{flex-direction:column}}._1c37dcfaa1ad8cda__indicator{@media not (prefers-reduced-motion){transition-duration:.2s;transition-property:translate,width,height,border-radius,border-block;transition-timing-function:ease-out}outline:2px solid transparent;outline-offset:-1px;pointer-events:none;position:absolute;&[data-orientation=horizontal]{background-color:var(--wpds-color-stroke-interactive-neutral-strong,#6e6e6e);bottom:0;height:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px));left:0;translate:var(--active-tab-left) 0;width:var(--active-tab-width);z-index:1}&[data-orientation=vertical]{background-color:var(--wpds-color-background-interactive-neutral-weak-active,#ededed);border-radius:var(--wpds-border-radius-sm,2px);height:var(--active-tab-height);left:50%;top:0;translate:-50% var(--active-tab-top);width:100%;z-index:0}._7313adbc8a112e90__tablist[data-select-on-move=true]:has(:focus-visible)\n			&[data-orientation=vertical]{border:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));box-sizing:border-box}}.a5fd8814f195aa5e__tab{align-items:center;background:transparent;border:none;border-radius:0;box-shadow:none;color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);cursor:var(--wpds-cursor-control,pointer);display:flex;flex:1 0 auto;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-md,13px);font-weight:400;line-height:1.2;outline:none;padding:0;position:relative;white-space:nowrap;z-index:1;&[data-disabled]{color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d);cursor:default;@media (forced-colors:active){color:GrayText}}&:not([data-disabled]):is(:hover,:focus-visible){color:var(--wpds-color-foreground-interactive-neutral-active,#1e1e1e)}&:after{border-radius:var(--wpds-border-radius-sm,2px);opacity:0;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));pointer-events:none;position:absolute;z-index:-1;@media not (prefers-reduced-motion){transition:opacity .1s linear}}&:focus-visible:after{opacity:1}[data-orientation=horizontal] &{height:48px;padding-inline:var(--wpds-dimension-padding-lg,16px);scroll-margin:24px;&:after{content:"";inset:var(--wpds-dimension-padding-md,12px)}}._59228b5227f38a99__is-minimal-variant[data-orientation=horizontal] &{padding-inline:0;&:after{inset-inline:round(up,var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)),1px)}}[data-orientation=vertical] &{min-height:var(--wpds-dimension-size-lg,40px);padding:var(--wpds-dimension-padding-sm,8px) var(--wpds-dimension-padding-md,12px)}[data-orientation=vertical][data-select-on-move=false] &:after{content:"";inset:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px))}}._5dfc77e6edd345d4__tab-children{align-items:center;display:flex;flex-grow:1;[data-orientation=horizontal] &{justify-content:center}[data-orientation=vertical] &{justify-content:start}}._4a20e969d15e5ac1__tab-chevron{flex-shrink:0;margin-inline-end:calc(var(--wpds-dimension-gap-xs, 4px)*-1);opacity:0;[data-orientation=horizontal] &{display:none}[role=tab]:is([aria-selected=true],:focus-visible,:hover) &{opacity:1}@media not (prefers-reduced-motion){[data-select-on-move=true]\n				[role=tab]:is([aria-selected=true])\n				&{transition:opacity .15s linear .15s}}&:dir(rtl){rotate:180deg}}}}');
  }
  var style_default17 = { "tablist": "_7313adbc8a112e90__tablist", "is-overflowing-first": "_9f2ac729c68a735a__is-overflowing-first", "is-overflowing-last": "_81c799c1f3cdd261__is-overflowing-last", "is-minimal-variant": "_59228b5227f38a99__is-minimal-variant", "indicator": "_1c37dcfaa1ad8cda__indicator", "tab": "a5fd8814f195aa5e__tab", "tab-children": "_5dfc77e6edd345d4__tab-children", "tab-chevron": "_4a20e969d15e5ac1__tab-chevron" };
  var SCROLL_EPSILON = 1;
  var List = (0, import_element42.forwardRef)(
    function TabList({
      children,
      variant = "default",
      className,
      activateOnFocus,
      ...otherProps
    }, forwardedRef) {
      const [listEl, setListEl] = (0, import_element42.useState)(null);
      const [overflow, setOverflow] = (0, import_element42.useState)({
        first: false,
        last: false,
        isScrolling: false
      });
      (0, import_element42.useEffect)(() => {
        if (!listEl) {
          return;
        }
        const measureOverflow = () => {
          const { scrollWidth, clientWidth, scrollLeft } = listEl;
          const maxScroll = Math.max(scrollWidth - clientWidth, 0);
          const direction = listEl.dir || (typeof window !== "undefined" ? window.getComputedStyle(listEl).direction : "ltr");
          const scrollFromStart = direction === "rtl" && scrollLeft < 0 ? (
            // In RTL layouts, scrollLeft is typically 0 at the visual "start"
            // (right edge) and becomes negative toward the "end" (left edge).
            // Normalize value for correct first/last detection logic.
            -scrollLeft
          ) : scrollLeft;
          const next = {
            first: scrollFromStart > SCROLL_EPSILON,
            last: scrollFromStart < maxScroll - SCROLL_EPSILON,
            isScrolling: scrollWidth > clientWidth
          };
          setOverflow(
            (prev) => prev.first === next.first && prev.last === next.last && prev.isScrolling === next.isScrolling ? prev : next
          );
        };
        const resizeObserver = new ResizeObserver(measureOverflow);
        const observeTabs = () => {
          resizeObserver.disconnect();
          resizeObserver.observe(listEl);
          listEl.querySelectorAll('[role="tab"]').forEach((tab) => resizeObserver.observe(tab));
        };
        const mutationObserver = new MutationObserver(observeTabs);
        mutationObserver.observe(listEl, {
          childList: true,
          subtree: true
        });
        let scrollTick = false;
        const throttleMeasureOverflowOnScroll = () => {
          if (!scrollTick) {
            requestAnimationFrame(() => {
              measureOverflow();
              scrollTick = false;
            });
            scrollTick = true;
          }
        };
        listEl.addEventListener(
          "scroll",
          throttleMeasureOverflowOnScroll,
          { passive: true }
        );
        observeTabs();
        measureOverflow();
        return () => {
          listEl.removeEventListener(
            "scroll",
            throttleMeasureOverflowOnScroll
          );
          resizeObserver.disconnect();
          mutationObserver.disconnect();
        };
      }, [listEl]);
      const mergedListRef = (0, import_compose2.useMergeRefs)([
        forwardedRef,
        (el) => setListEl(el)
      ]);
      return /* @__PURE__ */ (0, import_jsx_runtime132.jsxs)(
        index_parts_exports2.List,
        {
          ref: mergedListRef,
          activateOnFocus,
          "data-select-on-move": activateOnFocus ? "true" : "false",
          className: clsx_default(
            style_default17.tablist,
            overflow.first && style_default17["is-overflowing-first"],
            overflow.last && style_default17["is-overflowing-last"],
            style_default17[`is-${variant}-variant`],
            className
          ),
          ...otherProps,
          tabIndex: otherProps.tabIndex ?? (overflow.isScrolling ? -1 : void 0),
          children: [
            children,
            /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(index_parts_exports2.Indicator, { className: style_default17.indicator })
          ]
        }
      );
    }
  );

  // packages/ui/build-module/tabs/panel.mjs
  var import_element44 = __toESM(require_element(), 1);

  // packages/ui/build-module/tabs/context.mjs
  var import_element43 = __toESM(require_element(), 1);
  var import_jsx_runtime133 = __toESM(require_jsx_runtime(), 1);
  var VALIDATION_ENABLED = true;
  var TabsValidationContext = VALIDATION_ENABLED ? (0, import_element43.createContext)(null) : null;
  function useRegisterTabDev() {
    const context = (0, import_element43.useContext)(TabsValidationContext);
    (0, import_element43.useEffect)(() => {
      if (context) {
        return context.registerTab();
      }
      return void 0;
    }, [context]);
  }
  function useRegisterTabProd() {
  }
  var useRegisterTab = VALIDATION_ENABLED ? useRegisterTabDev : useRegisterTabProd;
  function useRegisterPanelDev() {
    const context = (0, import_element43.useContext)(TabsValidationContext);
    (0, import_element43.useEffect)(() => {
      if (context) {
        return context.registerPanel();
      }
      return void 0;
    }, [context]);
  }
  function useRegisterPanelProd() {
  }
  var useRegisterPanel = VALIDATION_ENABLED ? useRegisterPanelDev : useRegisterPanelProd;
  function TabsValidationProviderDev({
    children
  }) {
    const tabCountRef = (0, import_element43.useRef)(0);
    const panelCountRef = (0, import_element43.useRef)(0);
    const scheduleValidation = useScheduleValidation(() => {
      const tabCount = tabCountRef.current;
      const panelCount = panelCountRef.current;
      if (tabCount !== panelCount) {
        throw new Error(
          `Tabs: Tab/Panel count mismatch (${tabCount} Tabs, ${panelCount} Panels). Each Tab must be associated with exactly one Panel. Mismatched or missing associations can break screen reader navigation and violate WAI-ARIA Tabs pattern requirements.`
        );
      }
    });
    const registerTab = (0, import_element43.useCallback)(() => {
      tabCountRef.current += 1;
      scheduleValidation();
      return () => {
        tabCountRef.current -= 1;
        scheduleValidation();
      };
    }, [scheduleValidation]);
    const registerPanel = (0, import_element43.useCallback)(() => {
      panelCountRef.current += 1;
      scheduleValidation();
      return () => {
        panelCountRef.current -= 1;
        scheduleValidation();
      };
    }, [scheduleValidation]);
    const contextValue = (0, import_element43.useMemo)(
      () => ({
        registerTab,
        registerPanel
      }),
      [registerTab, registerPanel]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime133.jsx)(TabsValidationContext.Provider, { value: contextValue, children });
  }
  function TabsValidationProviderProd({
    children
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime133.jsx)(import_jsx_runtime133.Fragment, { children });
  }
  var TabsValidationProvider = VALIDATION_ENABLED ? TabsValidationProviderDev : TabsValidationProviderProd;

  // packages/ui/build-module/tabs/panel.mjs
  var import_jsx_runtime134 = __toESM(require_jsx_runtime(), 1);
  var STYLE_HASH_ATTRIBUTE19 = "data-wp-hash";
  function getRuntime19() {
    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") {
      registerDocument19(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash19(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE19}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE19) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle19(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime19();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash19(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE19, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument19(targetDocument) {
    const runtime = getRuntime19();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle19(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 registerStyle19(hash, css) {
    const runtime = getRuntime19();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle19(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle19("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_default5 = { "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) {
    registerStyle19("da99a163ac", "@layer wp-ui{@layer utilities, components, compositions, overrides;@layer utilities{._08e8a2e44959f892__outset-ring--focus:focus,.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,: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))}._970d04df7376df67__outset-ring--focus-within-except-active:focus-within,.e25b2bdd7aa21721__outset-ring--focus-except-active:focus{outline:none}._970d04df7376df67__outset-ring--focus-within-except-active:focus-within:not(:has(:active)),.e25b2bdd7aa21721__outset-ring--focus-except-active:focus:not(:active){@include mixins.focus-ring()}}}");
  }
  var focus_default4 = { "outset-ring--focus": "_08e8a2e44959f892__outset-ring--focus", "outset-ring--focus-visible": "d0541bc9dd9dc7b6__outset-ring--focus-visible", "outset-ring--focus-within": "cd83dfc2126a0846__outset-ring--focus-within", "outset-ring--focus-within-visible": "c5cb3ee4bddaa8e4__outset-ring--focus-within-visible", "outset-ring--focus-parent-visible": "ecadb9e080e2dfa5__outset-ring--focus-parent-visible", "outset-ring--focus-except-active": "e25b2bdd7aa21721__outset-ring--focus-except-active", "outset-ring--focus-within-except-active": "_970d04df7376df67__outset-ring--focus-within-except-active" };
  var Panel2 = (0, import_element44.forwardRef)(
    function TabPanel({ className, ...otherProps }, forwardedRef) {
      useRegisterPanel();
      return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
        index_parts_exports2.Panel,
        {
          ref: forwardedRef,
          className: clsx_default(
            global_css_defense_default5.div,
            focus_default4["outset-ring--focus-visible"],
            className
          ),
          ...otherProps
        }
      );
    }
  );

  // packages/ui/build-module/tabs/root.mjs
  var import_element45 = __toESM(require_element(), 1);
  var import_jsx_runtime135 = __toESM(require_jsx_runtime(), 1);
  var Root5 = (0, import_element45.forwardRef)(
    function TabsRoot3({ ...otherProps }, forwardedRef) {
      return /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(TabsValidationProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(index_parts_exports2.Root, { ref: forwardedRef, ...otherProps }) });
    }
  );

  // packages/ui/build-module/tabs/tab.mjs
  var import_element46 = __toESM(require_element(), 1);
  var import_jsx_runtime136 = __toESM(require_jsx_runtime(), 1);
  var STYLE_HASH_ATTRIBUTE20 = "data-wp-hash";
  function getRuntime20() {
    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") {
      registerDocument20(document);
    }
    return globalScope.__wpStyleRuntime;
  }
  function documentContainsStyleHash20(targetDocument, hash) {
    if (!targetDocument.head) {
      return false;
    }
    for (const style of targetDocument.head.querySelectorAll(
      `style[${STYLE_HASH_ATTRIBUTE20}]`
    )) {
      if (style.getAttribute(STYLE_HASH_ATTRIBUTE20) === hash) {
        return true;
      }
    }
    return false;
  }
  function injectStyle20(targetDocument, hash, css) {
    if (!targetDocument.head) {
      return;
    }
    const runtime = getRuntime20();
    let injectedStyles = runtime.injectedStyles.get(targetDocument);
    if (!injectedStyles) {
      injectedStyles = /* @__PURE__ */ new Set();
      runtime.injectedStyles.set(targetDocument, injectedStyles);
    }
    if (injectedStyles.has(hash)) {
      return;
    }
    if (documentContainsStyleHash20(targetDocument, hash)) {
      injectedStyles.add(hash);
      return;
    }
    const style = targetDocument.createElement("style");
    style.setAttribute(STYLE_HASH_ATTRIBUTE20, hash);
    style.appendChild(targetDocument.createTextNode(css));
    targetDocument.head.appendChild(style);
    injectedStyles.add(hash);
  }
  function registerDocument20(targetDocument) {
    const runtime = getRuntime20();
    runtime.documents.set(
      targetDocument,
      (runtime.documents.get(targetDocument) ?? 0) + 1
    );
    for (const [hash, css] of runtime.styles) {
      injectStyle20(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 registerStyle20(hash, css) {
    const runtime = getRuntime20();
    runtime.styles.set(hash, css);
    for (const targetDocument of runtime.documents.keys()) {
      injectStyle20(targetDocument, hash, css);
    }
  }
  if (typeof process === "undefined" || true) {
    registerStyle20("bb8cbb8f31", '@layer wp-ui{@layer utilities, components, compositions, overrides;@layer components{._7313adbc8a112e90__tablist{--direction-factor:1;--direction-start:left;--direction-end:right;align-items:stretch;display:flex;overflow-inline:auto;overscroll-behavior-inline:none;position:relative;&:dir(rtl){--direction-factor:-1;--direction-start:right;--direction-end:left}&[data-orientation=horizontal]{--fade-width:4rem;--fade-gradient-base:transparent 0%,#000 var(--fade-width);--fade-gradient-composed:var(--fade-gradient-base),#000 60%,transparent 50%;width:fit-content;&._9f2ac729c68a735a__is-overflowing-first{mask-image:linear-gradient(to var(--direction-end),var(--fade-gradient-base))}&._81c799c1f3cdd261__is-overflowing-last{mask-image:linear-gradient(to var(--direction-start),var(--fade-gradient-base))}&._9f2ac729c68a735a__is-overflowing-first._81c799c1f3cdd261__is-overflowing-last{mask-image:linear-gradient(to right,var(--fade-gradient-composed)),linear-gradient(to left,var(--fade-gradient-composed))}&._59228b5227f38a99__is-minimal-variant{gap:1rem}}&[data-orientation=vertical]{flex-direction:column}}._1c37dcfaa1ad8cda__indicator{@media not (prefers-reduced-motion){transition-duration:.2s;transition-property:translate,width,height,border-radius,border-block;transition-timing-function:ease-out}outline:2px solid transparent;outline-offset:-1px;pointer-events:none;position:absolute;&[data-orientation=horizontal]{background-color:var(--wpds-color-stroke-interactive-neutral-strong,#6e6e6e);bottom:0;height:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px));left:0;translate:var(--active-tab-left) 0;width:var(--active-tab-width);z-index:1}&[data-orientation=vertical]{background-color:var(--wpds-color-background-interactive-neutral-weak-active,#ededed);border-radius:var(--wpds-border-radius-sm,2px);height:var(--active-tab-height);left:50%;top:0;translate:-50% var(--active-tab-top);width:100%;z-index:0}._7313adbc8a112e90__tablist[data-select-on-move=true]:has(:focus-visible)\n			&[data-orientation=vertical]{border:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9));box-sizing:border-box}}.a5fd8814f195aa5e__tab{align-items:center;background:transparent;border:none;border-radius:0;box-shadow:none;color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);cursor:var(--wpds-cursor-control,pointer);display:flex;flex:1 0 auto;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-md,13px);font-weight:400;line-height:1.2;outline:none;padding:0;position:relative;white-space:nowrap;z-index:1;&[data-disabled]{color:var(--wpds-color-foreground-interactive-neutral-disabled,#8d8d8d);cursor:default;@media (forced-colors:active){color:GrayText}}&:not([data-disabled]):is(:hover,:focus-visible){color:var(--wpds-color-foreground-interactive-neutral-active,#1e1e1e)}&:after{border-radius:var(--wpds-border-radius-sm,2px);opacity:0;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));pointer-events:none;position:absolute;z-index:-1;@media not (prefers-reduced-motion){transition:opacity .1s linear}}&:focus-visible:after{opacity:1}[data-orientation=horizontal] &{height:48px;padding-inline:var(--wpds-dimension-padding-lg,16px);scroll-margin:24px;&:after{content:"";inset:var(--wpds-dimension-padding-md,12px)}}._59228b5227f38a99__is-minimal-variant[data-orientation=horizontal] &{padding-inline:0;&:after{inset-inline:round(up,var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)),1px)}}[data-orientation=vertical] &{min-height:var(--wpds-dimension-size-lg,40px);padding:var(--wpds-dimension-padding-sm,8px) var(--wpds-dimension-padding-md,12px)}[data-orientation=vertical][data-select-on-move=false] &:after{content:"";inset:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px))}}._5dfc77e6edd345d4__tab-children{align-items:center;display:flex;flex-grow:1;[data-orientation=horizontal] &{justify-content:center}[data-orientation=vertical] &{justify-content:start}}._4a20e969d15e5ac1__tab-chevron{flex-shrink:0;margin-inline-end:calc(var(--wpds-dimension-gap-xs, 4px)*-1);opacity:0;[data-orientation=horizontal] &{display:none}[role=tab]:is([aria-selected=true],:focus-visible,:hover) &{opacity:1}@media not (prefers-reduced-motion){[data-select-on-move=true]\n				[role=tab]:is([aria-selected=true])\n				&{transition:opacity .15s linear .15s}}&:dir(rtl){rotate:180deg}}}}');
  }
  var style_default18 = { "tablist": "_7313adbc8a112e90__tablist", "is-overflowing-first": "_9f2ac729c68a735a__is-overflowing-first", "is-overflowing-last": "_81c799c1f3cdd261__is-overflowing-last", "is-minimal-variant": "_59228b5227f38a99__is-minimal-variant", "indicator": "_1c37dcfaa1ad8cda__indicator", "tab": "a5fd8814f195aa5e__tab", "tab-children": "_5dfc77e6edd345d4__tab-children", "tab-chevron": "_4a20e969d15e5ac1__tab-chevron" };
  var Tab = (0, import_element46.forwardRef)(function Tab2({ className, children, ...otherProps }, forwardedRef) {
    useRegisterTab();
    return /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(
      index_parts_exports2.Tab,
      {
        ref: forwardedRef,
        className: clsx_default(style_default18.tab, className),
        ...otherProps,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime136.jsx)("span", { className: style_default18["tab-children"], children }),
          /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Icon, { icon: chevron_right_default, className: style_default18["tab-chevron"] })
        ]
      }
    );
  });

  // packages/fields/build-module/fields/pattern-title/view.mjs
  var import_jsx_runtime137 = __toESM(require_jsx_runtime(), 1);
  var { PATTERN_TYPES } = unlock3(import_patterns.privateApis);
  function PatternTitleView({ item }) {
    const lockMessage = (0, import_i18n13.__)("This pattern cannot be edited.");
    return /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(BaseTitleView, { item, className: "fields-field__pattern-title", children: item.type === PATTERN_TYPES.theme && /* @__PURE__ */ (0, import_jsx_runtime137.jsxs)(import_jsx_runtime137.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(VisuallyHidden, { children: lockMessage }),
      /* @__PURE__ */ (0, import_jsx_runtime137.jsxs)(tooltip_exports.Root, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(
          tooltip_exports.Trigger,
          {
            render: /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(icon_default, { icon: lock_small_default, size: 24 })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(tooltip_exports.Popup, { children: lockMessage })
      ] })
    ] }) });
  }

  // packages/fields/build-module/fields/pattern-title/index.mjs
  var patternTitleField = {
    type: "text",
    id: "title",
    label: (0, import_i18n14.__)("Title"),
    placeholder: (0, import_i18n14.__)("No title"),
    getValue: ({ item }) => getItemTitle(item),
    render: PatternTitleView,
    enableHiding: false,
    enableGlobalSearch: true,
    filterBy: false
  };
  var pattern_title_default = patternTitleField;

  // packages/fields/build-module/fields/pattern-description/index.mjs
  var import_html_entities2 = __toESM(require_html_entities(), 1);
  var import_i18n15 = __toESM(require_i18n(), 1);
  var import_jsx_runtime138 = __toESM(require_jsx_runtime(), 1);
  function getPatternDescription(item) {
    if (typeof item.excerpt === "string") {
      return (0, import_html_entities2.decodeEntities)(item.excerpt);
    }
    return (0, import_html_entities2.decodeEntities)(item.excerpt?.raw || "");
  }
  var patternDescriptionField = {
    id: "excerpt",
    type: "text",
    label: (0, import_i18n15.__)("Description"),
    placeholder: (0, import_i18n15.__)("Add a description"),
    getValue: ({ item }) => getPatternDescription(item),
    render: ({ item }) => {
      const description = getPatternDescription(item);
      return description ? /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(Text, { children: description }) : null;
    },
    Edit: {
      control: "textarea",
      rows: 4
    },
    enableSorting: false,
    enableHiding: false,
    filterBy: false,
    enableGlobalSearch: true
  };
  var pattern_description_default = patternDescriptionField;

  // packages/fields/build-module/fields/pattern-sync-status/index.mjs
  var import_i18n16 = __toESM(require_i18n(), 1);
  var import_patterns2 = __toESM(require_patterns(), 1);
  var import_jsx_runtime139 = __toESM(require_jsx_runtime(), 1);
  var { PATTERN_SYNC_TYPES, PATTERN_TYPES: PATTERN_TYPES2 } = unlock3(import_patterns2.privateApis);
  var SYNC_STATUS_FILTERS = [
    {
      value: PATTERN_SYNC_TYPES.full,
      label: (0, import_i18n16._x)("Synced", "pattern (singular)"),
      description: (0, import_i18n16.__)("Patterns that are kept in sync across the site.")
    },
    {
      value: PATTERN_SYNC_TYPES.unsynced,
      label: (0, import_i18n16._x)("Not synced", "pattern (singular)"),
      description: (0, import_i18n16.__)(
        "Patterns that can be changed freely without affecting the site."
      )
    }
  ];
  function getPatternSyncStatus(item) {
    if (item.type && item.type !== PATTERN_TYPES2.user) {
      return PATTERN_SYNC_TYPES.unsynced;
    }
    if (item.meta?.wp_pattern_sync_status === PATTERN_SYNC_TYPES.unsynced) {
      return PATTERN_SYNC_TYPES.unsynced;
    }
    return item.wp_pattern_sync_status || PATTERN_SYNC_TYPES.full;
  }
  var patternSyncStatusField = {
    id: "sync-status",
    type: "text",
    label: (0, import_i18n16.__)("Sync status"),
    readOnly: true,
    enableSorting: false,
    enableHiding: true,
    elements: SYNC_STATUS_FILTERS,
    filterBy: {
      operators: ["is"],
      isPrimary: true
    },
    render: ({ item }) => {
      const syncStatus = getPatternSyncStatus(item);
      return /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(
        "span",
        {
          className: `fields-field__pattern-sync-status fields-field__pattern-sync-status-${syncStatus}`,
          children: SYNC_STATUS_FILTERS.find(
            ({ value }) => value === syncStatus
          )?.label
        }
      );
    }
  };
  var pattern_sync_status_default = patternSyncStatusField;

  // packages/fields/build-module/fields/featured-image/index.mjs
  var import_i18n18 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/components/media-edit/index.mjs
  var import_components4 = __toESM(require_components(), 1);
  var import_blob = __toESM(require_blob(), 1);
  var import_core_data5 = __toESM(require_core_data(), 1);
  var import_data9 = __toESM(require_data(), 1);
  var import_element48 = __toESM(require_element(), 1);
  var import_i18n17 = __toESM(require_i18n(), 1);
  var import_html_entities3 = __toESM(require_html_entities(), 1);
  var import_a11y2 = __toESM(require_a11y(), 1);
  var import_media_utils2 = __toESM(require_media_utils(), 1);
  var import_notices2 = __toESM(require_notices(), 1);

  // 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 i3 = timeouts.findIndex((t4) => t4.cancel == cancel);
      if (~i3) timeouts.splice(i3, 1);
      pendingCount -= ~i3 ? 1 : 0;
    };
    let timeout = {
      time,
      handler,
      cancel
    };
    timeouts.splice(findTimeout(time), 0, timeout);
    pendingCount += 1;
    start();
    return timeout;
  };
  var findTimeout = (time) => ~(~timeouts.findIndex((t4) => t4.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), (t4) => t4.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 (e3) {
        raf.catch(e3);
      }
    });
  }

  // node_modules/@react-spring/shared/dist/react-spring-shared.esm.js
  var import_react13 = __toESM(require_react());
  function noop5() {
  }
  var defineHidden = (obj, key, value) => Object.defineProperty(obj, key, {
    value,
    writable: true,
    configurable: true
  });
  var is = {
    arr: Array.isArray,
    obj: (a3) => !!a3 && a3.constructor.name === "Object",
    fun: (a3) => typeof a3 === "function",
    str: (a3) => typeof a3 === "string",
    num: (a3) => typeof a3 === "number",
    und: (a3) => a3 === void 0
  };
  function isEqual(a3, b3) {
    if (is.arr(a3)) {
      if (!is.arr(b3) || a3.length !== b3.length) return false;
      for (let i3 = 0; i3 < a3.length; i3++) {
        if (a3[i3] !== b3[i3]) return false;
      }
      return true;
    }
    return a3 === b3;
  }
  var each = (obj, fn) => obj.forEach(fn);
  function eachProp(obj, fn, ctx9) {
    if (is.arr(obj)) {
      for (let i3 = 0; i3 < obj.length; i3++) {
        fn.call(ctx9, obj[i3], `${i3}`);
      }
      return;
    }
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        fn.call(ctx9, obj[key], key);
      }
    }
  }
  var toArray = (a3) => is.und(a3) ? [] : is.arr(a3) ? a3 : [a3];
  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 = noop5;
  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(advance2);
      }
    },
    advance: advance2,
    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(advance2);
  }
  function startSafely(animation) {
    if (!currentFrame.includes(animation)) startUnsafely(animation);
  }
  function startUnsafely(animation) {
    currentFrame.splice(findIndex(currentFrame, (other) => other.priority > animation.priority), 0, animation);
  }
  function advance2(dt) {
    const nextFrame = prevFrame;
    for (let i3 = 0; i3 < currentFrame.length; i3++) {
      const animation = currentFrame[i3];
      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(p4, q, t4) {
    if (t4 < 0) t4 += 1;
    if (t4 > 1) t4 -= 1;
    if (t4 < 1 / 6) return p4 + (q - p4) * 6 * t4;
    if (t4 < 1 / 2) return q;
    if (t4 < 2 / 3) return p4 + (q - p4) * (2 / 3 - t4) * 6;
    return p4;
  }
  function hslToRgb(h3, s3, l3) {
    const q = l3 < 0.5 ? l3 * (1 + s3) : l3 + s3 - l3 * s3;
    const p4 = 2 * l3 - q;
    const r4 = hue2rgb(p4, q, h3 + 1 / 3);
    const g3 = hue2rgb(p4, q, h3);
    const b3 = hue2rgb(p4, q, h3 - 1 / 3);
    return Math.round(r4 * 255) << 24 | Math.round(g3 * 255) << 16 | Math.round(b3 * 255) << 8;
  }
  function parse255(str3) {
    const int = parseInt(str3, 10);
    if (int < 0) return 0;
    if (int > 255) return 255;
    return int;
  }
  function parse360(str3) {
    const int = parseFloat(str3);
    return (int % 360 + 360) % 360 / 360;
  }
  function parse1(str3) {
    const num = parseFloat(str3);
    if (num < 0) return 0;
    if (num > 1) return 255;
    return Math.round(num * 255);
  }
  function parsePercentage(str3) {
    const int = parseFloat(str3);
    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 r4 = (int32Color & 4278190080) >>> 24;
    let g3 = (int32Color & 16711680) >>> 16;
    let b3 = (int32Color & 65280) >>> 8;
    let a3 = (int32Color & 255) / 255;
    return `rgba(${r4}, ${g3}, ${b3}, ${a3})`;
  }
  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 || ((t4) => t4);
    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 i3 = 1; i3 < inputRange.length - 1; ++i3) if (inputRange[i3] >= input) break;
    return i3 - 1;
  }
  function _extends() {
    _extends = Object.assign ? Object.assign.bind() : function(target) {
      for (var i3 = 1; i3 < arguments.length; i3++) {
        var source = arguments[i3];
        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, p32, p4) => `rgba(${Math.round(p1)}, ${Math.round(p22)}, ${Math.round(p32)}, ${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((_, i3) => keyframes.map((values) => {
      if (!(i3 in values)) {
        throw Error('The arity of each "output" value must be equal');
      }
      return values[i3];
    }));
    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 i3 = 0;
      return output[0].replace(numberRegex, () => `${interpolators[i3++](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_react13.useEffect : import_react13.useLayoutEffect;
  var useIsMounted = () => {
    const isMounted = (0, import_react13.useRef)(false);
    useIsomorphicLayoutEffect(() => {
      isMounted.current = true;
      return () => {
        isMounted.current = false;
      };
    }, []);
    return isMounted;
  };
  function useForceUpdate() {
    const update4 = (0, import_react13.useState)()[1];
    const isMounted = useIsMounted();
    return () => {
      if (isMounted.current) {
        update4(Math.random());
      }
    };
  }
  function useMemoOne(getResult, inputs) {
    const [initial2] = (0, import_react13.useState)(() => ({
      inputs,
      result: getResult()
    }));
    const committed = (0, import_react13.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_react13.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 i3 = 0; i3 < next.length; i3++) {
      if (next[i3] !== prev[i3]) {
        return false;
      }
    }
    return true;
  }
  var useOnce = (effect) => (0, import_react13.useEffect)(effect, emptyDeps);
  var emptyDeps = [];

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

  // node_modules/@react-spring/animated/dist/react-spring-animated.esm.js
  var React73 = __toESM(require_react());
  var import_react14 = __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, i3) => node.setValue(source[i3])).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 i3 = 1; i3 < arguments.length; i3++) {
        var source = arguments[i3];
        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 = (Component3, host2) => {
    const hasInstance = !is.fun(Component3) || Component3.prototype && Component3.prototype.isReactComponent;
    return (0, import_react14.forwardRef)((givenProps, givenRef) => {
      const instanceRef = (0, import_react14.useRef)(null);
      const ref = hasInstance && (0, import_react14.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_react14.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_react14.useEffect)(callback, []);
      useOnce(() => () => {
        const observer2 = observerRef.current;
        each(observer2.deps, (dep) => removeFluidObserver(dep, observer2));
      });
      const usedProps = host2.getComponentProps(props.getValue());
      return React73.createElement(Component3, _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 = (Component3) => {
      const displayName = getDisplayName(Component3) || "Anonymous";
      if (is.str(Component3)) {
        Component3 = animated2[Component3] || (animated2[Component3] = withAnimated(Component3, hostConfig));
      } else {
        Component3 = Component3[cacheKey] || (Component3[cacheKey] = withAnimated(Component3, hostConfig));
      }
      Component3.displayName = `Animated(${displayName})`;
      return Component3;
    };
    eachProp(components, (Component3, key) => {
      if (is.arr(components)) {
        key = getDisplayName(Component3);
      }
      animated2[key] = animated2(Component3);
    });
    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 i3 = 1; i3 < arguments.length; i3++) {
        var source = arguments[i3];
        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: state2,
    actions: actions2
  }) {
    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)) {
          state2.paused = matchProp(props.pause, key);
        }
        let pause = defaultProps == null ? void 0 : defaultProps.pause;
        if (pause !== true) {
          pause = state2.paused || matchProp(pause, key);
        }
        delay = callProp(props.delay || 0, key);
        if (pause) {
          state2.resumeQueue.add(onResume);
          actions2.pause();
        } else {
          actions2.resume();
          onResume();
        }
      }
      function onPause() {
        state2.resumeQueue.add(onResume);
        state2.timeouts.delete(timeout);
        timeout.cancel();
        delay = timeout.time - raf.now();
      }
      function onResume() {
        if (delay > 0 && !globals.skipAnimation) {
          state2.delayed = true;
          timeout = raf.setTimeout(onStart, delay);
          state2.pauseQueue.add(onPause);
          state2.timeouts.add(timeout);
        } else {
          onStart();
        }
      }
      function onStart() {
        if (state2.delayed) {
          state2.delayed = false;
        }
        state2.pauseQueue.delete(onPause);
        state2.timeouts.delete(timeout);
        if (callId <= (state2.cancelId || 0)) {
          cancel = true;
        }
        try {
          actions2.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, state2, target) {
    const {
      callId,
      parentId,
      onRest
    } = props;
    const {
      asyncTo: prevTo,
      promise: prevPromise
    } = state2;
    if (!parentId && to2 === prevTo && !props.reset) {
      return prevPromise;
    }
    return state2.promise = (async () => {
      state2.asyncId = callId;
      state2.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 <= (state2.cancelId || 0) && getCancelledResult(target) || callId !== state2.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(state2);
            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 (state2.paused) {
            await new Promise((resume) => {
              state2.resumeQueue.add(resume);
            });
          }
          return result2;
        })();
      };
      let result;
      if (globals.skipAnimation) {
        stopAsync(state2);
        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 == state2.asyncId) {
          state2.asyncId = parentId;
          state2.asyncTo = parentId ? prevTo : void 0;
          state2.promise = parentId ? prevPromise : void 0;
        }
      }
      if (is.fun(onRest)) {
        raf.batchedUpdates(() => {
          onRest(result, target, target.item);
        });
      }
      return result;
    })();
  }
  function stopAsync(state2, cancelId) {
    flush(state2.timeouts, (t4) => t4.cancel());
    state2.pauseQueue.clear();
    state2.resumeQueue.clear();
    state2.asyncId = state2.asyncTo = state2.promise = void 0;
    if (cancelId) state2.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, i3) => {
        if (node2.done) return;
        const to2 = node2.constructor == AnimatedString ? 1 : payload ? payload[i3].lastPosition : toValues[i3];
        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[i3];
          const v0 = node2.v0 != null ? node2.v0 : node2.v0 = is.arr(config2.velocity) ? config2.velocity[i3] : 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 p4 = 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;
                }
              }
              p4 = (config2.progress || 0) + elapsed / this._memoizedDuration;
              p4 = p4 > 1 ? 1 : p4 < 0 ? 0 : p4;
              node2.durationProgress = p4;
            }
            position = from + config2.easing(p4) * (to2 - from);
            velocity = (position - node2.lastPosition) / dt;
            finished = p4 == 1;
          } else if (config2.decay) {
            const decay = config2.decay === true ? 0.998 : config2.decay;
            const e3 = Math.exp(-(1 - decay) * elapsed);
            position = from + v0 / (1 - decay) * (1 - e3);
            finished = Math.abs(node2.lastPosition - position) <= precision;
            velocity = v0 * e3;
          } 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 n3 = 0; n3 < numSteps; ++n3) {
              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[i3].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 state2 = this._state;
      return scheduleProps(++this._lastCallId, {
        key,
        props,
        defaultProps,
        state: state2,
        actions: {
          pause: () => {
            if (!isPaused(this)) {
              setPausedBit(this, true);
              flushCalls(state2.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(state2.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 state2 = ctrl["_state"];
    if (props.pause === !state2.paused) {
      state2.paused = props.pause;
      flushCalls(props.pause ? state2.pauseQueue : state2.resumeQueue);
    } else if (state2.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 && state2.asyncId) {
      promises.push(scheduleProps(++ctrl["_lastAsyncId"], {
        props,
        state: state2,
        actions: {
          pause: noop5,
          resume: noop5,
          start(props2, resolve) {
            if (cancel) {
              stopAsync(state2, ctrl["_lastAsyncId"]);
              resolve(getCancelledResult(ctrl));
            } else {
              props2.onRest = onRest;
              resolve(runAsync(asyncTo, props2, state2, ctrl));
            }
          }
        }
      }));
    }
    if (state2.paused) {
      await new Promise((resume) => {
        state2.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, create8) {
    if (props.keys) {
      each(props.keys, (key) => {
        const spring = springs[key] || (springs[key] = create8(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, i3;
    for (i3 = 0; i3 < sourceKeys.length; i3++) {
      key = sourceKeys[i3];
      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_react15.useContext)(ctx);
    const pause = props.pause || !!inherited.pause, immediate = props.immediate || !!inherited.immediate;
    props = useMemoOne(() => ({
      pause,
      immediate
    }), [pause, immediate]);
    const {
      Provider: Provider2
    } = ctx;
    return React74.createElement(Provider2, {
      value: props
    }, children);
  };
  var ctx = makeContext(SpringContext, {});
  SpringContext.Provider = ctx.Provider;
  SpringContext.Consumer = ctx.Consumer;
  function makeContext(target, init2) {
    Object.assign(target, React74.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, i3;
    for (i3 = 0; i3 < sourceKeys.length; i3++) {
      key = sourceKeys[i3];
      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, (n3) => "-" + n3.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, i3) => {
      instance.setAttribute(name2, values[i3]);
    });
    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((v3) => isValueIdentity(v3, id)) : is.num(value) ? value === id : parseFloat(value) === id;
  var AnimatedStyle = class extends AnimatedObject {
    constructor(_ref) {
      let {
        x: x2,
        y: y3,
        z
      } = _ref, style = _objectWithoutPropertiesLoose2(_ref, _excluded$1);
      const inputs = [];
      const transforms = [];
      if (x2 || y3 || z) {
        inputs.push([x2 || 0, y3 || 0, z || 0]);
        transforms.push((xyz) => [`translate3d(${xyz.map((v3) => addUnit(v3, "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, y4, z2, deg]) => [`rotate3d(${x3},${y4},${z2},${addUnit(deg, unit)})`, isValueIdentity(deg, 0)] : (input) => [`${key}(${input.map((v3) => addUnit(v3, 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 identity4 = true;
      each(this.inputs, (input, i3) => {
        const arg1 = getFluidValue(input[0]);
        const [t4, id] = this.transforms[i3](is.arr(arg1) ? arg1 : input.map(getFluidValue));
        transform += " " + t4;
        identity4 = identity4 && id;
      });
      return identity4 ? "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/fields/build-module/components/media-edit/use-moving-animation.mjs
  var import_element47 = __toESM(require_element(), 1);
  function getAbsolutePosition(element) {
    return {
      top: element.offsetTop,
      left: element.offsetLeft
    };
  }
  function useMovingAnimation(triggerAnimationOnChange) {
    const ref = (0, import_element47.useRef)(null);
    const previousRef = (0, import_element47.useRef)(void 0);
    if (ref.current) {
      previousRef.current = getAbsolutePosition(ref.current);
    }
    (0, import_element47.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 = getAbsolutePosition(ref.current);
      const x2 = Math.round(previous.left - destination.left);
      const y3 = Math.round(previous.top - destination.top);
      controller.start({ x: 0, y: 0, from: { x: x2, y: y3 } });
      return () => {
        controller.stop();
        controller.set({ x: 0, y: 0 });
      };
    }, [triggerAnimationOnChange]);
    return ref;
  }

  // packages/fields/build-module/components/media-edit/index.mjs
  var import_jsx_runtime140 = __toESM(require_jsx_runtime(), 1);
  var { MediaUploadModal } = unlock3(import_media_utils2.privateApis);
  function AnimatedMediaItem({
    children,
    index: index2,
    className
  }) {
    const ref = useMovingAnimation(index2);
    return /* @__PURE__ */ (0, import_jsx_runtime140.jsx)("div", { ref, className, children });
  }
  function normalizeValue(value) {
    if (Array.isArray(value)) {
      return value;
    }
    return value ? [value] : [];
  }
  function ConditionalMediaUpload({ render: render5, multiple, ...props }) {
    const [isModalOpen, setIsModalOpen] = (0, import_element48.useState)(false);
    if (window.__experimentalDataViewsMediaModal) {
      return /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(import_jsx_runtime140.Fragment, { children: [
        render5 && render5({ open: () => setIsModalOpen(true) }),
        isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
          MediaUploadModal,
          {
            ...props,
            multiple,
            isOpen: isModalOpen,
            onClose: () => {
              setIsModalOpen(false);
              props.onClose?.();
            },
            onSelect: (media) => {
              setIsModalOpen(false);
              props.onSelect?.(media);
            }
          }
        )
      ] });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
      import_media_utils2.MediaUpload,
      {
        ...props,
        render: render5,
        multiple: multiple ? "add" : void 0
      }
    );
  }
  function MediaPickerButton({
    open,
    children,
    label,
    showTooltip = false,
    onFilesDrop,
    attachment,
    isUploading = false
  }) {
    const isBlob = attachment && (0, import_blob.isBlobURL)(attachment.source_url);
    const mediaPickerButton = /* @__PURE__ */ (0, import_jsx_runtime140.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_runtime140.jsx)("span", { className: "fields__media-edit-picker-button-spinner", children: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(import_components4.Spinner, {}) }),
          !isUploading && /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
            import_components4.DropZone,
            {
              onFilesDrop: (files) => onFilesDrop(files, attachment?.id)
            }
          )
        ]
      }
    );
    if (!showTooltip) {
      return mediaPickerButton;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(tooltip_exports.Root, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(tooltip_exports.Trigger, { render: mediaPickerButton }),
      /* @__PURE__ */ (0, import_jsx_runtime140.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_runtime140.jsx)(import_components4.__experimentalTruncate, { className: "fields__media-edit-filename", children: (0, import_html_entities3.decodeEntities)(attachment.title.rendered) });
  }
  function MediaEditPlaceholder(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(MediaPickerButton, { ...props, children: /* @__PURE__ */ (0, import_jsx_runtime140.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_runtime140.jsxs)(import_jsx_runtime140.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
        import_components4.Button,
        {
          __next40pxDefaultSize: true,
          icon: isHorizontal ? chevron_left_default : chevron_up_default,
          label: isHorizontal ? (0, import_i18n17.__)("Move left") : (0, import_i18n17.__)("Move up"),
          size: "small",
          disabled: isUploading || index2 === 0,
          accessibleWhenDisabled: true,
          tooltipPosition: "top",
          onClick: (event) => {
            event.stopPropagation();
            moveItem(itemId, "up");
          }
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
        import_components4.Button,
        {
          __next40pxDefaultSize: true,
          icon: isHorizontal ? chevron_right_default : chevron_down_default,
          label: isHorizontal ? (0, import_i18n17.__)("Move right") : (0, import_i18n17.__)("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_runtime140.jsx)(
        "img",
        {
          className: "fields__media-edit-thumbnail",
          alt: attachment.alt_text || "",
          src: url
        }
      );
    } else if (mimeType.startsWith("audio")) {
      return /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(import_components4.Icon, { icon: audio_default });
    } else if (mimeType.startsWith("video")) {
      return /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(import_components4.Icon, { icon: video_default });
    } else if (archiveMimeTypes.includes(mimeType)) {
      return /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(import_components4.Icon, { icon: archive_default });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(import_components4.Icon, { icon: file_default });
  }
  function ExpandedMediaEditAttachments({
    allItems,
    addButtonLabel,
    multiple,
    removeItem,
    moveItem,
    open,
    onFilesDrop,
    isUploading,
    setTargetItemId
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime140.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_blob.isBlobURL)(attachment.source_url);
            const attachmentNumericId = attachment.id;
            return /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(
              AnimatedMediaItem,
              {
                index: index2,
                className: clsx_default("fields__media-edit-expanded-item", {
                  "has-preview-image": hasPreviewImage
                }),
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                    MediaPickerButton,
                    {
                      open: () => {
                        setTargetItemId(attachmentNumericId);
                        open();
                      },
                      label: !isBlob ? (0, import_i18n17.sprintf)(
                        /* translators: %s: The title of the media item. */
                        (0, import_i18n17.__)("Replace %s"),
                        (0, import_html_entities3.decodeEntities)(
                          attachment.title.rendered
                        )
                      ) : (0, import_i18n17.__)("Replace"),
                      showTooltip: true,
                      onFilesDrop,
                      attachment,
                      isUploading,
                      children: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)("div", { className: "fields__media-edit-expanded-preview", children: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                        import_components4.__experimentalVStack,
                        {
                          spacing: 0,
                          alignment: "center",
                          justify: "center",
                          className: "fields__media-edit-expanded-preview-stack",
                          children: (!isBlob || hasPreviewImage) && /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                            MediaPreview,
                            {
                              attachment
                            }
                          )
                        }
                      ) })
                    }
                  ),
                  !isBlob && /* @__PURE__ */ (0, import_jsx_runtime140.jsx)("div", { className: "fields__media-edit-expanded-overlay", children: /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(
                    import_components4.__experimentalHStack,
                    {
                      className: "fields__media-edit-expanded-actions",
                      spacing: 0,
                      alignment: "flex-end",
                      expanded: false,
                      children: [
                        multiple && allItems.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                          MoveButtons,
                          {
                            itemId: attachmentNumericId,
                            index: index2,
                            totalItems: allItems.length,
                            isUploading,
                            moveItem,
                            orientation: "horizontal"
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                          import_components4.Button,
                          {
                            __next40pxDefaultSize: true,
                            icon: close_small_default,
                            label: (0, import_i18n17.__)("Remove"),
                            size: "small",
                            disabled: isUploading,
                            accessibleWhenDisabled: true,
                            tooltipPosition: "top",
                            onClick: (event) => {
                              event.stopPropagation();
                              removeItem(attachmentNumericId);
                            }
                          }
                        )
                      ]
                    }
                  ) })
                ]
              },
              attachment.id
            );
          }),
          (multiple || !allItems?.length) && /* @__PURE__ */ (0, import_jsx_runtime140.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_runtime140.jsxs)(import_jsx_runtime140.Fragment, { children: [
      !!allItems?.length && /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
        "div",
        {
          className: clsx_default("fields__media-edit-compact-group", {
            "is-single": allItems.length === 1
          }),
          children: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(import_components4.__experimentalVStack, { spacing: 0, children: allItems.map((attachment, index2) => {
            const isBlob = (0, import_blob.isBlobURL)(attachment.source_url);
            const showMoveButtons = multiple && allItems.length > 1;
            const attachmentNumericId = attachment.id;
            return /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(
              AnimatedMediaItem,
              {
                index: index2,
                className: "fields__media-edit-compact",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                    MediaPickerButton,
                    {
                      open: () => {
                        setTargetItemId(
                          attachmentNumericId
                        );
                        open();
                      },
                      label: (0, import_i18n17.__)("Replace"),
                      showTooltip: true,
                      onFilesDrop,
                      attachment,
                      isUploading,
                      children: /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(import_jsx_runtime140.Fragment, { children: [
                        /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                          MediaPreview,
                          {
                            attachment
                          }
                        ),
                        !isBlob && /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                          MediaTitle,
                          {
                            attachment
                          }
                        )
                      ] })
                    }
                  ),
                  !isBlob && /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(
                    import_components4.__experimentalHStack,
                    {
                      className: "fields__media-edit-compact-movers",
                      spacing: 0,
                      alignment: "flex-end",
                      expanded: false,
                      children: [
                        showMoveButtons && /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                          MoveButtons,
                          {
                            itemId: attachmentNumericId,
                            index: index2,
                            totalItems: allItems.length,
                            isUploading,
                            moveItem,
                            orientation: "vertical"
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                          import_components4.Button,
                          {
                            __next40pxDefaultSize: true,
                            icon: close_small_default,
                            label: (0, import_i18n17.__)("Remove"),
                            size: "small",
                            disabled: isUploading,
                            accessibleWhenDisabled: true,
                            tooltipPosition: "top",
                            onClick: (event) => {
                              event.stopPropagation();
                              removeItem(
                                attachmentNumericId
                              );
                            }
                          }
                        )
                      ]
                    }
                  )
                ]
              },
              attachment.id
            );
          }) })
        }
      ),
      (multiple || !allItems?.length) && /* @__PURE__ */ (0, import_jsx_runtime140.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_element48.useState)(false);
    const validityTargetRef = (0, import_element48.useRef)(null);
    const [customValidity, setCustomValidity] = (0, import_element48.useState)(void 0);
    (0, import_element48.useEffect)(() => {
      const validityTarget = validityTargetRef.current;
      const handler = () => {
        setIsTouched(true);
      };
      validityTarget?.addEventListener("invalid", handler);
      return () => validityTarget?.removeEventListener("invalid", handler);
    }, []);
    const attachments = (0, import_data9.useSelect)(
      (select9) => {
        if (!value) {
          return null;
        }
        const normalizedValue = normalizeValue(value);
        const sortedIds = normalizedValue.toSorted((a3, b3) => a3 - b3);
        const { getEntityRecords } = select9(import_core_data5.store);
        return getEntityRecords("postType", "attachment", {
          include: sortedIds
        });
      },
      [value]
    );
    const stableAttachmentsRef = (0, import_element48.useRef)(
      null
    );
    if (attachments !== null) {
      stableAttachmentsRef.current = attachments;
    }
    let stableAttachments = attachments;
    if (attachments === null && stableAttachmentsRef.current && value) {
      const stableIds = new Set(
        stableAttachmentsRef.current.map((a3) => a3.id)
      );
      if (normalizeValue(value).every((id) => stableIds.has(id))) {
        stableAttachments = stableAttachmentsRef.current;
      }
    }
    const orderedAttachments = (0, import_element48.useMemo)(() => {
      if (!stableAttachments) {
        return null;
      }
      const normalizedValue = normalizeValue(value);
      const attachmentMap = new Map(
        stableAttachments.map((a3) => [a3.id, a3])
      );
      return normalizedValue.map((id) => attachmentMap.get(id)).filter((a3) => a3 !== void 0);
    }, [stableAttachments, value]);
    const { createErrorNotice } = (0, import_data9.useDispatch)(import_notices2.store);
    const { receiveEntityRecords } = (0, import_data9.useDispatch)(import_core_data5.store);
    const [targetItemId, setTargetItemId] = (0, import_element48.useState)();
    const openModalRef = (0, import_element48.useRef)(void 0);
    const [pendingOpen, setPendingOpen] = (0, import_element48.useState)(false);
    const [blobs, setBlobs] = (0, import_element48.useState)([]);
    (0, import_element48.useEffect)(() => {
      if (pendingOpen) {
        setPendingOpen(false);
        openModalRef.current?.();
      }
    }, [pendingOpen]);
    const onChangeControl = (0, import_element48.useCallback)(
      (newValue) => onChange(field.setValue({ item: data, value: newValue })),
      [data, field, onChange]
    );
    const removeItem = (0, import_element48.useCallback)(
      (itemId) => {
        const currentIds = normalizeValue(value);
        const newIds = currentIds.filter((id) => id !== itemId);
        setIsTouched(true);
        onChangeControl(newIds.length ? newIds : void 0);
      },
      [value, onChangeControl]
    );
    const moveItem = (0, import_element48.useCallback)(
      (itemId, direction) => {
        if (!orderedAttachments) {
          return;
        }
        const currentIds = orderedAttachments.map((a3) => a3.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_element48.useCallback)(
      (files, _targetItemId) => {
        setTargetItemId(_targetItemId);
        (0, import_media_utils2.uploadMedia)({
          allowedTypes: allowedTypes?.length ? allowedTypes : void 0,
          filesList: files,
          onFileChange(uploadedMedia) {
            const blobUrls = uploadedMedia.filter((item) => (0, import_blob.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 = normalizeValue(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_i18n17.__)("Choose files") : (0, import_i18n17.__)("Choose file"));
    const allItems = (0, import_element48.useMemo)(() => {
      if (!blobs.length) {
        return orderedAttachments;
      }
      const items = [
        ...orderedAttachments || []
      ];
      const blobItems = blobs.map((url) => ({
        id: url,
        source_url: url,
        mime_type: (0, import_blob.getBlobTypeByURL)(url)
      }));
      if (targetItemId !== void 0) {
        const targetIndex = items.findIndex(
          (a3) => a3.id === targetItemId
        );
        items.splice(targetIndex, 1, ...blobItems);
      } else {
        items.push(...blobItems);
      }
      return items;
    }, [orderedAttachments, targetItemId, blobs]);
    (0, import_element48.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_i18n17.__)("Invalid")
          );
        } else {
          input.setCustomValidity("");
        }
      } else {
        input.setCustomValidity("");
        setCustomValidity(void 0);
      }
    }, [isTouched, field.isValid, validity]);
    (0, import_element48.useEffect)(() => {
      if (isTouched && customValidity?.message) {
        (0, import_a11y2.speak)(customValidity.message);
      }
    }, [isTouched, customValidity?.message]);
    const onBlur = (0, import_element48.useCallback)(
      (event) => {
        if (isTouched) {
          return;
        }
        if (!event.relatedTarget || !event.currentTarget.contains(event.relatedTarget)) {
          setIsTouched(true);
        }
      },
      [isTouched]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)("div", { onBlur, children: [
      /* @__PURE__ */ (0, import_jsx_runtime140.jsx)("fieldset", { className: "fields__media-edit", "data-field-id": field.id, children: /* @__PURE__ */ (0, import_jsx_runtime140.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 = normalizeValue(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_runtime140.jsxs)(import_components4.__experimentalVStack, { spacing: 2, children: [
              field.label && (hideLabelFromVision ? /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)("legend", {}), children: field.label }) : /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                import_components4.BaseControl.VisualLabel,
                {
                  as: "legend",
                  style: { marginBottom: 0 },
                  children: field.label
                }
              )),
              /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                AttachmentsComponent,
                {
                  allItems,
                  addButtonLabel,
                  multiple,
                  removeItem,
                  moveItem,
                  open: () => setPendingOpen(true),
                  onFilesDrop,
                  isUploading: !!blobs.length,
                  setTargetItemId
                }
              ),
              field.description && /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
                import_components4.__experimentalText,
                {
                  variant: "muted",
                  className: "fields__media-edit-description",
                  children: field.description
                }
              )
            ] });
          }
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(VisuallyHidden, { children: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
        "input",
        {
          type: "text",
          ref: validityTargetRef,
          value: value ?? "",
          tabIndex: -1,
          "aria-hidden": "true",
          onChange: () => {
          }
        }
      ) }),
      customValidity && /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(
        "p",
        {
          className: clsx_default(
            "components-validated-control__indicator",
            {
              "is-invalid": customValidity.type === "invalid",
              "is-valid": customValidity.type === "valid"
            }
          ),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
              import_components4.Icon,
              {
                className: "components-validated-control__indicator-icon",
                icon: error_default,
                size: 16,
                fill: "currentColor"
              }
            ),
            customValidity.message
          ]
        }
      )
    ] });
  }

  // packages/fields/build-module/fields/featured-image/featured-image-view.mjs
  var import_jsx_runtime141 = __toESM(require_jsx_runtime(), 1);
  var FeaturedImageView = ({
    item,
    config: config2
  }) => {
    const media = item?._embedded?.["wp:featuredmedia"]?.[0];
    const url = media?.source_url;
    if (url) {
      return /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
        "img",
        {
          className: "fields-controls__featured-image-image",
          src: url,
          alt: "",
          srcSet: media?.media_details?.sizes ? Object.values(media.media_details.sizes).map(
            (size4) => `${size4.source_url} ${size4.width}w`
          ).join(", ") : void 0,
          sizes: config2?.sizes || "100vw"
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime141.jsx)("span", { className: "fields-controls__featured-image-placeholder" });
  };

  // packages/fields/build-module/fields/featured-image/index.mjs
  var import_jsx_runtime142 = __toESM(require_jsx_runtime(), 1);
  var featuredImageField = {
    id: "featured_media",
    type: "media",
    label: (0, import_i18n18.__)("Featured Image"),
    placeholder: (0, import_i18n18.__)("Set featured image"),
    Edit: (props) => /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(MediaEdit, { ...props, isExpanded: true }),
    render: FeaturedImageView,
    setValue: ({ value }) => ({
      featured_media: value ?? 0
    }),
    enableSorting: false,
    filterBy: false
  };
  var featured_image_default = featuredImageField;

  // packages/fields/build-module/fields/template/index.mjs
  var import_i18n21 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/template/template-edit.mjs
  var import_element49 = __toESM(require_element(), 1);
  var import_core_data7 = __toESM(require_core_data(), 1);
  var import_components5 = __toESM(require_components(), 1);
  var import_data11 = __toESM(require_data(), 1);
  var import_i18n19 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/template/hooks.mjs
  var import_data10 = __toESM(require_data(), 1);
  var import_core_data6 = __toESM(require_core_data(), 1);
  function useTemplateFieldMode(record) {
    const postType2 = record.type;
    const availableTemplates = record?.available_templates ?? {};
    const hasAvailableTemplates = Object.keys(availableTemplates).length > 0;
    return (0, import_data10.useSelect)(
      (select9) => {
        const isBlockTheme = !!select9(import_core_data6.store).getCurrentTheme()?.is_block_theme;
        const postTypeObj = select9(import_core_data6.store).getPostType(postType2);
        if (!postTypeObj?.viewable) {
          return null;
        }
        const canCreateTemplates = isBlockTheme && (select9(import_core_data6.store).canUser("create", {
          kind: "postType",
          name: "wp_template"
        }) ?? false);
        const isVisible2 = hasAvailableTemplates || canCreateTemplates;
        const canViewTemplates = isVisible2 ? !!select9(import_core_data6.store).canUser("read", {
          kind: "postType",
          name: "wp_template"
        }) : false;
        if ((!isBlockTheme || !canViewTemplates) && isVisible2) {
          return "classic";
        }
        if (isBlockTheme && canViewTemplates) {
          return "block-theme";
        }
        return null;
      },
      [postType2, hasAvailableTemplates]
    );
  }
  function getTemplateSlugToCheck(postType2, slug) {
    if (slug) {
      return postType2 === "page" ? `${postType2}-${slug}` : `single-${postType2}-${slug}`;
    }
    return postType2 === "page" ? "page" : `single-${postType2}`;
  }
  var NAME_NOT_FOUND = "";
  function useDefaultTemplateLabel(postType2, postId2, slug) {
    return (0, import_data10.useSelect)(
      (select9) => {
        if (!postType2 || !postId2) {
          return NAME_NOT_FOUND;
        }
        const postIdStr = String(postId2);
        const homePage = unlock3(select9(import_core_data6.store)).getHomePage();
        if (postType2 === "page" && homePage?.postType === "page" && homePage?.postId === postIdStr) {
          const templates = select9(
            import_core_data6.store
          ).getEntityRecords("postType", "wp_template", {
            per_page: -1
          });
          const frontPage = templates?.find(
            (t4) => t4.slug === "front-page"
          );
          if (frontPage) {
            return getItemTitle(frontPage);
          }
        }
        const postsPageId = unlock3(select9(import_core_data6.store)).getPostsPageId();
        if (postType2 === "page" && postsPageId === postIdStr) {
          const templateId22 = select9(import_core_data6.store).getDefaultTemplateId({
            slug: "home"
          });
          if (!templateId22) {
            return NAME_NOT_FOUND;
          }
          const template22 = select9(
            import_core_data6.store
          ).getEntityRecord(
            "postType",
            "wp_template",
            templateId22
          );
          return template22 ? getItemTitle(template22) : NAME_NOT_FOUND;
        }
        const slugToCheck = getTemplateSlugToCheck(postType2, slug);
        const templateId2 = select9(import_core_data6.store).getDefaultTemplateId({
          slug: slugToCheck
        });
        if (!templateId2) {
          return NAME_NOT_FOUND;
        }
        const template2 = select9(import_core_data6.store).getEntityRecord(
          "postType",
          "wp_template",
          templateId2
        );
        return template2 ? getItemTitle(template2) : NAME_NOT_FOUND;
      },
      [postType2, postId2, slug]
    );
  }

  // packages/fields/build-module/fields/template/template-edit.mjs
  var import_jsx_runtime143 = __toESM(require_jsx_runtime(), 1);
  var EMPTY_ARRAY5 = [];
  function ClassicTemplateEdit({
    data,
    field,
    onChange
  }) {
    const postId2 = typeof data.id === "number" ? data.id : parseInt(data.id, 10);
    const value = field.getValue({ item: data });
    const options = (0, import_element49.useMemo)(
      () => Object.entries(
        data?.available_templates ?? {}
      ).map(([templateSlug, title]) => ({
        label: title,
        value: templateSlug
      })),
      [data]
    );
    const canSwitchTemplate = (0, import_data11.useSelect)(
      (select9) => {
        const { getHomePage, getPostsPageId } = unlock3(
          select9(import_core_data7.store)
        );
        const singlePostId = String(postId2);
        const isPostsPage = getPostsPageId() === singlePostId;
        const isFrontPage = data.type === "page" && getHomePage()?.postId === singlePostId;
        return !isPostsPage && !isFrontPage;
      },
      [postId2, data.type]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
      import_components5.SelectControl,
      {
        label: (0, import_i18n19.__)("Template"),
        hideLabelFromVision: true,
        value,
        options,
        onChange,
        disabled: !canSwitchTemplate
      }
    );
  }
  function BlockThemeTemplateEdit({
    data,
    field,
    onChange
  }) {
    const postType2 = data.type;
    const postId2 = typeof data.id === "number" ? data.id : parseInt(data.id, 10);
    const slug = data.slug;
    const { templates, canSwitchTemplate } = (0, import_data11.useSelect)(
      (select9) => {
        const allTemplates = select9(import_core_data7.store).getEntityRecords(
          "postType",
          "wp_template",
          {
            per_page: -1,
            post_type: postType2
          }
        ) ?? EMPTY_ARRAY5;
        const { getHomePage, getPostsPageId } = unlock3(
          select9(import_core_data7.store)
        );
        const singlePostId = String(postId2);
        const isPostsPage = getPostsPageId() === singlePostId;
        const isFrontPage = postType2 === "page" && getHomePage()?.postId === singlePostId;
        return {
          templates: allTemplates,
          canSwitchTemplate: !isPostsPage && !isFrontPage
        };
      },
      [postId2, postType2]
    );
    const defaultTemplateLabel = useDefaultTemplateLabel(
      postType2,
      postId2,
      slug
    );
    const value = field.getValue({ item: data });
    const options = (0, import_element49.useMemo)(() => {
      const templateOptions = templates.map((template2) => ({
        label: getItemTitle(template2),
        value: template2.slug
      }));
      return [
        { label: defaultTemplateLabel, value: "" },
        ...templateOptions
      ];
    }, [templates, defaultTemplateLabel]);
    return /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
      import_components5.SelectControl,
      {
        label: (0, import_i18n19.__)("Template"),
        hideLabelFromVision: true,
        value,
        options,
        onChange,
        disabled: !canSwitchTemplate
      }
    );
  }
  var TemplateEdit = ({
    data,
    field,
    onChange
  }) => {
    const onChangeControl = (0, import_element49.useCallback)(
      (newValue) => onChange({
        [field.id]: newValue
      }),
      [field.id, onChange]
    );
    const mode = useTemplateFieldMode(data);
    if (!mode || !["block-theme", "classic"].includes(mode)) {
      return null;
    }
    const Edit2 = mode === "classic" ? ClassicTemplateEdit : BlockThemeTemplateEdit;
    return /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(Edit2, { data, field, onChange: onChangeControl });
  };

  // packages/fields/build-module/fields/template/template-view.mjs
  var import_data12 = __toESM(require_data(), 1);
  var import_core_data8 = __toESM(require_core_data(), 1);
  var import_i18n20 = __toESM(require_i18n(), 1);
  var import_jsx_runtime144 = __toESM(require_jsx_runtime(), 1);
  function ClassicTemplateView({
    item,
    field
  }) {
    const templateSlug = field.getValue({ item });
    const availableTemplates = item?.available_templates ?? {};
    const classicLabel = templateSlug && availableTemplates[templateSlug] ? availableTemplates[templateSlug] : (0, import_i18n20.__)("Default template");
    return /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(import_jsx_runtime144.Fragment, { children: classicLabel });
  }
  function BlockThemeTemplateView({
    item,
    field
  }) {
    const postType2 = item.type;
    const slug = item.slug;
    const postId2 = item.id;
    const templateSlug = field.getValue({ item });
    const defaultTemplateLabel = useDefaultTemplateLabel(
      postType2,
      postId2,
      slug
    );
    const templateLabel = (0, import_data12.useSelect)(
      (select9) => {
        if (!templateSlug) {
          return;
        }
        const allTemplates = select9(
          import_core_data8.store
        ).getEntityRecords("postType", "wp_template", {
          per_page: -1,
          post_type: postType2
        });
        const match3 = allTemplates?.find(
          (t4) => t4.slug === templateSlug
        );
        return match3 ? getItemTitle(match3) : void 0;
      },
      [postType2, templateSlug]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(import_jsx_runtime144.Fragment, { children: templateLabel ?? defaultTemplateLabel });
  }
  var TemplateView = ({
    item,
    field
  }) => {
    const mode = useTemplateFieldMode(item);
    if (!mode || !["block-theme", "classic"].includes(mode)) {
      return null;
    }
    const View4 = mode === "classic" ? ClassicTemplateView : BlockThemeTemplateView;
    return /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(View4, { item, field });
  };

  // packages/fields/build-module/fields/template/index.mjs
  var templateField = {
    id: "template",
    type: "text",
    label: (0, import_i18n21.__)("Template"),
    Edit: TemplateEdit,
    render: TemplateView,
    enableSorting: false,
    filterBy: false
  };
  var template_default = templateField;

  // packages/fields/build-module/fields/parent/index.mjs
  var import_i18n25 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/parent/parent-edit.mjs
  var import_remove_accents = __toESM(require_remove_accents(), 1);
  var import_components6 = __toESM(require_components(), 1);
  var import_data13 = __toESM(require_data(), 1);
  var import_element50 = __toESM(require_element(), 1);
  var import_core_data9 = __toESM(require_core_data(), 1);
  var import_compose3 = __toESM(require_compose(), 1);
  var import_html_entities5 = __toESM(require_html_entities(), 1);
  var import_i18n23 = __toESM(require_i18n(), 1);
  var import_url6 = __toESM(require_url(), 1);

  // packages/fields/build-module/fields/parent/utils.mjs
  var import_html_entities4 = __toESM(require_html_entities(), 1);
  var import_i18n22 = __toESM(require_i18n(), 1);
  function getTitleWithFallbackName(post2) {
    return typeof post2.title === "object" && "rendered" in post2.title && post2.title.rendered ? (0, import_html_entities4.decodeEntities)(post2.title.rendered) : `#${post2?.id} (${(0, import_i18n22.__)("no title")})`;
  }

  // packages/fields/build-module/fields/parent/parent-edit.mjs
  var import_jsx_runtime145 = __toESM(require_jsx_runtime(), 1);
  function buildTermsTree(flatTerms) {
    const flatTermsWithParentAndChildren = flatTerms.map((term) => {
      return {
        children: [],
        ...term
      };
    });
    if (flatTermsWithParentAndChildren.some(
      ({ parent }) => parent === null || parent === void 0
    )) {
      return flatTermsWithParentAndChildren;
    }
    const termsByParent = flatTermsWithParentAndChildren.reduce(
      (acc, term) => {
        const { parent } = term;
        if (!acc[parent]) {
          acc[parent] = [];
        }
        acc[parent].push(term);
        return acc;
      },
      {}
    );
    const fillWithChildren = (terms) => {
      return terms.map((term) => {
        const children = termsByParent[term.id];
        return {
          ...term,
          children: children && children.length ? fillWithChildren(children) : []
        };
      });
    };
    return fillWithChildren(termsByParent["0"] || []);
  }
  var getItemPriority = (name2, searchValue) => {
    const normalizedName = (0, import_remove_accents.default)(name2 || "").toLowerCase();
    const normalizedSearch = (0, import_remove_accents.default)(searchValue || "").toLowerCase();
    if (normalizedName === normalizedSearch) {
      return 0;
    }
    if (normalizedName.startsWith(normalizedSearch)) {
      return normalizedName.length;
    }
    return Infinity;
  };
  function PageAttributesParent({
    data,
    onChangeControl
  }) {
    const [fieldValue, setFieldValue] = (0, import_element50.useState)("");
    const pageId = data.parent;
    const postId2 = data.id;
    const postTypeSlug = data.type;
    const { parentPostTitle, pageItems, isHierarchical } = (0, import_data13.useSelect)(
      (select9) => {
        const { getEntityRecord, getEntityRecords, getPostType } = select9(import_core_data9.store);
        const postTypeInfo = getPostType(postTypeSlug);
        const postIsHierarchical = postTypeInfo?.hierarchical && postTypeInfo.viewable;
        const parentPost = pageId ? getEntityRecord(
          "postType",
          postTypeSlug,
          pageId
        ) : null;
        const query = {
          per_page: 100,
          exclude: postId2,
          parent_exclude: postId2,
          orderby: "menu_order",
          order: "asc",
          _fields: "id,title,parent",
          ...!!fieldValue && {
            // Perform a search by relevance when the field is changed.
            search: fieldValue,
            orderby: "relevance",
            search_columns: ["post_title"]
          }
        };
        return {
          isHierarchical: postIsHierarchical,
          parentPostTitle: parentPost ? getTitleWithFallbackName(parentPost) : "",
          pageItems: postIsHierarchical ? getEntityRecords(
            "postType",
            postTypeSlug,
            query
          ) : null
        };
      },
      [fieldValue, pageId, postId2, postTypeSlug]
    );
    const parentOptions = (0, import_element50.useMemo)(() => {
      const getOptionsFromTree = (tree2, level = 0) => {
        const mappedNodes = tree2.map((treeNode) => [
          {
            value: treeNode.id,
            label: "\u2014 ".repeat(level) + (0, import_html_entities5.decodeEntities)(treeNode.name),
            rawName: treeNode.name
          },
          ...getOptionsFromTree(treeNode.children || [], level + 1)
        ]);
        const sortedNodes = mappedNodes.sort(([a3], [b3]) => {
          const priorityA = getItemPriority(a3.rawName, fieldValue);
          const priorityB = getItemPriority(b3.rawName, fieldValue);
          return priorityA >= priorityB ? 1 : -1;
        });
        return sortedNodes.flat();
      };
      if (!pageItems) {
        return [];
      }
      let tree = pageItems.map((item) => ({
        id: item.id,
        parent: item.parent ?? null,
        name: getTitleWithFallbackName(item)
      }));
      if (!fieldValue) {
        tree = buildTermsTree(tree);
      }
      const opts = getOptionsFromTree(tree);
      const optsHasParent = opts.find((item) => item.value === pageId);
      if (pageId && parentPostTitle && !optsHasParent) {
        opts.unshift({
          value: pageId,
          label: parentPostTitle,
          rawName: ""
        });
      }
      return opts.map((option) => ({
        ...option,
        value: option.value.toString()
      }));
    }, [pageItems, fieldValue, parentPostTitle, pageId]);
    if (!isHierarchical) {
      return null;
    }
    const handleKeydown = (inputValue) => {
      setFieldValue(inputValue);
    };
    const handleChange = (selectedPostId) => {
      if (selectedPostId) {
        return onChangeControl(parseInt(selectedPostId, 10) ?? 0);
      }
      onChangeControl(0);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime145.jsx)(
      import_components6.ComboboxControl,
      {
        label: (0, import_i18n23.__)("Parent"),
        help: (0, import_i18n23.__)("Choose a parent page."),
        value: pageId?.toString(),
        options: parentOptions,
        onFilterValueChange: (0, import_compose3.debounce)(
          (value) => handleKeydown(value),
          300
        ),
        onChange: handleChange,
        hideLabelFromVision: true
      }
    );
  }
  var ParentEdit = ({
    data,
    field,
    onChange
  }) => {
    const { id } = field;
    const homeUrl = (0, import_data13.useSelect)((select9) => {
      return select9(import_core_data9.store).getEntityRecord("root", "__unstableBase")?.home;
    }, []);
    const onChangeControl = (0, import_element50.useCallback)(
      (newValue) => onChange({
        [id]: newValue
      }),
      [id, onChange]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime145.jsx)("fieldset", { className: "fields-controls__parent", children: /* @__PURE__ */ (0, import_jsx_runtime145.jsxs)("div", { children: [
      (0, import_element50.createInterpolateElement)(
        (0, import_i18n23.sprintf)(
          /* translators: %1$s The home URL of the WordPress installation without the scheme. */
          (0, import_i18n23.__)(
            'Child pages inherit characteristics from their parent, such as URL structure. For instance, if "Pricing" is a child of "Services", its URL would be %1$s<wbr />/services<wbr />/pricing.'
          ),
          (0, import_url6.filterURLForDisplay)(homeUrl).replace(
            /([/.])/g,
            "<wbr />$1"
          )
        ),
        {
          wbr: /* @__PURE__ */ (0, import_jsx_runtime145.jsx)("wbr", {})
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime145.jsx)("p", { children: (0, import_element50.createInterpolateElement)(
        (0, import_i18n23.__)(
          "They also show up as sub-items in the default navigation menu. <a>Learn more.</a>"
        ),
        {
          a: /* @__PURE__ */ (0, import_jsx_runtime145.jsx)(
            import_components6.ExternalLink,
            {
              href: (0, import_i18n23.__)(
                "https://wordpress.org/documentation/article/page-post-settings-sidebar/#page-attributes"
              ),
              children: void 0
            }
          )
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime145.jsx)(
        PageAttributesParent,
        {
          data,
          onChangeControl
        }
      )
    ] }) });
  };

  // packages/fields/build-module/fields/parent/parent-view.mjs
  var import_data14 = __toESM(require_data(), 1);
  var import_core_data10 = __toESM(require_core_data(), 1);
  var import_i18n24 = __toESM(require_i18n(), 1);
  var import_jsx_runtime146 = __toESM(require_jsx_runtime(), 1);
  var ParentView = ({
    item
  }) => {
    const parent = (0, import_data14.useSelect)(
      (select9) => {
        const { getEntityRecord } = select9(import_core_data10.store);
        return item?.parent ? getEntityRecord("postType", item.type, item.parent) : null;
      },
      [item.parent, item.type]
    );
    if (parent) {
      return /* @__PURE__ */ (0, import_jsx_runtime146.jsx)(import_jsx_runtime146.Fragment, { children: getTitleWithFallbackName(parent) });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime146.jsx)(import_jsx_runtime146.Fragment, { children: (0, import_i18n24.__)("None") });
  };

  // packages/fields/build-module/fields/parent/index.mjs
  var parentField = {
    id: "parent",
    type: "text",
    label: (0, import_i18n25.__)("Parent"),
    Edit: ParentEdit,
    render: ParentView,
    enableSorting: true,
    filterBy: false
  };
  var parent_default = parentField;

  // packages/fields/build-module/fields/password/index.mjs
  var import_i18n27 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/password/edit.mjs
  var import_components7 = __toESM(require_components(), 1);
  var import_element51 = __toESM(require_element(), 1);
  var import_i18n26 = __toESM(require_i18n(), 1);
  var import_jsx_runtime147 = __toESM(require_jsx_runtime(), 1);
  function PasswordEdit({
    data,
    onChange,
    field
  }) {
    const [showPassword, setShowPassword] = (0, import_element51.useState)(
      !!field.getValue({ item: data })
    );
    const handleTogglePassword = (value) => {
      setShowPassword(value);
      if (!value) {
        onChange({ password: "" });
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime147.jsxs)(
      import_components7.__experimentalVStack,
      {
        as: "fieldset",
        spacing: 4,
        className: "fields-controls__password",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
            import_components7.CheckboxControl,
            {
              label: (0, import_i18n26.__)("Password protected"),
              help: (0, import_i18n26.__)("Only visible to those who know the password"),
              checked: showPassword,
              onChange: handleTogglePassword
            }
          ),
          showPassword && /* @__PURE__ */ (0, import_jsx_runtime147.jsx)("div", { className: "fields-controls__password-input", children: /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
            import_components7.TextControl,
            {
              label: (0, import_i18n26.__)("Password"),
              onChange: (value) => onChange({
                password: value
              }),
              value: field.getValue({ item: data }) || "",
              placeholder: (0, import_i18n26.__)("Use a secure password"),
              type: "text",
              maxLength: 255
            }
          ) })
        ]
      }
    );
  }
  var edit_default = PasswordEdit;

  // packages/fields/build-module/fields/password/index.mjs
  var passwordField = {
    id: "password",
    type: "text",
    label: (0, import_i18n27.__)("Password"),
    Edit: edit_default,
    enableSorting: false,
    enableHiding: false,
    isVisible: (item) => item.status !== "private",
    filterBy: false
  };
  var password_default = passwordField;

  // packages/fields/build-module/fields/status/index.mjs
  var import_i18n29 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/status/status-view.mjs
  var import_components8 = __toESM(require_components(), 1);

  // packages/fields/build-module/fields/status/status-elements.mjs
  var import_i18n28 = __toESM(require_i18n(), 1);
  var STATUSES = [
    {
      value: "draft",
      label: (0, import_i18n28.__)("Draft"),
      icon: drafts_default,
      description: (0, import_i18n28.__)("Not ready to publish.")
    },
    {
      value: "future",
      label: (0, import_i18n28.__)("Scheduled"),
      icon: scheduled_default,
      description: (0, import_i18n28.__)("Publish automatically on a chosen date.")
    },
    {
      value: "pending",
      label: (0, import_i18n28.__)("Pending Review"),
      icon: pending_default,
      description: (0, import_i18n28.__)("Waiting for review before publishing.")
    },
    {
      value: "private",
      label: (0, import_i18n28.__)("Private"),
      icon: not_allowed_default,
      description: (0, import_i18n28.__)("Only visible to site admins and editors.")
    },
    {
      value: "publish",
      label: (0, import_i18n28.__)("Published"),
      icon: published_default,
      description: (0, import_i18n28.__)("Visible to everyone.")
    },
    { value: "trash", label: (0, import_i18n28.__)("Trash"), icon: trash_default }
  ];
  var status_elements_default = STATUSES;

  // packages/fields/build-module/fields/status/status-view.mjs
  var import_jsx_runtime148 = __toESM(require_jsx_runtime(), 1);
  function StatusView({ item, field }) {
    const currentStatus = field.getValue({ item });
    const status = status_elements_default.find(({ value }) => value === currentStatus);
    const label = status?.label || currentStatus;
    const icon = status?.icon;
    return /* @__PURE__ */ (0, import_jsx_runtime148.jsxs)(import_components8.__experimentalHStack, { alignment: "left", spacing: 0, children: [
      icon && /* @__PURE__ */ (0, import_jsx_runtime148.jsx)("div", { className: "fields-controls__status-icon", children: /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(import_components8.Icon, { icon }) }),
      /* @__PURE__ */ (0, import_jsx_runtime148.jsx)("span", { children: label })
    ] });
  }
  var status_view_default = StatusView;

  // packages/fields/build-module/fields/status/index.mjs
  var OPERATOR_IS_ANY = "isAny";
  var statusField = {
    label: (0, import_i18n29.__)("Status"),
    id: "status",
    type: "text",
    elements: status_elements_default,
    // An auto-draft is a draft that hasn't been saved yet, so treat it as
    // one for display, selection, and filtering.
    getValue: ({ item }) => item.status === "auto-draft" ? "draft" : item.status,
    render: status_view_default,
    Edit: "radio",
    enableSorting: false,
    filterBy: {
      operators: [OPERATOR_IS_ANY]
    }
  };
  var status_default = statusField;

  // packages/fields/build-module/fields/comment-status/index.mjs
  var import_i18n30 = __toESM(require_i18n(), 1);
  var commentStatusField = {
    id: "comment_status",
    label: (0, import_i18n30.__)("Comments"),
    type: "text",
    Edit: "radio",
    enableSorting: false,
    enableHiding: false,
    filterBy: false,
    elements: [
      {
        value: "open",
        label: (0, import_i18n30.__)("Open"),
        description: (0, import_i18n30.__)("Visitors can add new comments and replies.")
      },
      {
        value: "closed",
        label: (0, import_i18n30.__)("Closed"),
        description: (0, import_i18n30.__)(
          "Visitors cannot add new comments or replies. Existing comments remain visible."
        )
      }
    ]
  };
  var comment_status_default = commentStatusField;

  // packages/fields/build-module/fields/ping-status/index.mjs
  var import_i18n31 = __toESM(require_i18n(), 1);
  var import_components9 = __toESM(require_components(), 1);
  var import_jsx_runtime149 = __toESM(require_jsx_runtime(), 1);
  function PingStatusEdit({
    data,
    onChange
  }) {
    const pingStatus = data?.ping_status ?? "open";
    const onTogglePingback = (checked) => {
      onChange({
        ...data,
        ping_status: checked ? "open" : "closed"
      });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime149.jsx)(
      import_components9.CheckboxControl,
      {
        label: (0, import_i18n31.__)("Enable pingbacks & trackbacks"),
        checked: pingStatus === "open",
        onChange: onTogglePingback,
        help: /* @__PURE__ */ (0, import_jsx_runtime149.jsx)(
          import_components9.ExternalLink,
          {
            href: (0, import_i18n31.__)(
              "https://wordpress.org/documentation/article/trackbacks-and-pingbacks/"
            ),
            children: (0, import_i18n31.__)("Learn more about pingbacks & trackbacks")
          }
        )
      }
    );
  }
  var pingStatusField = {
    id: "ping_status",
    label: (0, import_i18n31.__)("Trackbacks & Pingbacks"),
    type: "text",
    Edit: PingStatusEdit,
    enableSorting: false,
    enableHiding: false,
    filterBy: false,
    elements: [
      {
        value: "open",
        label: (0, import_i18n31.__)("Allow"),
        description: (0, import_i18n31.__)(
          "Allow link notifications from other blogs (pingbacks and trackbacks) on new articles."
        )
      },
      {
        value: "closed",
        label: (0, import_i18n31.__)("Don't allow"),
        description: (0, import_i18n31.__)(
          "Don't allow link notifications from other blogs (pingbacks and trackbacks) on new articles."
        )
      }
    ]
  };
  var ping_status_default = pingStatusField;

  // packages/fields/build-module/fields/discussion/index.mjs
  var import_i18n32 = __toESM(require_i18n(), 1);
  var discussionField = {
    id: "discussion",
    label: (0, import_i18n32.__)("Discussion"),
    type: "text",
    render: ({ item }) => {
      const commentsOpen = item.comment_status === "open";
      const pingsOpen = item.ping_status === "open";
      if (commentsOpen && pingsOpen) {
        return (0, import_i18n32.__)("Open");
      }
      if (commentsOpen && !pingsOpen) {
        return (0, import_i18n32.__)("Comments only");
      }
      if (!commentsOpen && pingsOpen) {
        return (0, import_i18n32.__)("Pings only");
      }
      return (0, import_i18n32.__)("Closed");
    },
    filterBy: false
  };
  var discussion_default = discussionField;

  // packages/fields/build-module/fields/date/index.mjs
  var import_i18n34 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/date/date-view.mjs
  var import_i18n33 = __toESM(require_i18n(), 1);
  var import_element52 = __toESM(require_element(), 1);
  var import_date2 = __toESM(require_date(), 1);
  var import_jsx_runtime150 = __toESM(require_jsx_runtime(), 1);
  var getFormattedDate = (dateToDisplay) => (0, import_date2.dateI18n)(
    (0, import_date2.getSettings)().formats.datetimeAbbreviated,
    (0, import_date2.getDate)(dateToDisplay)
  );
  var DateView = ({ item }) => {
    const isDraftOrPrivate = ["draft", "private"].includes(
      item.status ?? ""
    );
    if (isDraftOrPrivate) {
      return (0, import_element52.createInterpolateElement)(
        (0, import_i18n33.sprintf)(
          /* translators: %s: page creation or modification date. */
          (0, import_i18n33.__)("<span>Modified: <time>%s</time></span>"),
          getFormattedDate(item.date ?? null)
        ),
        {
          span: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)("span", {}),
          time: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)("time", {})
        }
      );
    }
    const isScheduled = item.status === "future";
    if (isScheduled) {
      return (0, import_element52.createInterpolateElement)(
        (0, import_i18n33.sprintf)(
          /* translators: %s: page creation date */
          (0, import_i18n33.__)("<span>Scheduled: <time>%s</time></span>"),
          getFormattedDate(item.date ?? null)
        ),
        {
          span: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)("span", {}),
          time: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)("time", {})
        }
      );
    }
    const isPublished = item.status === "publish";
    if (isPublished) {
      return (0, import_element52.createInterpolateElement)(
        (0, import_i18n33.sprintf)(
          /* translators: %s: page creation time */
          (0, import_i18n33.__)("<span>Published: <time>%s</time></span>"),
          getFormattedDate(item.date ?? null)
        ),
        {
          span: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)("span", {}),
          time: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)("time", {})
        }
      );
    }
    const dateToDisplay = (0, import_date2.getDate)(item.modified ?? null) > (0, import_date2.getDate)(item.date ?? null) ? item.modified : item.date;
    const isPending = item.status === "pending";
    if (isPending) {
      return (0, import_element52.createInterpolateElement)(
        (0, import_i18n33.sprintf)(
          /* translators: %s: page creation or modification date. */
          (0, import_i18n33.__)("<span>Modified: <time>%s</time></span>"),
          getFormattedDate(dateToDisplay ?? null)
        ),
        {
          span: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)("span", {}),
          time: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)("time", {})
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime150.jsx)("time", { children: getFormattedDate(item.date ?? null) });
  };
  var date_view_default = DateView;

  // packages/fields/build-module/fields/date/index.mjs
  var dateField = {
    id: "date",
    type: "datetime",
    label: (0, import_i18n34.__)("Date"),
    render: date_view_default,
    filterBy: {
      operators: ["before", "after"]
    }
  };
  var date_default = dateField;

  // packages/fields/build-module/fields/scheduled-date/index.mjs
  var import_i18n35 = __toESM(require_i18n(), 1);
  var scheduledDateField = {
    id: "scheduled_date",
    type: "datetime",
    label: (0, import_i18n35.__)("Scheduled Date"),
    getValue: ({ item }) => item.date,
    setValue: ({ value }) => ({ date: value }),
    isVisible: (item) => item.status === "future",
    Edit: {
      control: "datetime",
      compact: true
    },
    enableHiding: false,
    enableSorting: false,
    filterBy: false
  };
  var scheduled_date_default = scheduledDateField;

  // packages/fields/build-module/fields/last-edited/index.mjs
  var import_i18n37 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/last-edited/last-edited-date-view.mjs
  var import_i18n36 = __toESM(require_i18n(), 1);
  var import_date3 = __toESM(require_date(), 1);
  var import_jsx_runtime151 = __toESM(require_jsx_runtime(), 1);
  function LastEditedDateView({ item }) {
    if (!item.modified) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(Text, { children: (0, import_i18n36.sprintf)(
      // translators: %s: Human-readable time difference, e.g. "2 days ago".
      (0, import_i18n36.__)("Last edited %s."),
      (0, import_date3.humanTimeDiff)(item.modified)
    ) });
  }

  // packages/fields/build-module/fields/last-edited/index.mjs
  var lastEditedDateField = {
    id: "last_edited_date",
    type: "datetime",
    label: (0, import_i18n37.__)("Last edited"),
    render: LastEditedDateView,
    getValue: ({ item }) => item.modified,
    isVisible: (item) => !!item.modified,
    readOnly: true,
    enableHiding: false,
    enableSorting: false,
    filterBy: false
  };
  var last_edited_default = lastEditedDateField;

  // packages/fields/build-module/fields/author/index.mjs
  var import_i18n39 = __toESM(require_i18n(), 1);
  var import_data16 = __toESM(require_data(), 1);
  var import_core_data12 = __toESM(require_core_data(), 1);

  // packages/fields/build-module/fields/author/author-view.mjs
  var import_i18n38 = __toESM(require_i18n(), 1);
  var import_element53 = __toESM(require_element(), 1);
  var import_components10 = __toESM(require_components(), 1);
  var import_data15 = __toESM(require_data(), 1);
  var import_core_data11 = __toESM(require_core_data(), 1);
  var import_jsx_runtime152 = __toESM(require_jsx_runtime(), 1);
  function AuthorView({ item }) {
    const authorId = item?.author;
    const embeddedAuthorId = item?._embedded?.author?.[0]?.id;
    const shouldFetch = Boolean(
      authorId && (!embeddedAuthorId || authorId !== embeddedAuthorId)
    );
    const author = (0, import_data15.useSelect)(
      (select9) => {
        if (!shouldFetch) {
          return null;
        }
        const { getEntityRecord } = select9(import_core_data11.store);
        return authorId ? getEntityRecord("root", "user", authorId) : null;
      },
      [authorId, shouldFetch]
    );
    const text = author?.name || item?._embedded?.author?.[0]?.name;
    const imageUrl = author?.avatar_urls?.[48] || item?._embedded?.author?.[0]?.avatar_urls?.[48];
    const [isImageLoaded, setIsImageLoaded] = (0, import_element53.useState)(false);
    return /* @__PURE__ */ (0, import_jsx_runtime152.jsxs)(import_components10.__experimentalHStack, { alignment: "left", spacing: 0, children: [
      !!imageUrl && /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(
        "div",
        {
          className: clsx_default("fields-controls__author-avatar", {
            "is-loaded": isImageLoaded
          }),
          children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(
            "img",
            {
              onLoad: () => setIsImageLoaded(true),
              alt: (0, import_i18n38.__)("Author avatar"),
              src: imageUrl
            }
          )
        }
      ),
      !imageUrl && /* @__PURE__ */ (0, import_jsx_runtime152.jsx)("div", { className: "fields-controls__author-icon", children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(import_components10.Icon, { icon: comment_author_avatar_default }) }),
      /* @__PURE__ */ (0, import_jsx_runtime152.jsx)("span", { className: "fields-controls__author-name", children: text })
    ] });
  }
  var author_view_default = AuthorView;

  // packages/fields/build-module/fields/author/index.mjs
  var authorField = {
    label: (0, import_i18n39.__)("Author"),
    id: "author",
    type: "integer",
    getElements: async () => {
      const authors = await (0, import_data16.resolveSelect)(import_core_data12.store).getEntityRecords(
        "root",
        "user",
        {
          per_page: -1,
          who: "authors",
          _fields: "id,name",
          context: "view"
        }
      ) ?? [];
      return authors.map(({ id, name: name2 }) => ({
        value: id,
        label: name2
      }));
    },
    setValue: ({ value }) => ({ author: Number(value) }),
    render: author_view_default,
    sort: (a3, b3, direction) => {
      const nameA = a3._embedded?.author?.[0]?.name || "";
      const nameB = b3._embedded?.author?.[0]?.name || "";
      return direction === "asc" ? nameA.localeCompare(nameB) : nameB.localeCompare(nameA);
    },
    filterBy: {
      operators: ["isAny", "isNone"]
    }
  };
  var author_default = authorField;

  // packages/fields/build-module/fields/template-author/index.mjs
  var import_i18n40 = __toESM(require_i18n(), 1);
  var import_data18 = __toESM(require_data(), 1);
  var import_core_data14 = __toESM(require_core_data(), 1);

  // packages/fields/build-module/fields/template-author/view.mjs
  var import_element54 = __toESM(require_element(), 1);
  var import_data17 = __toESM(require_data(), 1);
  var import_core_data13 = __toESM(require_core_data(), 1);
  var import_jsx_runtime153 = __toESM(require_jsx_runtime(), 1);
  function getIconForSource(originalSource) {
    switch (originalSource) {
      case "theme":
        return layout_default;
      case "plugin":
        return plugins_default;
      case "site":
        return globe_default;
      default:
        return comment_author_avatar_default;
    }
  }
  function TemplateAuthorView({
    item
  }) {
    const [isImageLoaded, setIsImageLoaded] = (0, import_element54.useState)(false);
    const originalSource = item.original_source;
    const icon = getIconForSource(originalSource);
    const text = item.author_text;
    const authorId = item.author;
    const imageUrl = (0, import_data17.useSelect)(
      (select9) => {
        if (originalSource === "site") {
          const siteData = select9(import_core_data13.store).getEntityRecord("root", "__unstableBase");
          const logoId = siteData?.site_logo;
          if (!logoId) {
            return void 0;
          }
          return select9(import_core_data13.store).getEntityRecord("postType", "attachment", logoId)?.source_url;
        }
        if (originalSource !== "user" || !authorId) {
          return void 0;
        }
        return select9(import_core_data13.store).getUser(authorId)?.avatar_urls?.[48];
      },
      [originalSource, authorId]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime153.jsxs)(Stack, { direction: "row", align: "center", children: [
      imageUrl && /* @__PURE__ */ (0, import_jsx_runtime153.jsx)(
        "div",
        {
          className: clsx_default("fields-controls__author-avatar", {
            "is-loaded": isImageLoaded
          }),
          children: /* @__PURE__ */ (0, import_jsx_runtime153.jsx)(
            "img",
            {
              onLoad: () => setIsImageLoaded(true),
              alt: "",
              src: imageUrl
            }
          )
        }
      ),
      !imageUrl && /* @__PURE__ */ (0, import_jsx_runtime153.jsx)("div", { className: "fields-controls__author-icon", children: /* @__PURE__ */ (0, import_jsx_runtime153.jsx)(Icon, { icon }) }),
      /* @__PURE__ */ (0, import_jsx_runtime153.jsx)("span", { className: "fields-controls__author-name", children: text })
    ] });
  }

  // packages/fields/build-module/fields/template-author/index.mjs
  async function getAuthorElements(postType2) {
    const records = await (0, import_data18.resolveSelect)(import_core_data14.store).getEntityRecords(
      "postType",
      postType2,
      { per_page: -1, _fields: "id,author_text" }
    );
    const seen = /* @__PURE__ */ new Set();
    const elements2 = [];
    for (const record of records ?? []) {
      const value = record.author_text;
      if (value && !seen.has(value)) {
        seen.add(value);
        elements2.push({ value, label: value });
      }
    }
    return elements2;
  }
  var templateAuthorField = {
    label: (0, import_i18n40.__)("Author"),
    id: "author",
    getValue: ({ item }) => item.author_text,
    render: TemplateAuthorView,
    getElements: () => getAuthorElements("wp_template")
  };
  var templatePartAuthorField = {
    label: (0, import_i18n40.__)("Author"),
    id: "author",
    getValue: ({ item }) => item.author_text,
    render: TemplateAuthorView,
    enableSorting: false,
    filterBy: {
      isPrimary: true
    },
    getElements: () => getAuthorElements("wp_template_part")
  };

  // packages/fields/build-module/fields/notes/index.mjs
  var import_i18n41 = __toESM(require_i18n(), 1);
  var notesField = {
    id: "notesCount",
    label: (0, import_i18n41.__)("Notes"),
    type: "integer",
    enableSorting: false,
    filterBy: false
  };
  var notes_default = notesField;

  // packages/fields/build-module/fields/excerpt/index.mjs
  var import_html_entities6 = __toESM(require_html_entities(), 1);
  var import_i18n42 = __toESM(require_i18n(), 1);
  var import_components11 = __toESM(require_components(), 1);
  var import_jsx_runtime154 = __toESM(require_jsx_runtime(), 1);
  var excerptField = {
    id: "excerpt",
    type: "text",
    label: (0, import_i18n42.__)("Excerpt"),
    placeholder: (0, import_i18n42.__)("Add an excerpt"),
    description: /* @__PURE__ */ (0, import_jsx_runtime154.jsx)(
      import_components11.ExternalLink,
      {
        href: (0, import_i18n42.__)(
          "https://wordpress.org/documentation/article/page-post-settings-sidebar/#excerpt"
        ),
        children: (0, import_i18n42.__)("Learn more about manual excerpts")
      }
    ),
    render: ({ item }) => {
      let excerpt;
      if (typeof item.excerpt === "string") {
        excerpt = !!item.excerpt ? (0, import_html_entities6.decodeEntities)(item.excerpt) : (0, import_i18n42.__)("Add an excerpt");
      } else {
        excerpt = (0, import_html_entities6.decodeEntities)(item.excerpt?.raw || "");
      }
      return /* @__PURE__ */ (0, import_jsx_runtime154.jsx)(import_components11.__experimentalText, { align: "left", numberOfLines: 3, truncate: true, children: excerpt });
    },
    Edit: {
      control: "textarea",
      rows: 4
    },
    enableSorting: false,
    filterBy: false
  };
  var excerpt_default = excerptField;

  // packages/fields/build-module/fields/description/index.mjs
  var import_html_entities7 = __toESM(require_html_entities(), 1);
  var import_i18n43 = __toESM(require_i18n(), 1);
  var import_jsx_runtime155 = __toESM(require_jsx_runtime(), 1);
  var isCustomTemplate = (item) => item.source === "custom" && !item.has_theme_file && item.is_custom;
  var getValue = ({ item }) => (0, import_html_entities7.decodeEntities)(item.description || "");
  var render = ({ item }) => {
    const { description } = item;
    return description && /* @__PURE__ */ (0, import_jsx_runtime155.jsx)(Text, { children: (0, import_html_entities7.decodeEntities)(description) });
  };
  var descriptionField = {
    id: "description",
    type: "text",
    label: (0, import_i18n43.__)("Description"),
    placeholder: (0, import_i18n43.__)("Add a description"),
    getValue,
    render,
    Edit: {
      control: "textarea",
      rows: 4
    },
    isVisible: isCustomTemplate,
    enableSorting: false,
    filterBy: false,
    enableGlobalSearch: true
  };
  var readOnlyDescriptionField = {
    id: "description_readonly",
    type: "text",
    label: (0, import_i18n43.__)("Description"),
    getValue,
    render,
    readOnly: true,
    isVisible: (item) => !isCustomTemplate(item) && !!item.description,
    enableSorting: false,
    enableHiding: false,
    filterBy: false
  };
  var description_default = descriptionField;

  // packages/fields/build-module/fields/format/index.mjs
  var import_i18n44 = __toESM(require_i18n(), 1);
  var import_data19 = __toESM(require_data(), 1);
  var import_core_data15 = __toESM(require_core_data(), 1);
  var POST_FORMATS = [
    { id: "aside", caption: (0, import_i18n44.__)("Aside") },
    { id: "audio", caption: (0, import_i18n44.__)("Audio") },
    { id: "chat", caption: (0, import_i18n44.__)("Chat") },
    { id: "gallery", caption: (0, import_i18n44.__)("Gallery") },
    { id: "image", caption: (0, import_i18n44.__)("Image") },
    { id: "link", caption: (0, import_i18n44.__)("Link") },
    { id: "quote", caption: (0, import_i18n44.__)("Quote") },
    { id: "standard", caption: (0, import_i18n44.__)("Standard") },
    { id: "status", caption: (0, import_i18n44.__)("Status") },
    { id: "video", caption: (0, import_i18n44.__)("Video") }
  ].sort((a3, b3) => {
    const normalizedA = a3.caption.toUpperCase();
    const normalizedB = b3.caption.toUpperCase();
    if (normalizedA < normalizedB) {
      return -1;
    }
    if (normalizedA > normalizedB) {
      return 1;
    }
    return 0;
  });
  var formatField = {
    id: "format",
    label: (0, import_i18n44.__)("Format"),
    type: "text",
    Edit: "radio",
    enableSorting: false,
    enableHiding: false,
    filterBy: false,
    getElements: async () => {
      const themeSupports = await (0, import_data19.resolveSelect)(import_core_data15.store).getThemeSupports();
      return POST_FORMATS.filter(
        (f3) => themeSupports?.formats?.includes(
          f3.id
        )
      ).map((f3) => ({ value: f3.id, label: f3.caption }));
    }
  };
  var format_default = formatField;

  // packages/fields/build-module/fields/post-content-info/index.mjs
  var import_i18n46 = __toESM(require_i18n(), 1);

  // packages/fields/build-module/fields/post-content-info/post-content-info-view.mjs
  var import_components12 = __toESM(require_components(), 1);
  var import_i18n45 = __toESM(require_i18n(), 1);
  var import_wordcount = __toESM(require_wordcount(), 1);
  var import_date4 = __toESM(require_date(), 1);
  var import_element55 = __toESM(require_element(), 1);
  var import_jsx_runtime156 = __toESM(require_jsx_runtime(), 1);
  var AVERAGE_READING_RATE = 189;
  function PostContentInfoView({
    item
  }) {
    let content = "";
    if (typeof item.content === "string") {
      content = item.content;
    } else if (typeof item.content === "function") {
      content = item.content(item);
    }
    const wordCountType = (0, import_i18n45._x)(
      "words",
      "Word count type. Do not translate!"
    );
    const wordsCounted = (0, import_element55.useMemo)(
      () => content ? (0, import_wordcount.count)(content, wordCountType) : 0,
      [content, wordCountType]
    );
    const modified = item.modified;
    if (!wordsCounted && !modified) {
      return null;
    }
    let contentInfoText;
    if (wordsCounted) {
      const readingTime = Math.round(wordsCounted / AVERAGE_READING_RATE);
      const wordsCountText = (0, import_i18n45.sprintf)(
        // translators: %s: the number of words in the post.
        (0, import_i18n45._n)("%s word", "%s words", wordsCounted),
        wordsCounted.toLocaleString()
      );
      const minutesText = readingTime <= 1 ? (0, import_i18n45.__)("1 minute") : (0, import_i18n45.sprintf)(
        /* translators: %s: the number of minutes to read the post. */
        (0, import_i18n45._n)("%s minute", "%s minutes", readingTime),
        readingTime.toLocaleString()
      );
      contentInfoText = (0, import_i18n45.sprintf)(
        /* translators: 1: How many words a post has. 2: the number of minutes to read the post (e.g. 130 words, 2 minutes read time.) */
        (0, import_i18n45.__)("%1$s, %2$s read time."),
        wordsCountText,
        minutesText
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime156.jsxs)(import_components12.__experimentalVStack, { spacing: 1, children: [
      contentInfoText && /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(import_components12.__experimentalText, { variant: "muted", children: contentInfoText }),
      modified && /* @__PURE__ */ (0, import_jsx_runtime156.jsx)(import_components12.__experimentalText, { variant: "muted", children: (0, import_i18n45.sprintf)(
        // translators: %s: Human-readable time difference, e.g. "2 days ago".
        (0, import_i18n45.__)("Last edited %s."),
        (0, import_date4.humanTimeDiff)(modified)
      ) })
    ] });
  }

  // packages/fields/build-module/fields/post-content-info/index.mjs
  var postContentInfoField = {
    label: (0, import_i18n46.__)("Post content information"),
    id: "post-content-info",
    type: "text",
    readOnly: true,
    render: PostContentInfoView,
    enableSorting: false,
    enableHiding: false,
    filterBy: false
  };
  var post_content_info_default = postContentInfoField;

  // packages/fields/build-module/fields/sticky/index.mjs
  var import_i18n47 = __toESM(require_i18n(), 1);
  var stickyField = {
    id: "sticky",
    type: "boolean",
    label: (0, import_i18n47.__)("Sticky"),
    description: (0, import_i18n47.__)("Pin this post to the top of the blog."),
    enableSorting: false,
    enableHiding: false,
    isVisible: (item) => !!item._links?.["wp:action-sticky"],
    filterBy: false
  };
  var sticky_default = stickyField;

  // packages/fields/build-module/fields/posts-per-page/index.mjs
  var import_i18n48 = __toESM(require_i18n(), 1);
  var postsPerPageField = {
    id: "posts_per_page",
    type: "integer",
    label: (0, import_i18n48.__)("Posts per page"),
    description: (0, import_i18n48.__)(
      "Set the default number of posts to display on blog pages, including categories and tags. Some templates may override this setting."
    ),
    getValue: ({ item }) => item.posts_per_page ?? 1,
    setValue: ({ value }) => ({ posts_per_page: value }),
    isValid: { min: 1 },
    enableSorting: false,
    enableHiding: false,
    filterBy: false
  };
  var posts_per_page_default = postsPerPageField;

  // packages/fields/build-module/fields/site-discussion/index.mjs
  var import_i18n49 = __toESM(require_i18n(), 1);
  var siteDiscussionField = {
    id: "default_comment_status",
    type: "text",
    label: (0, import_i18n49.__)("Discussion"),
    Edit: "radio",
    getValue: ({ item }) => item.default_comment_status || "",
    setValue: ({ value }) => ({
      default_comment_status: value || null
    }),
    render: ({ item }) => {
      return item.default_comment_status === "open" ? (0, import_i18n49.__)("Comments open") : (0, import_i18n49.__)("Comments closed");
    },
    elements: [
      {
        value: "open",
        label: (0, import_i18n49.__)("Open"),
        description: (0, import_i18n49.__)("Visitors can add new comments and replies.")
      },
      {
        value: "",
        label: (0, import_i18n49.__)("Closed"),
        description: (0, import_i18n49.__)(
          "Visitors cannot add new comments or replies. Existing comments remain visible."
        )
      }
    ],
    enableSorting: false,
    enableHiding: false,
    filterBy: false
  };
  var site_discussion_default = siteDiscussionField;

  // packages/fields/build-module/fields/posts-page-title/index.mjs
  var import_i18n50 = __toESM(require_i18n(), 1);
  var postsPageTitleField = {
    id: "posts_page_title",
    type: "text",
    label: (0, import_i18n50.__)("Blog title"),
    description: (0, import_i18n50.__)(
      "Set the Posts Page title. Appears in search results, and when the page is shared on social media."
    ),
    getValue: ({ item }) => {
      const title = item.title;
      if (typeof title === "string") {
        return title;
      }
      return title?.raw ?? "";
    },
    setValue: ({ value }) => ({ title: value }),
    enableSorting: false,
    enableHiding: false,
    filterBy: false
  };
  var posts_page_title_default = postsPageTitleField;

  // packages/fields/build-module/actions/view-post.mjs
  var import_i18n51 = __toESM(require_i18n(), 1);
  var viewPost = {
    id: "view-post",
    label: (0, import_i18n51._x)("View", "verb"),
    isPrimary: true,
    icon: external_default,
    isEligible(post2) {
      return post2.status !== "trash";
    },
    callback(posts, { onActionPerformed }) {
      const post2 = posts[0];
      window.open(post2?.link, "_blank");
      if (onActionPerformed) {
        onActionPerformed(posts);
      }
    }
  };
  var view_post_default = viewPost;

  // packages/fields/build-module/actions/reorder-page.mjs
  var import_data20 = __toESM(require_data(), 1);
  var import_core_data16 = __toESM(require_core_data(), 1);
  var import_i18n52 = __toESM(require_i18n(), 1);
  var import_notices3 = __toESM(require_notices(), 1);
  var import_element56 = __toESM(require_element(), 1);
  var import_components13 = __toESM(require_components(), 1);
  var import_jsx_runtime157 = __toESM(require_jsx_runtime(), 1);
  function isItemValid(item) {
    return typeof item.menu_order === "number" && Number.isInteger(item.menu_order);
  }
  function ReorderModal({
    items,
    closeModal: closeModal2,
    onActionPerformed
  }) {
    const [item, setItem] = (0, import_element56.useState)(items[0]);
    const { editEntityRecord, saveEditedEntityRecord } = (0, import_data20.useDispatch)(import_core_data16.store);
    const { createSuccessNotice, createErrorNotice } = (0, import_data20.useDispatch)(import_notices3.store);
    const isValid2 = isItemValid(item);
    async function onOrder(event) {
      event.preventDefault();
      if (!isValid2) {
        return;
      }
      try {
        await editEntityRecord("postType", item.type, item.id, {
          menu_order: item.menu_order
        });
        closeModal2?.();
        await saveEditedEntityRecord("postType", item.type, item.id, {
          throwOnError: true
        });
        createSuccessNotice((0, import_i18n52.__)("Order updated."), {
          type: "snackbar"
        });
        onActionPerformed?.(items);
      } catch (error2) {
        const typedError = error2;
        const errorMessage = typedError.message && typedError.code !== "unknown_error" ? typedError.message : (0, import_i18n52.__)("An error occurred while updating the order");
        createErrorNotice(errorMessage, {
          type: "snackbar"
        });
      }
    }
    return /* @__PURE__ */ (0, import_jsx_runtime157.jsx)("form", { onSubmit: onOrder, children: /* @__PURE__ */ (0, import_jsx_runtime157.jsxs)(import_components13.__experimentalVStack, { spacing: "5", children: [
      /* @__PURE__ */ (0, import_jsx_runtime157.jsx)("div", { children: (0, import_i18n52.__)(
        "Determines the order of pages. Pages with the same order value are sorted alphabetically. Negative order values are supported."
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime157.jsx)(
        import_components13.__experimentalInputControl,
        {
          label: (0, import_i18n52.__)("Order"),
          type: "number",
          value: typeof item.menu_order === "number" && Number.isInteger(item.menu_order) ? String(item.menu_order) : "",
          onChange: (value) => {
            const parsed = parseInt(value, 10);
            setItem({
              ...item,
              menu_order: isNaN(parsed) ? void 0 : parsed
            });
          }
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime157.jsxs)(import_components13.__experimentalHStack, { justify: "right", children: [
        /* @__PURE__ */ (0, import_jsx_runtime157.jsx)(
          import_components13.Button,
          {
            __next40pxDefaultSize: true,
            variant: "tertiary",
            onClick: () => {
              closeModal2?.();
            },
            children: (0, import_i18n52.__)("Cancel")
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime157.jsx)(
          import_components13.Button,
          {
            __next40pxDefaultSize: true,
            variant: "primary",
            type: "submit",
            accessibleWhenDisabled: true,
            disabled: !isValid2,
            children: (0, import_i18n52.__)("Save")
          }
        )
      ] })
    ] }) });
  }
  var reorderPage = {
    id: "order-pages",
    label: (0, import_i18n52.__)("Order"),
    isEligible({ status }) {
      return status !== "trash";
    },
    modalFocusOnMount: "firstContentElement",
    RenderModal: ReorderModal
  };
  var reorder_page_default = reorderPage;

  // packages/fields/build-module/actions/duplicate-post.mjs
  var import_data21 = __toESM(require_data(), 1);
  var import_core_data17 = __toESM(require_core_data(), 1);
  var import_i18n53 = __toESM(require_i18n(), 1);
  var import_notices4 = __toESM(require_notices(), 1);
  var import_element57 = __toESM(require_element(), 1);
  var import_components14 = __toESM(require_components(), 1);
  var import_jsx_runtime158 = __toESM(require_jsx_runtime(), 1);
  var duplicatePost = {
    id: "duplicate-post",
    label: (0, import_i18n53._x)("Duplicate", "action label"),
    isEligible({ status }) {
      return status !== "trash";
    },
    modalFocusOnMount: "firstContentElement",
    RenderModal: ({ items, closeModal: closeModal2, onActionPerformed }) => {
      const [item, setItem] = (0, import_element57.useState)({
        ...items[0],
        title: (0, import_i18n53.sprintf)(
          /* translators: %s: Existing post title */
          (0, import_i18n53._x)("%s (Copy)", "post"),
          getItemTitle(items[0])
        )
      });
      const [isCreatingPage, setIsCreatingPage] = (0, import_element57.useState)(false);
      const { saveEntityRecord } = (0, import_data21.useDispatch)(import_core_data17.store);
      const { createSuccessNotice, createErrorNotice } = (0, import_data21.useDispatch)(import_notices4.store);
      async function createPage(event) {
        event.preventDefault();
        if (isCreatingPage) {
          return;
        }
        const isTemplate2 = item.type === "wp_template";
        const newItemObject = {
          status: isTemplate2 ? "publish" : "draft",
          title: item.title,
          slug: isTemplate2 ? item.slug : item.title || (0, import_i18n53.__)("No title"),
          comment_status: item.comment_status,
          content: typeof item.content === "string" ? item.content : item.content.raw,
          excerpt: typeof item.excerpt === "string" ? item.excerpt : item.excerpt?.raw,
          meta: item.meta,
          parent: item.parent,
          password: item.password,
          template: item.template,
          format: item.format,
          featured_media: item.featured_media,
          menu_order: item.menu_order,
          ping_status: item.ping_status
        };
        const assignablePropertiesPrefix = "wp:action-assign-";
        const assignableProperties = Object.keys(item?._links || {}).filter(
          (property) => property.startsWith(assignablePropertiesPrefix)
        ).map(
          (property) => property.slice(assignablePropertiesPrefix.length)
        );
        assignableProperties.forEach((property) => {
          if (item.hasOwnProperty(property)) {
            newItemObject[property] = item[property];
          }
        });
        setIsCreatingPage(true);
        try {
          const newItem = await saveEntityRecord(
            "postType",
            item.type,
            newItemObject,
            { throwOnError: true }
          );
          createSuccessNotice(
            (0, import_i18n53.sprintf)(
              // translators: %s: Title of the created post, e.g: "Hello world".
              (0, import_i18n53.__)('"%s" successfully created.'),
              getItemTitle(newItem)
            ),
            {
              id: "duplicate-post-action",
              type: "snackbar"
            }
          );
          if (onActionPerformed) {
            onActionPerformed([newItem]);
          }
        } catch (error2) {
          const typedError = error2;
          const errorMessage = typedError.message && typedError.code !== "unknown_error" ? typedError.message : (0, import_i18n53.__)("An error occurred while duplicating the page.");
          createErrorNotice(errorMessage, {
            type: "snackbar"
          });
        } finally {
          setIsCreatingPage(false);
          closeModal2?.();
        }
      }
      return /* @__PURE__ */ (0, import_jsx_runtime158.jsx)("form", { onSubmit: createPage, children: /* @__PURE__ */ (0, import_jsx_runtime158.jsxs)(import_components14.__experimentalVStack, { spacing: 3, children: [
        typeof item.id === "string" && /* @__PURE__ */ (0, import_jsx_runtime158.jsx)("div", { children: (0, import_i18n53.__)(
          "You are about to duplicate a bundled template. Changes will not be live until you activate the new template."
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime158.jsx)(
          import_components14.__experimentalInputControl,
          {
            label: (0, import_i18n53.__)("Title"),
            placeholder: (0, import_i18n53.__)("No title"),
            value: getItemTitle(item),
            onChange: (value) => setItem((prev) => ({
              ...prev,
              title: value || (0, import_i18n53.__)("No title")
            }))
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime158.jsxs)(import_components14.__experimentalHStack, { spacing: 2, justify: "end", children: [
          /* @__PURE__ */ (0, import_jsx_runtime158.jsx)(
            import_components14.Button,
            {
              variant: "tertiary",
              onClick: closeModal2,
              __next40pxDefaultSize: true,
              children: (0, import_i18n53.__)("Cancel")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime158.jsx)(
            import_components14.Button,
            {
              variant: "primary",
              type: "submit",
              isBusy: isCreatingPage,
              "aria-disabled": isCreatingPage,
              __next40pxDefaultSize: true,
              children: (0, import_i18n53._x)("Duplicate", "action label")
            }
          )
        ] })
      ] }) });
    }
  };
  var duplicate_post_default = duplicatePost;

  // packages/fields/build-module/actions/rename-post.mjs
  var import_data22 = __toESM(require_data(), 1);
  var import_core_data18 = __toESM(require_core_data(), 1);
  var import_i18n54 = __toESM(require_i18n(), 1);
  var import_element58 = __toESM(require_element(), 1);
  var import_patterns3 = __toESM(require_patterns(), 1);
  var import_components15 = __toESM(require_components(), 1);
  var import_notices5 = __toESM(require_notices(), 1);
  var import_jsx_runtime159 = __toESM(require_jsx_runtime(), 1);
  var { PATTERN_TYPES: PATTERN_TYPES3 } = unlock3(import_patterns3.privateApis);
  var renamePost = {
    id: "rename-post",
    label: (0, import_i18n54.__)("Rename"),
    modalFocusOnMount: "firstContentElement",
    isEligible(post2) {
      if (post2.status === "trash") {
        return false;
      }
      if (post2.type === "wp_template" && typeof post2.id === "string" && window?.__experimentalTemplateActivate) {
        return false;
      }
      const specialChecks = ["wp_template", "wp_template_part"];
      if (!window?.__experimentalTemplateActivate) {
        specialChecks.push("wp_template");
      }
      if (!specialChecks.includes(post2.type)) {
        return post2.permissions?.update;
      }
      if (isTemplate(post2) && !window?.__experimentalTemplateActivate) {
        return isTemplateRemovable(post2) && post2.is_custom && post2.permissions?.update;
      }
      if (isTemplatePart(post2)) {
        return post2.source === "custom" && !post2?.has_theme_file && post2.permissions?.update;
      }
      return post2.type === PATTERN_TYPES3.user && post2.permissions?.update;
    },
    RenderModal: ({ items, closeModal: closeModal2, onActionPerformed }) => {
      const [item] = items;
      const [title, setTitle] = (0, import_element58.useState)(() => getItemTitle(item, ""));
      const { editEntityRecord, saveEditedEntityRecord } = (0, import_data22.useDispatch)(import_core_data18.store);
      const { createSuccessNotice, createErrorNotice } = (0, import_data22.useDispatch)(import_notices5.store);
      async function onRename(event) {
        event.preventDefault();
        try {
          await editEntityRecord("postType", item.type, item.id, {
            title
          });
          setTitle("");
          closeModal2?.();
          await saveEditedEntityRecord("postType", item.type, item.id, {
            throwOnError: true
          });
          createSuccessNotice((0, import_i18n54.__)("Name updated"), {
            type: "snackbar"
          });
          onActionPerformed?.(items);
        } catch (error2) {
          const typedError = error2;
          const errorMessage = typedError.message && typedError.code !== "unknown_error" ? typedError.message : (0, import_i18n54.__)("An error occurred while updating the name");
          createErrorNotice(errorMessage, { type: "snackbar" });
        }
      }
      return /* @__PURE__ */ (0, import_jsx_runtime159.jsx)("form", { onSubmit: onRename, children: /* @__PURE__ */ (0, import_jsx_runtime159.jsxs)(import_components15.__experimentalVStack, { spacing: "5", children: [
        /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
          import_components15.TextControl,
          {
            label: (0, import_i18n54.__)("Name"),
            value: title,
            onChange: setTitle,
            required: true
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime159.jsxs)(import_components15.__experimentalHStack, { justify: "right", children: [
          /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
            import_components15.Button,
            {
              __next40pxDefaultSize: true,
              variant: "tertiary",
              onClick: () => {
                closeModal2?.();
              },
              children: (0, import_i18n54.__)("Cancel")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime159.jsx)(
            import_components15.Button,
            {
              __next40pxDefaultSize: true,
              variant: "primary",
              type: "submit",
              children: (0, import_i18n54.__)("Save")
            }
          )
        ] })
      ] }) });
    }
  };
  var rename_post_default = renamePost;

  // packages/fields/build-module/actions/reset-post.mjs
  var import_data23 = __toESM(require_data(), 1);
  var import_core_data19 = __toESM(require_core_data(), 1);
  var import_i18n55 = __toESM(require_i18n(), 1);
  var import_notices6 = __toESM(require_notices(), 1);
  var import_element59 = __toESM(require_element(), 1);
  var import_blocks4 = __toESM(require_blocks(), 1);
  var import_components16 = __toESM(require_components(), 1);
  var import_url7 = __toESM(require_url(), 1);
  var import_api_fetch = __toESM(require_api_fetch(), 1);
  var import_jsx_runtime160 = __toESM(require_jsx_runtime(), 1);
  var isTemplateRevertable2 = (templateOrTemplatePart) => {
    if (!templateOrTemplatePart) {
      return false;
    }
    return templateOrTemplatePart.source === "custom" && (Boolean(templateOrTemplatePart?.plugin) || templateOrTemplatePart?.has_theme_file);
  };
  var revertTemplate = async (template2, { allowUndo = true } = {}) => {
    const noticeId = "edit-site-template-reverted";
    (0, import_data23.dispatch)(import_notices6.store).removeNotice(noticeId);
    if (!isTemplateRevertable2(template2)) {
      (0, import_data23.dispatch)(import_notices6.store).createErrorNotice(
        (0, import_i18n55.__)("This template is not revertable."),
        {
          type: "snackbar"
        }
      );
      return;
    }
    try {
      const templateEntityConfig = (0, import_data23.select)(import_core_data19.store).getEntityConfig(
        "postType",
        template2.type
      );
      if (!templateEntityConfig) {
        (0, import_data23.dispatch)(import_notices6.store).createErrorNotice(
          (0, import_i18n55.__)(
            "The editor has encountered an unexpected error. Please reload."
          ),
          { type: "snackbar" }
        );
        return;
      }
      const fileTemplatePath = (0, import_url7.addQueryArgs)(
        `${templateEntityConfig.baseURL}/${template2.id}`,
        { context: "edit", source: template2.origin }
      );
      const fileTemplate = await (0, import_api_fetch.default)({
        path: fileTemplatePath
      });
      if (!fileTemplate) {
        (0, import_data23.dispatch)(import_notices6.store).createErrorNotice(
          (0, import_i18n55.__)(
            "The editor has encountered an unexpected error. Please reload."
          ),
          { type: "snackbar" }
        );
        return;
      }
      const serializeBlocks = ({ blocks: blocksForSerialization = [] }) => (0, import_blocks4.__unstableSerializeAndClean)(blocksForSerialization);
      const edited = (0, import_data23.select)(import_core_data19.store).getEditedEntityRecord(
        "postType",
        template2.type,
        template2.id
      );
      (0, import_data23.dispatch)(import_core_data19.store).editEntityRecord(
        "postType",
        template2.type,
        template2.id,
        {
          content: serializeBlocks,
          // Required to make the `undo` behave correctly.
          blocks: edited.blocks,
          // Required to revert the blocks in the editor.
          source: "custom"
          // required to avoid turning the editor into a dirty state
        },
        {
          undoIgnore: true
          // Required to merge this edit with the last undo level.
        }
      );
      const blocks = (0, import_blocks4.parse)(fileTemplate?.content?.raw);
      (0, import_data23.dispatch)(import_core_data19.store).editEntityRecord(
        "postType",
        template2.type,
        fileTemplate.id,
        {
          content: serializeBlocks,
          blocks,
          source: "theme"
        }
      );
      if (allowUndo) {
        const undoRevert = () => {
          (0, import_data23.dispatch)(import_core_data19.store).editEntityRecord(
            "postType",
            template2.type,
            edited.id,
            {
              content: serializeBlocks,
              blocks: edited.blocks,
              source: "custom"
            }
          );
        };
        (0, import_data23.dispatch)(import_notices6.store).createSuccessNotice(
          (0, import_i18n55.__)("Template reset."),
          {
            type: "snackbar",
            id: noticeId,
            actions: [
              {
                label: (0, import_i18n55.__)("Undo"),
                onClick: undoRevert
              }
            ]
          }
        );
      }
    } catch (error2) {
      const errorMessage = error2.message && error2.code !== "unknown_error" ? error2.message : (0, import_i18n55.__)("Template revert failed. Please reload.");
      (0, import_data23.dispatch)(import_notices6.store).createErrorNotice(errorMessage, {
        type: "snackbar"
      });
    }
  };
  var resetPostAction = {
    id: "reset-post",
    label: (0, import_i18n55.__)("Reset"),
    isEligible: (item) => {
      if (window?.__experimentalTemplateActivate) {
        return item.type === "wp_template_part" && item?.source === "custom" && item?.has_theme_file;
      }
      return isTemplateOrTemplatePart(item) && item?.source === "custom" && (Boolean(item.type === "wp_template" && item?.plugin) || item?.has_theme_file);
    },
    icon: backup_default,
    supportsBulk: true,
    hideModalHeader: true,
    modalFocusOnMount: "firstContentElement",
    RenderModal: ({ items, closeModal: closeModal2, onActionPerformed }) => {
      const [isBusy, setIsBusy] = (0, import_element59.useState)(false);
      const { saveEditedEntityRecord } = (0, import_data23.useDispatch)(import_core_data19.store);
      const { createSuccessNotice, createErrorNotice } = (0, import_data23.useDispatch)(import_notices6.store);
      const onConfirm = async () => {
        try {
          for (const template2 of items) {
            await revertTemplate(template2, {
              allowUndo: false
            });
            await saveEditedEntityRecord(
              "postType",
              template2.type,
              template2.id
            );
          }
          createSuccessNotice(
            items.length > 1 ? (0, import_i18n55.sprintf)(
              /* translators: %d: The number of items. */
              (0, import_i18n55.__)("%d items reset."),
              items.length
            ) : (0, import_i18n55.sprintf)(
              /* translators: %s: The template/part's name. */
              (0, import_i18n55.__)('"%s" reset.'),
              getItemTitle(items[0])
            ),
            {
              type: "snackbar",
              id: "revert-template-action"
            }
          );
        } catch (error2) {
          let fallbackErrorMessage;
          if (items[0].type === "wp_template") {
            fallbackErrorMessage = items.length === 1 ? (0, import_i18n55.__)(
              "An error occurred while reverting the template."
            ) : (0, import_i18n55.__)(
              "An error occurred while reverting the templates."
            );
          } else {
            fallbackErrorMessage = items.length === 1 ? (0, import_i18n55.__)(
              "An error occurred while reverting the template part."
            ) : (0, import_i18n55.__)(
              "An error occurred while reverting the template parts."
            );
          }
          const typedError = error2;
          const errorMessage = typedError.message && typedError.code !== "unknown_error" ? typedError.message : fallbackErrorMessage;
          createErrorNotice(errorMessage, { type: "snackbar" });
        }
      };
      return /* @__PURE__ */ (0, import_jsx_runtime160.jsxs)(import_components16.__experimentalVStack, { spacing: "5", children: [
        /* @__PURE__ */ (0, import_jsx_runtime160.jsx)(import_components16.__experimentalText, { children: (0, import_i18n55.__)("Reset to default and clear all customizations?") }),
        /* @__PURE__ */ (0, import_jsx_runtime160.jsxs)(import_components16.__experimentalHStack, { justify: "right", children: [
          /* @__PURE__ */ (0, import_jsx_runtime160.jsx)(
            import_components16.Button,
            {
              __next40pxDefaultSize: true,
              variant: "tertiary",
              onClick: closeModal2,
              disabled: isBusy,
              accessibleWhenDisabled: true,
              children: (0, import_i18n55.__)("Cancel")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime160.jsx)(
            import_components16.Button,
            {
              __next40pxDefaultSize: true,
              variant: "primary",
              onClick: async () => {
                setIsBusy(true);
                await onConfirm();
                onActionPerformed?.(items);
                setIsBusy(false);
                closeModal2?.();
              },
              isBusy,
              disabled: isBusy,
              accessibleWhenDisabled: true,
              children: (0, import_i18n55.__)("Reset")
            }
          )
        ] })
      ] });
    }
  };
  var reset_post_default = resetPostAction;

  // packages/fields/build-module/actions/duplicate-pattern.mjs
  var import_i18n56 = __toESM(require_i18n(), 1);
  var import_patterns4 = __toESM(require_patterns(), 1);
  var import_jsx_runtime161 = __toESM(require_jsx_runtime(), 1);
  var { CreatePatternModalContents, useDuplicatePatternProps } = unlock3(import_patterns4.privateApis);
  var duplicatePattern = {
    id: "duplicate-pattern",
    label: (0, import_i18n56._x)("Duplicate", "action label"),
    isEligible: (item) => item.type !== "wp_template_part",
    modalHeader: (0, import_i18n56._x)("Duplicate pattern", "action label"),
    modalFocusOnMount: "firstContentElement",
    RenderModal: ({ items, closeModal: closeModal2 }) => {
      const [item] = items;
      const duplicatedProps = useDuplicatePatternProps({
        pattern: item,
        onSuccess: () => closeModal2?.()
      });
      return /* @__PURE__ */ (0, import_jsx_runtime161.jsx)(
        CreatePatternModalContents,
        {
          onClose: closeModal2,
          confirmLabel: (0, import_i18n56._x)("Duplicate", "action label"),
          ...duplicatedProps
        }
      );
    }
  };
  var duplicate_pattern_default = duplicatePattern;

  // node_modules/tslib/tslib.es6.mjs
  var __assign = function() {
    __assign = Object.assign || function __assign2(t4) {
      for (var s3, i3 = 1, n3 = arguments.length; i3 < n3; i3++) {
        s3 = arguments[i3];
        for (var p4 in s3) if (Object.prototype.hasOwnProperty.call(s3, p4)) t4[p4] = s3[p4];
      }
      return t4;
    };
    return __assign.apply(this, arguments);
  };

  // node_modules/lower-case/dist.es2015/index.js
  function lowerCase(str3) {
    return str3.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/upper-case-first/dist.es2015/index.js
  function upperCaseFirst(input) {
    return input.charAt(0).toUpperCase() + input.substr(1);
  }

  // node_modules/capital-case/dist.es2015/index.js
  function capitalCaseTransform(input) {
    return upperCaseFirst(input.toLowerCase());
  }
  function capitalCase(input, options) {
    if (options === void 0) {
      options = {};
    }
    return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options));
  }

  // 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));
  }

  // node_modules/client-zip/index.js
  "stream" in Blob.prototype || Object.defineProperty(Blob.prototype, "stream", { value() {
    return new Response(this).body;
  } }), "setBigUint64" in DataView.prototype || Object.defineProperty(DataView.prototype, "setBigUint64", { value(e3, n3, t4) {
    const i3 = Number(0xffffffffn & n3), r4 = Number(n3 >> 32n);
    this.setUint32(e3 + (t4 ? 0 : 4), i3, t4), this.setUint32(e3 + (t4 ? 4 : 0), r4, t4);
  } });
  var e2 = (e3) => new DataView(new ArrayBuffer(e3));
  var n2 = (e3) => new Uint8Array(e3.buffer || e3);
  var t2 = (e3) => new TextEncoder().encode(String(e3));
  var i2 = (e3) => Math.min(4294967295, Number(e3));
  var r3 = (e3) => Math.min(65535, Number(e3));
  function f2(e3, i3) {
    if (void 0 === i3 || i3 instanceof Date || (i3 = new Date(i3)), e3 instanceof File) return { isFile: 1, t: i3 || new Date(e3.lastModified), i: e3.stream() };
    if (e3 instanceof Response) return { isFile: 1, t: i3 || new Date(e3.headers.get("Last-Modified") || Date.now()), i: e3.body };
    if (void 0 === i3) i3 = /* @__PURE__ */ new Date();
    else if (isNaN(i3)) throw new Error("Invalid modification date.");
    if (void 0 === e3) return { isFile: 0, t: i3 };
    if ("string" == typeof e3) return { isFile: 1, t: i3, i: t2(e3) };
    if (e3 instanceof Blob) return { isFile: 1, t: i3, i: e3.stream() };
    if (e3 instanceof Uint8Array || e3 instanceof ReadableStream) return { isFile: 1, t: i3, i: e3 };
    if (e3 instanceof ArrayBuffer || ArrayBuffer.isView(e3)) return { isFile: 1, t: i3, i: n2(e3) };
    if (Symbol.asyncIterator in e3) return { isFile: 1, t: i3, i: o2(e3[Symbol.asyncIterator]()) };
    throw new TypeError("Unsupported input format.");
  }
  function o2(e3, n3 = e3) {
    return new ReadableStream({ async pull(n4) {
      let t4 = 0;
      for (; n4.desiredSize > t4; ) {
        const i3 = await e3.next();
        if (!i3.value) {
          n4.close();
          break;
        }
        {
          const e4 = a2(i3.value);
          n4.enqueue(e4), t4 += e4.byteLength;
        }
      }
    }, cancel(e4) {
      n3.throw?.(e4);
    } });
  }
  function a2(e3) {
    return "string" == typeof e3 ? t2(e3) : e3 instanceof Uint8Array ? e3 : n2(e3);
  }
  function s2(e3, i3, r4) {
    let [f3, o4] = (function(e4) {
      return e4 ? e4 instanceof Uint8Array ? [e4, 1] : ArrayBuffer.isView(e4) || e4 instanceof ArrayBuffer ? [n2(e4), 1] : [t2(e4), 0] : [void 0, 0];
    })(i3);
    if (e3 instanceof File) return { o: d2(f3 || t2(e3.name)), u: BigInt(e3.size), l: o4 };
    if (e3 instanceof Response) {
      const n3 = e3.headers.get("content-disposition"), i4 = n3 && n3.match(/;\s*filename\*?=["']?(.*?)["']?$/i), a3 = i4 && i4[1] || e3.url && new URL(e3.url).pathname.split("/").findLast(Boolean), s3 = a3 && decodeURIComponent(a3), u3 = r4 || +e3.headers.get("content-length");
      return { o: d2(f3 || t2(s3)), u: BigInt(u3), l: o4 };
    }
    return f3 = d2(f3, void 0 !== e3 || void 0 !== r4), "string" == typeof e3 ? { o: f3, u: BigInt(t2(e3).length), l: o4 } : e3 instanceof Blob ? { o: f3, u: BigInt(e3.size), l: o4 } : e3 instanceof ArrayBuffer || ArrayBuffer.isView(e3) ? { o: f3, u: BigInt(e3.byteLength), l: o4 } : { o: f3, u: u2(e3, r4), l: o4 };
  }
  function u2(e3, n3) {
    return n3 > -1 ? BigInt(n3) : e3 ? void 0 : 0n;
  }
  function d2(e3, n3 = 1) {
    if (!e3 || e3.every(((c6) => 47 === c6))) throw new Error("The file must have a name.");
    if (n3) for (; 47 === e3[e3.length - 1]; ) e3 = e3.subarray(0, -1);
    else 47 !== e3[e3.length - 1] && (e3 = new Uint8Array([...e3, 47]));
    return e3;
  }
  var l2 = new Uint32Array(256);
  for (let e3 = 0; e3 < 256; ++e3) {
    let n3 = e3;
    for (let e4 = 0; e4 < 8; ++e4) n3 = n3 >>> 1 ^ (1 & n3 && 3988292384);
    l2[e3] = n3;
  }
  function y2(e3, n3 = 0) {
    n3 ^= -1;
    for (var t4 = 0, i3 = e3.length; t4 < i3; t4++) n3 = n3 >>> 8 ^ l2[255 & n3 ^ e3[t4]];
    return (-1 ^ n3) >>> 0;
  }
  function w2(e3, n3, t4 = 0) {
    const i3 = e3.getSeconds() >> 1 | e3.getMinutes() << 5 | e3.getHours() << 11, r4 = e3.getDate() | e3.getMonth() + 1 << 5 | e3.getFullYear() - 1980 << 9;
    n3.setUint16(t4, i3, 1), n3.setUint16(t4 + 2, r4, 1);
  }
  function B({ o: e3, l: n3 }, t4) {
    return 8 * (!n3 || (t4 ?? (function(e4) {
      try {
        b2.decode(e4);
      } catch {
        return 0;
      }
      return 1;
    })(e3)));
  }
  var b2 = new TextDecoder("utf8", { fatal: 1 });
  function p3(t4, i3 = 0) {
    const r4 = e2(30);
    return r4.setUint32(0, 1347093252), r4.setUint32(4, 754976768 | i3), w2(t4.t, r4, 10), r4.setUint16(26, t4.o.length, 1), n2(r4);
  }
  async function* g2(e3) {
    let { i: n3 } = e3;
    if ("then" in n3 && (n3 = await n3), n3 instanceof Uint8Array) yield n3, e3.m = y2(n3, 0), e3.u = BigInt(n3.length);
    else {
      e3.u = 0n;
      const t4 = n3.getReader();
      for (; ; ) {
        const { value: n4, done: i3 } = await t4.read();
        if (i3) break;
        e3.m = y2(n4, e3.m), e3.u += BigInt(n4.length), yield n4;
      }
    }
  }
  function I(t4, r4) {
    const f3 = e2(16 + (r4 ? 8 : 0));
    return f3.setUint32(0, 1347094280), f3.setUint32(4, t4.isFile ? t4.m : 0, 1), r4 ? (f3.setBigUint64(8, t4.u, 1), f3.setBigUint64(16, t4.u, 1)) : (f3.setUint32(8, i2(t4.u), 1), f3.setUint32(12, i2(t4.u), 1)), n2(f3);
  }
  function v2(t4, r4, f3 = 0, o4 = 0) {
    const a3 = e2(46);
    return a3.setUint32(0, 1347092738), a3.setUint32(4, 755182848), a3.setUint16(8, 2048 | f3), w2(t4.t, a3, 12), a3.setUint32(16, t4.isFile ? t4.m : 0, 1), a3.setUint32(20, i2(t4.u), 1), a3.setUint32(24, i2(t4.u), 1), a3.setUint16(28, t4.o.length, 1), a3.setUint16(30, o4, 1), a3.setUint16(40, t4.isFile ? 33204 : 16893, 1), a3.setUint32(42, i2(r4), 1), n2(a3);
  }
  function h2(t4, i3, r4) {
    const f3 = e2(r4);
    return f3.setUint16(0, 1, 1), f3.setUint16(2, r4 - 4, 1), 16 & r4 && (f3.setBigUint64(4, t4.u, 1), f3.setBigUint64(12, t4.u, 1)), f3.setBigUint64(r4 - 8, i3, 1), n2(f3);
  }
  function D(e3) {
    return e3 instanceof File || e3 instanceof Response ? [[e3], [e3]] : [[e3.input, e3.name, e3.size], [e3.input, e3.lastModified]];
  }
  var S2 = (e3) => (function(e4) {
    let n3 = BigInt(22), t4 = 0n, i3 = 0;
    for (const r4 of e4) {
      if (!r4.o) throw new Error("Every file must have a non-empty name.");
      if (void 0 === r4.u) throw new Error(`Missing size for file "${new TextDecoder().decode(r4.o)}".`);
      const e5 = r4.u >= 0xffffffffn, f3 = t4 >= 0xffffffffn;
      t4 += BigInt(46 + r4.o.length + (e5 && 8)) + r4.u, n3 += BigInt(r4.o.length + 46 + (12 * f3 | 28 * e5)), i3 || (i3 = e5);
    }
    return (i3 || t4 >= 0xffffffffn) && (n3 += BigInt(76)), n3 + t4;
  })((function* (e4) {
    for (const n3 of e4) yield s2(...D(n3)[0]);
  })(e3));
  function A(e3, n3 = {}) {
    const t4 = { "Content-Type": "application/zip", "Content-Disposition": "attachment" };
    return ("bigint" == typeof n3.length || Number.isInteger(n3.length)) && n3.length > 0 && (t4["Content-Length"] = String(n3.length)), n3.metadata && (t4["Content-Length"] = String(S2(n3.metadata))), new Response(N2(e3, n3), { headers: t4 });
  }
  function N2(t4, a3 = {}) {
    const u3 = (function(e3) {
      const n3 = e3[Symbol.iterator in e3 ? Symbol.iterator : Symbol.asyncIterator]();
      return { async next() {
        const e4 = await n3.next();
        if (e4.done) return e4;
        const [t5, i3] = D(e4.value);
        return { done: 0, value: Object.assign(f2(...i3), s2(...t5)) };
      }, throw: n3.throw?.bind(n3), [Symbol.asyncIterator]() {
        return this;
      } };
    })(t4);
    return o2((async function* (t5, f3) {
      const o4 = [];
      let a4 = 0n, s3 = 0n, u4 = 0;
      for await (const e3 of t5) {
        const n3 = B(e3, f3.buffersAreUTF8);
        yield p3(e3, n3), yield new Uint8Array(e3.o), e3.isFile && (yield* g2(e3));
        const t6 = e3.u >= 0xffffffffn, i3 = 12 * (a4 >= 0xffffffffn) | 28 * t6;
        yield I(e3, t6), o4.push(v2(e3, a4, n3, i3)), o4.push(e3.o), i3 && o4.push(h2(e3, a4, i3)), t6 && (a4 += 8n), s3++, a4 += BigInt(46 + e3.o.length) + e3.u, u4 || (u4 = t6);
      }
      let d3 = 0n;
      for (const e3 of o4) yield e3, d3 += BigInt(e3.length);
      if (u4 || a4 >= 0xffffffffn) {
        const t6 = e2(76);
        t6.setUint32(0, 1347094022), t6.setBigUint64(4, BigInt(44), 1), t6.setUint32(12, 755182848), t6.setBigUint64(24, s3, 1), t6.setBigUint64(32, s3, 1), t6.setBigUint64(40, d3, 1), t6.setBigUint64(48, a4, 1), t6.setUint32(56, 1347094023), t6.setBigUint64(64, a4 + d3, 1), t6.setUint32(72, 1, 1), yield n2(t6);
      }
      const l3 = e2(22);
      l3.setUint32(0, 1347093766), l3.setUint16(8, r3(s3), 1), l3.setUint16(10, r3(s3), 1), l3.setUint32(12, i2(d3), 1), l3.setUint32(16, i2(a4), 1), yield n2(l3);
    })(u3, a3), u3);
  }

  // packages/fields/build-module/actions/export-pattern.mjs
  var import_blob2 = __toESM(require_blob(), 1);
  var import_i18n57 = __toESM(require_i18n(), 1);
  function getJsonFromItem(item) {
    return JSON.stringify(
      {
        __file: item.type,
        title: getItemTitle(item),
        content: typeof item.content === "string" ? item.content : item.content?.raw,
        syncStatus: item.wp_pattern_sync_status
      },
      null,
      2
    );
  }
  var exportPattern = {
    id: "export-pattern",
    label: (0, import_i18n57.__)("Export as JSON"),
    icon: download_default,
    supportsBulk: true,
    isEligible: (item) => item.type === "wp_block",
    callback: async (items) => {
      if (items.length === 1) {
        return (0, import_blob2.downloadBlob)(
          `${paramCase(
            getItemTitle(items[0]) || items[0].slug
          )}.json`,
          getJsonFromItem(items[0]),
          "application/json"
        );
      }
      const nameCount = {};
      const filesToZip = items.map((item) => {
        const name2 = paramCase(getItemTitle(item) || item.slug);
        nameCount[name2] = (nameCount[name2] || 0) + 1;
        return {
          name: `${name2 + (nameCount[name2] > 1 ? "-" + (nameCount[name2] - 1) : "")}.json`,
          lastModified: /* @__PURE__ */ new Date(),
          input: getJsonFromItem(item)
        };
      });
      return (0, import_blob2.downloadBlob)(
        (0, import_i18n57.__)("patterns-export") + ".zip",
        await A(filesToZip).blob(),
        "application/zip"
      );
    }
  };
  var export_pattern_default = exportPattern;

  // packages/fields/build-module/actions/view-post-revisions.mjs
  var import_url8 = __toESM(require_url(), 1);
  var import_i18n58 = __toESM(require_i18n(), 1);
  var viewPostRevisions = {
    id: "view-post-revisions",
    context: "list",
    label(items) {
      const revisionsCount = items[0]._links?.["version-history"]?.[0]?.count ?? 0;
      return (0, import_i18n58.sprintf)(
        /* translators: %d: number of revisions. */
        (0, import_i18n58.__)("View revisions (%d)"),
        revisionsCount
      );
    },
    isEligible(post2) {
      if (post2.status === "trash") {
        return false;
      }
      const lastRevisionId = post2?._links?.["predecessor-version"]?.[0]?.id ?? null;
      const revisionsCount = post2?._links?.["version-history"]?.[0]?.count ?? 0;
      return !!lastRevisionId && revisionsCount > 1;
    },
    callback(posts, { onActionPerformed }) {
      const post2 = posts[0];
      const href = (0, import_url8.addQueryArgs)("revision.php", {
        revision: post2?._links?.["predecessor-version"]?.[0]?.id
      });
      document.location.href = href;
      if (onActionPerformed) {
        onActionPerformed(posts);
      }
    }
  };
  var view_post_revisions_default = viewPostRevisions;

  // packages/fields/build-module/actions/permanently-delete-post.mjs
  var import_core_data20 = __toESM(require_core_data(), 1);
  var import_i18n59 = __toESM(require_i18n(), 1);
  var import_notices7 = __toESM(require_notices(), 1);
  var import_element60 = __toESM(require_element(), 1);
  var import_data24 = __toESM(require_data(), 1);
  var import_components17 = __toESM(require_components(), 1);
  var import_html_entities8 = __toESM(require_html_entities(), 1);
  var import_jsx_runtime162 = __toESM(require_jsx_runtime(), 1);
  var permanentlyDeletePost = {
    id: "permanently-delete",
    label: (0, import_i18n59.__)("Permanently delete"),
    supportsBulk: true,
    icon: trash_default,
    isEligible(item) {
      if (isTemplateOrTemplatePart(item) || item.type === "wp_block") {
        return false;
      }
      const { status, permissions } = item;
      return status === "trash" && permissions?.delete;
    },
    hideModalHeader: true,
    modalFocusOnMount: "firstContentElement",
    RenderModal: ({ items, closeModal: closeModal2, onActionPerformed }) => {
      const [isBusy, setIsBusy] = (0, import_element60.useState)(false);
      const { createSuccessNotice, createErrorNotice } = (0, import_data24.useDispatch)(import_notices7.store);
      const { deleteEntityRecord } = (0, import_data24.useDispatch)(import_core_data20.store);
      return /* @__PURE__ */ (0, import_jsx_runtime162.jsxs)(import_components17.__experimentalVStack, { spacing: "5", children: [
        /* @__PURE__ */ (0, import_jsx_runtime162.jsx)(import_components17.__experimentalText, { children: items.length > 1 ? (0, import_i18n59.sprintf)(
          // translators: %d: number of items to delete.
          (0, import_i18n59._n)(
            "Are you sure you want to permanently delete %d item?",
            "Are you sure you want to permanently delete %d items?",
            items.length
          ),
          items.length
        ) : (0, import_i18n59.sprintf)(
          // translators: %s: The post's title
          (0, import_i18n59.__)(
            'Are you sure you want to permanently delete "%s"?'
          ),
          (0, import_html_entities8.decodeEntities)(getItemTitle(items[0]))
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime162.jsxs)(import_components17.__experimentalHStack, { justify: "right", children: [
          /* @__PURE__ */ (0, import_jsx_runtime162.jsx)(
            import_components17.Button,
            {
              variant: "tertiary",
              onClick: closeModal2,
              disabled: isBusy,
              accessibleWhenDisabled: true,
              __next40pxDefaultSize: true,
              children: (0, import_i18n59.__)("Cancel")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime162.jsx)(
            import_components17.Button,
            {
              variant: "primary",
              onClick: async () => {
                setIsBusy(true);
                const promiseResult = await Promise.allSettled(
                  items.map(
                    (post2) => deleteEntityRecord(
                      "postType",
                      post2.type,
                      post2.id,
                      { force: true },
                      { throwOnError: true }
                    )
                  )
                );
                if (promiseResult.every(
                  ({ status }) => status === "fulfilled"
                )) {
                  let successMessage;
                  if (promiseResult.length === 1) {
                    successMessage = (0, import_i18n59.sprintf)(
                      /* translators: %s: The posts's title. */
                      (0, import_i18n59.__)('"%s" permanently deleted.'),
                      getItemTitle(items[0])
                    );
                  } else {
                    successMessage = (0, import_i18n59.__)(
                      "The items were permanently deleted."
                    );
                  }
                  createSuccessNotice(successMessage, {
                    type: "snackbar",
                    id: "permanently-delete-post-action"
                  });
                  onActionPerformed?.(items);
                } else {
                  let errorMessage;
                  if (promiseResult.length === 1) {
                    const typedError = promiseResult[0];
                    if (typedError.reason?.message) {
                      errorMessage = typedError.reason.message;
                    } else {
                      errorMessage = (0, import_i18n59.__)(
                        "An error occurred while permanently deleting the item."
                      );
                    }
                  } else {
                    const errorMessages = /* @__PURE__ */ new Set();
                    const failedPromises = promiseResult.filter(
                      ({ status }) => status === "rejected"
                    );
                    for (const failedPromise of failedPromises) {
                      const typedError = failedPromise;
                      if (typedError.reason?.message) {
                        errorMessages.add(
                          typedError.reason.message
                        );
                      }
                    }
                    if (errorMessages.size === 0) {
                      errorMessage = (0, import_i18n59.__)(
                        "An error occurred while permanently deleting the items."
                      );
                    } else if (errorMessages.size === 1) {
                      errorMessage = (0, import_i18n59.sprintf)(
                        /* translators: %s: an error message */
                        (0, import_i18n59.__)(
                          "An error occurred while permanently deleting the items: %s"
                        ),
                        [...errorMessages][0]
                      );
                    } else {
                      errorMessage = (0, import_i18n59.sprintf)(
                        /* translators: %s: a list of comma separated error messages */
                        (0, import_i18n59.__)(
                          "Some errors occurred while permanently deleting the items: %s"
                        ),
                        [...errorMessages].join(",")
                      );
                    }
                  }
                  createErrorNotice(errorMessage, {
                    type: "snackbar"
                  });
                }
                setIsBusy(false);
                closeModal2?.();
              },
              isBusy,
              disabled: isBusy,
              accessibleWhenDisabled: true,
              __next40pxDefaultSize: true,
              children: (0, import_i18n59.__)("Delete permanently")
            }
          )
        ] })
      ] });
    }
  };
  var permanently_delete_post_default = permanentlyDeletePost;

  // packages/fields/build-module/actions/restore-post.mjs
  var import_core_data21 = __toESM(require_core_data(), 1);
  var import_i18n60 = __toESM(require_i18n(), 1);
  var import_notices8 = __toESM(require_notices(), 1);
  var restorePost = {
    id: "restore",
    label: (0, import_i18n60.__)("Restore"),
    isPrimary: true,
    icon: backup_default,
    supportsBulk: true,
    isEligible(item) {
      return !isTemplateOrTemplatePart(item) && item.type !== "wp_block" && item.status === "trash" && item.permissions?.update;
    },
    async callback(posts, { registry, onActionPerformed }) {
      const { createSuccessNotice, createErrorNotice } = registry.dispatch(import_notices8.store);
      const { editEntityRecord, saveEditedEntityRecord } = registry.dispatch(import_core_data21.store);
      await Promise.allSettled(
        posts.map((post2) => {
          return editEntityRecord("postType", post2.type, post2.id, {
            status: "draft"
          });
        })
      );
      const promiseResult = await Promise.allSettled(
        posts.map((post2) => {
          return saveEditedEntityRecord("postType", post2.type, post2.id, {
            throwOnError: true
          });
        })
      );
      if (promiseResult.every(({ status }) => status === "fulfilled")) {
        let successMessage;
        if (posts.length === 1) {
          successMessage = (0, import_i18n60.sprintf)(
            /* translators: %s: The number of posts. */
            (0, import_i18n60.__)('"%s" has been restored.'),
            getItemTitle(posts[0])
          );
        } else if (posts[0].type === "page") {
          successMessage = (0, import_i18n60.sprintf)(
            /* translators: %d: The number of posts. */
            (0, import_i18n60.__)("%d pages have been restored."),
            posts.length
          );
        } else {
          successMessage = (0, import_i18n60.sprintf)(
            /* translators: %d: The number of posts. */
            (0, import_i18n60.__)("%d posts have been restored."),
            posts.length
          );
        }
        createSuccessNotice(successMessage, {
          type: "snackbar",
          id: "restore-post-action"
        });
        if (onActionPerformed) {
          onActionPerformed(posts);
        }
      } else {
        let errorMessage;
        if (promiseResult.length === 1) {
          const typedError = promiseResult[0];
          if (typedError.reason?.message) {
            errorMessage = typedError.reason.message;
          } else {
            errorMessage = (0, import_i18n60.__)(
              "An error occurred while restoring the post."
            );
          }
        } else {
          const errorMessages = /* @__PURE__ */ new Set();
          const failedPromises = promiseResult.filter(
            ({ status }) => status === "rejected"
          );
          for (const failedPromise of failedPromises) {
            const typedError = failedPromise;
            if (typedError.reason?.message) {
              errorMessages.add(typedError.reason.message);
            }
          }
          if (errorMessages.size === 0) {
            errorMessage = (0, import_i18n60.__)(
              "An error occurred while restoring the posts."
            );
          } else if (errorMessages.size === 1) {
            errorMessage = (0, import_i18n60.sprintf)(
              /* translators: %s: an error message */
              (0, import_i18n60.__)("An error occurred while restoring the posts: %s"),
              [...errorMessages][0]
            );
          } else {
            errorMessage = (0, import_i18n60.sprintf)(
              /* translators: %s: a list of comma separated error messages */
              (0, import_i18n60.__)(
                "Some errors occurred while restoring the posts: %s"
              ),
              [...errorMessages].join(",")
            );
          }
        }
        createErrorNotice(errorMessage, {
          type: "snackbar"
        });
      }
    }
  };
  var restore_post_default = restorePost;

  // packages/fields/build-module/actions/trash-post.mjs
  var import_data25 = __toESM(require_data(), 1);
  var import_core_data22 = __toESM(require_core_data(), 1);
  var import_i18n61 = __toESM(require_i18n(), 1);
  var import_notices9 = __toESM(require_notices(), 1);
  var import_element61 = __toESM(require_element(), 1);
  var import_components18 = __toESM(require_components(), 1);
  var import_jsx_runtime163 = __toESM(require_jsx_runtime(), 1);
  var trashPost = {
    id: "move-to-trash",
    label: (0, import_i18n61._x)("Trash", "verb"),
    isPrimary: true,
    icon: trash_default,
    isEligible(item) {
      if (item.type === "wp_template_part" || item.type === "wp_block") {
        return false;
      }
      if (item.type === "wp_template" && typeof item.id === "string") {
        return false;
      }
      return !!item.status && !["auto-draft", "trash"].includes(item.status) && item.permissions?.delete;
    },
    supportsBulk: true,
    hideModalHeader: true,
    modalFocusOnMount: "firstContentElement",
    RenderModal: ({ items, closeModal: closeModal2, onActionPerformed }) => {
      const [isBusy, setIsBusy] = (0, import_element61.useState)(false);
      const { createSuccessNotice, createErrorNotice } = (0, import_data25.useDispatch)(import_notices9.store);
      const { deleteEntityRecord } = (0, import_data25.useDispatch)(import_core_data22.store);
      return /* @__PURE__ */ (0, import_jsx_runtime163.jsxs)(import_components18.__experimentalVStack, { spacing: "5", children: [
        /* @__PURE__ */ (0, import_jsx_runtime163.jsx)(import_components18.__experimentalText, { children: items.length === 1 ? (0, import_i18n61.sprintf)(
          // translators: %s: The item's title.
          (0, import_i18n61.__)(
            'Are you sure you want to move "%s" to the trash?'
          ),
          getItemTitle(items[0])
        ) : (0, import_i18n61.sprintf)(
          // translators: %d: The number of items (2 or more).
          (0, import_i18n61._n)(
            "Are you sure you want to move %d item to the trash ?",
            "Are you sure you want to move %d items to the trash ?",
            items.length
          ),
          items.length
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime163.jsxs)(import_components18.__experimentalHStack, { justify: "right", children: [
          /* @__PURE__ */ (0, import_jsx_runtime163.jsx)(
            import_components18.Button,
            {
              __next40pxDefaultSize: true,
              variant: "tertiary",
              onClick: closeModal2,
              disabled: isBusy,
              accessibleWhenDisabled: true,
              children: (0, import_i18n61.__)("Cancel")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime163.jsx)(
            import_components18.Button,
            {
              __next40pxDefaultSize: true,
              variant: "primary",
              onClick: async () => {
                setIsBusy(true);
                const promiseResult = await Promise.allSettled(
                  items.map(
                    (item) => deleteEntityRecord(
                      "postType",
                      item.type,
                      item.id.toString(),
                      {},
                      { throwOnError: true }
                    )
                  )
                );
                if (promiseResult.every(
                  ({ status }) => status === "fulfilled"
                )) {
                  let successMessage;
                  if (promiseResult.length === 1) {
                    successMessage = (0, import_i18n61.sprintf)(
                      /* translators: %s: The item's title. */
                      (0, import_i18n61.__)('"%s" moved to the trash.'),
                      getItemTitle(items[0])
                    );
                  } else {
                    successMessage = (0, import_i18n61.sprintf)(
                      /* translators: %d: The number of items. */
                      (0, import_i18n61._n)(
                        "%d item moved to the trash.",
                        "%d items moved to the trash.",
                        items.length
                      ),
                      items.length
                    );
                  }
                  createSuccessNotice(successMessage, {
                    type: "snackbar",
                    id: "move-to-trash-action"
                  });
                } else {
                  let errorMessage;
                  if (promiseResult.length === 1) {
                    const typedError = promiseResult[0];
                    if (typedError.reason?.message) {
                      errorMessage = typedError.reason.message;
                    } else {
                      errorMessage = (0, import_i18n61.__)(
                        "An error occurred while moving the item to the trash."
                      );
                    }
                  } else {
                    const errorMessages = /* @__PURE__ */ new Set();
                    const failedPromises = promiseResult.filter(
                      ({ status }) => status === "rejected"
                    );
                    for (const failedPromise of failedPromises) {
                      const typedError = failedPromise;
                      if (typedError.reason?.message) {
                        errorMessages.add(
                          typedError.reason.message
                        );
                      }
                    }
                    if (errorMessages.size === 0) {
                      errorMessage = (0, import_i18n61.__)(
                        "An error occurred while moving the items to the trash."
                      );
                    } else if (errorMessages.size === 1) {
                      errorMessage = (0, import_i18n61.sprintf)(
                        /* translators: %s: an error message */
                        (0, import_i18n61.__)(
                          "An error occurred while moving the item to the trash: %s"
                        ),
                        [...errorMessages][0]
                      );
                    } else {
                      errorMessage = (0, import_i18n61.sprintf)(
                        /* translators: %s: a list of comma separated error messages */
                        (0, import_i18n61.__)(
                          "Some errors occurred while moving the items to the trash: %s"
                        ),
                        [...errorMessages].join(",")
                      );
                    }
                  }
                  createErrorNotice(errorMessage, {
                    type: "snackbar"
                  });
                }
                if (onActionPerformed) {
                  onActionPerformed(items);
                }
                setIsBusy(false);
                closeModal2?.();
              },
              isBusy,
              disabled: isBusy,
              accessibleWhenDisabled: true,
              children: (0, import_i18n61._x)("Trash", "verb")
            }
          )
        ] })
      ] });
    }
  };
  var trash_post_default = trashPost;

  // packages/fields/build-module/actions/delete-post.mjs
  var import_i18n62 = __toESM(require_i18n(), 1);
  var import_element62 = __toESM(require_element(), 1);
  var import_components19 = __toESM(require_components(), 1);
  var import_patterns5 = __toESM(require_patterns(), 1);
  var import_html_entities9 = __toESM(require_html_entities(), 1);

  // packages/fields/build-module/mutation/index.mjs
  var import_notices10 = __toESM(require_notices(), 1);
  var import_core_data23 = __toESM(require_core_data(), 1);
  var import_data26 = __toESM(require_data(), 1);
  function getErrorMessagesFromPromises(allSettledResults) {
    const errorMessages = /* @__PURE__ */ new Set();
    if (allSettledResults.length === 1) {
      const typedError = allSettledResults[0];
      if (typedError.reason?.message) {
        errorMessages.add(typedError.reason.message);
      }
    } else {
      const failedPromises = allSettledResults.filter(
        ({ status }) => status === "rejected"
      );
      for (const failedPromise of failedPromises) {
        const typedError = failedPromise;
        if (typedError.reason?.message) {
          errorMessages.add(typedError.reason.message);
        }
      }
    }
    return errorMessages;
  }
  var deletePostWithNotices = async (posts, notice, callbacks) => {
    const { createSuccessNotice, createErrorNotice } = (0, import_data26.dispatch)(import_notices10.store);
    const { deleteEntityRecord } = (0, import_data26.dispatch)(import_core_data23.store);
    const allSettledResults = await Promise.allSettled(
      posts.map((post2) => {
        return deleteEntityRecord(
          "postType",
          post2.type,
          post2.id,
          { force: true },
          { throwOnError: true }
        );
      })
    );
    if (allSettledResults.every(({ status }) => status === "fulfilled")) {
      let successMessage;
      if (allSettledResults.length === 1) {
        successMessage = notice.success.messages.getMessage(posts[0]);
      } else {
        successMessage = notice.success.messages.getBatchMessage(posts);
      }
      createSuccessNotice(successMessage, {
        type: notice.success.type ?? "snackbar",
        id: notice.success.id
      });
      callbacks.onActionPerformed?.(posts);
    } else {
      const errorMessages = getErrorMessagesFromPromises(allSettledResults);
      let errorMessage = "";
      if (allSettledResults.length === 1) {
        errorMessage = notice.error.messages.getMessage(errorMessages);
      } else {
        errorMessage = notice.error.messages.getBatchMessage(errorMessages);
      }
      createErrorNotice(errorMessage, {
        type: notice.error.type ?? "snackbar",
        id: notice.error.id
      });
      callbacks.onActionError?.();
    }
  };

  // packages/fields/build-module/actions/delete-post.mjs
  var import_jsx_runtime164 = __toESM(require_jsx_runtime(), 1);
  var { PATTERN_TYPES: PATTERN_TYPES4 } = unlock3(import_patterns5.privateApis);
  var deletePostAction = {
    id: "delete-post",
    label: (0, import_i18n62.__)("Delete"),
    isPrimary: true,
    icon: trash_default,
    isEligible(post2) {
      if (isTemplateOrTemplatePart(post2)) {
        return isTemplateRemovable(post2);
      }
      return post2.type === PATTERN_TYPES4.user;
    },
    supportsBulk: true,
    hideModalHeader: true,
    modalFocusOnMount: "firstContentElement",
    RenderModal: ({ items, closeModal: closeModal2, onActionPerformed }) => {
      const [isBusy, setIsBusy] = (0, import_element62.useState)(false);
      const isResetting = items.every(
        (item) => isTemplateOrTemplatePart(item) && item?.has_theme_file
      );
      return /* @__PURE__ */ (0, import_jsx_runtime164.jsxs)(import_components19.__experimentalVStack, { spacing: "5", children: [
        /* @__PURE__ */ (0, import_jsx_runtime164.jsx)(import_components19.__experimentalText, { children: items.length > 1 ? (0, import_i18n62.sprintf)(
          // translators: %d: number of items to delete.
          (0, import_i18n62._n)(
            "Delete %d item?",
            "Delete %d items?",
            items.length
          ),
          items.length
        ) : (0, import_i18n62.sprintf)(
          // translators: %s: The template or template part's title
          (0, import_i18n62._x)('Delete "%s"?', "template part"),
          getItemTitle(items[0])
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime164.jsxs)(import_components19.__experimentalHStack, { justify: "right", children: [
          /* @__PURE__ */ (0, import_jsx_runtime164.jsx)(
            import_components19.Button,
            {
              variant: "tertiary",
              onClick: closeModal2,
              disabled: isBusy,
              accessibleWhenDisabled: true,
              __next40pxDefaultSize: true,
              children: (0, import_i18n62.__)("Cancel")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime164.jsx)(
            import_components19.Button,
            {
              variant: "primary",
              onClick: async () => {
                setIsBusy(true);
                const notice = {
                  success: {
                    messages: {
                      getMessage: (item) => {
                        return isResetting ? (0, import_i18n62.sprintf)(
                          /* translators: %s: The template/part's name. */
                          (0, import_i18n62.__)('"%s" reset.'),
                          (0, import_html_entities9.decodeEntities)(
                            getItemTitle(item)
                          )
                        ) : (0, import_i18n62.sprintf)(
                          /* translators: %s: The template/part's name. */
                          (0, import_i18n62._x)(
                            '"%s" deleted.',
                            "template part"
                          ),
                          (0, import_html_entities9.decodeEntities)(
                            getItemTitle(item)
                          )
                        );
                      },
                      getBatchMessage: () => {
                        return isResetting ? (0, import_i18n62.__)("Items reset.") : (0, import_i18n62.__)("Items deleted.");
                      }
                    }
                  },
                  error: {
                    messages: {
                      getMessage: (error2) => {
                        if (error2.size === 1) {
                          return [...error2][0];
                        }
                        return isResetting ? (0, import_i18n62.__)(
                          "An error occurred while reverting the item."
                        ) : (0, import_i18n62.__)(
                          "An error occurred while deleting the item."
                        );
                      },
                      getBatchMessage: (errors) => {
                        if (errors.size === 0) {
                          return isResetting ? (0, import_i18n62.__)(
                            "An error occurred while reverting the items."
                          ) : (0, import_i18n62.__)(
                            "An error occurred while deleting the items."
                          );
                        }
                        if (errors.size === 1) {
                          return isResetting ? (0, import_i18n62.sprintf)(
                            /* translators: %s: an error message */
                            (0, import_i18n62.__)(
                              "An error occurred while reverting the items: %s"
                            ),
                            [...errors][0]
                          ) : (0, import_i18n62.sprintf)(
                            /* translators: %s: an error message */
                            (0, import_i18n62.__)(
                              "An error occurred while deleting the items: %s"
                            ),
                            [...errors][0]
                          );
                        }
                        return isResetting ? (0, import_i18n62.sprintf)(
                          /* translators: %s: a list of comma separated error messages */
                          (0, import_i18n62.__)(
                            "Some errors occurred while reverting the items: %s"
                          ),
                          [...errors].join(
                            ","
                          )
                        ) : (0, import_i18n62.sprintf)(
                          /* translators: %s: a list of comma separated error messages */
                          (0, import_i18n62.__)(
                            "Some errors occurred while deleting the items: %s"
                          ),
                          [...errors].join(
                            ","
                          )
                        );
                      }
                    }
                  }
                };
                await deletePostWithNotices(items, notice, {
                  onActionPerformed
                });
                setIsBusy(false);
                closeModal2?.();
              },
              isBusy,
              disabled: isBusy,
              accessibleWhenDisabled: true,
              __next40pxDefaultSize: true,
              children: (0, import_i18n62.__)("Delete")
            }
          )
        ] })
      ] });
    }
  };
  var delete_post_default = deletePostAction;

  // packages/fields/build-module/actions/duplicate-template-part.mjs
  var import_data29 = __toESM(require_data(), 1);
  var import_i18n64 = __toESM(require_i18n(), 1);
  var import_notices12 = __toESM(require_notices(), 1);
  var import_element64 = __toESM(require_element(), 1);
  var import_blocks6 = __toESM(require_blocks(), 1);

  // packages/fields/build-module/components/create-template-part-modal/index.mjs
  var import_components20 = __toESM(require_components(), 1);
  var import_compose4 = __toESM(require_compose(), 1);
  var import_core_data25 = __toESM(require_core_data(), 1);
  var import_data28 = __toESM(require_data(), 1);
  var import_element63 = __toESM(require_element(), 1);
  var import_i18n63 = __toESM(require_i18n(), 1);
  var import_notices11 = __toESM(require_notices(), 1);
  var import_blocks5 = __toESM(require_blocks(), 1);

  // packages/fields/build-module/components/create-template-part-modal/utils.mjs
  var import_data27 = __toESM(require_data(), 1);
  var import_core_data24 = __toESM(require_core_data(), 1);
  var useExistingTemplateParts = () => {
    return (0, import_data27.useSelect)(
      (select9) => select9(import_core_data24.store).getEntityRecords(
        "postType",
        "wp_template_part",
        {
          per_page: -1
        }
      ),
      []
    ) ?? [];
  };
  var getUniqueTemplatePartTitle = (title, templateParts) => {
    const lowercaseTitle = title.toLowerCase();
    const existingTitles = templateParts.map(
      (templatePart) => templatePart.title.rendered.toLowerCase()
    );
    if (!existingTitles.includes(lowercaseTitle)) {
      return title;
    }
    let suffix = 2;
    while (existingTitles.includes(`${lowercaseTitle} ${suffix}`)) {
      suffix++;
    }
    return `${title} ${suffix}`;
  };
  var getCleanTemplatePartSlug = (title) => {
    return paramCase(title).replace(/[^\w-]+/g, "") || "wp-custom-part";
  };

  // packages/fields/build-module/components/create-template-part-modal/index.mjs
  var import_jsx_runtime165 = __toESM(require_jsx_runtime(), 1);
  function getAreaRadioId(value, instanceId) {
    return `fields-create-template-part-modal__area-option-${value}-${instanceId}`;
  }
  function getAreaRadioDescriptionId(value, instanceId) {
    return `fields-create-template-part-modal__area-option-description-${value}-${instanceId}`;
  }
  function CreateTemplatePartModal({
    modalTitle,
    ...restProps
  }) {
    const defaultModalTitle = (0, import_data28.useSelect)(
      (select9) => select9(import_core_data25.store).getPostType("wp_template_part")?.labels?.add_new_item,
      []
    );
    return /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
      import_components20.Modal,
      {
        title: modalTitle || defaultModalTitle,
        onRequestClose: restProps.closeModal,
        overlayClassName: "fields-create-template-part-modal",
        focusOnMount: "firstContentElement",
        size: "medium",
        children: /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(CreateTemplatePartModalContents, { ...restProps })
      }
    );
  }
  var getTemplatePartIcon2 = (areaOrIconName) => {
    if ("header" === areaOrIconName) {
      return header_default;
    } else if ("footer" === areaOrIconName) {
      return footer_default;
    } else if ("sidebar" === areaOrIconName) {
      return sidebar_default;
    } else if ("navigation-overlay" === areaOrIconName) {
      return navigation_overlay_default;
    }
    return symbol_filled_default;
  };
  function CreateTemplatePartModalContents({
    defaultArea = "uncategorized",
    blocks = [],
    confirmLabel = (0, import_i18n63.__)("Add"),
    closeModal: closeModal2,
    onCreate,
    onError,
    defaultTitle = ""
  }) {
    const { createErrorNotice } = (0, import_data28.useDispatch)(import_notices11.store);
    const { saveEntityRecord } = (0, import_data28.useDispatch)(import_core_data25.store);
    const existingTemplateParts = useExistingTemplateParts();
    const [title, setTitle] = (0, import_element63.useState)(defaultTitle);
    const [area, setArea] = (0, import_element63.useState)(defaultArea);
    const [isSubmitting, setIsSubmitting] = (0, import_element63.useState)(false);
    const instanceId = (0, import_compose4.useInstanceId)(CreateTemplatePartModal);
    const defaultTemplatePartAreas = (0, import_data28.useSelect)(
      (select9) => select9(import_core_data25.store).getCurrentTheme()?.default_template_part_areas,
      []
    );
    async function createTemplatePart() {
      if (!title || isSubmitting) {
        return;
      }
      try {
        setIsSubmitting(true);
        const uniqueTitle = getUniqueTemplatePartTitle(
          title,
          existingTemplateParts
        );
        const cleanSlug = getCleanTemplatePartSlug(uniqueTitle);
        const templatePart = await saveEntityRecord(
          "postType",
          "wp_template_part",
          {
            slug: cleanSlug,
            title: uniqueTitle,
            content: (0, import_blocks5.serialize)(blocks),
            area
          },
          { throwOnError: true }
        );
        await onCreate(templatePart);
      } catch (error2) {
        const errorMessage = error2 instanceof Error && "code" in error2 && error2.message && error2.code !== "unknown_error" ? error2.message : (0, import_i18n63.__)(
          "An error occurred while creating the template part."
        );
        createErrorNotice(errorMessage, { type: "snackbar" });
        onError?.();
      } finally {
        setIsSubmitting(false);
      }
    }
    return /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
      "form",
      {
        onSubmit: async (event) => {
          event.preventDefault();
          await createTemplatePart();
        },
        children: /* @__PURE__ */ (0, import_jsx_runtime165.jsxs)(import_components20.__experimentalVStack, { spacing: "4", children: [
          /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
            import_components20.TextControl,
            {
              label: (0, import_i18n63.__)("Name"),
              value: title,
              onChange: setTitle,
              required: true
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime165.jsxs)("fieldset", { className: "fields-create-template-part-modal__area-fieldset", children: [
            /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(import_components20.BaseControl.VisualLabel, { as: "legend", children: (0, import_i18n63.__)("Area") }),
            /* @__PURE__ */ (0, import_jsx_runtime165.jsx)("div", { className: "fields-create-template-part-modal__area-radio-group", children: (defaultTemplatePartAreas ?? []).map(
              (item) => {
                const icon = getTemplatePartIcon2(item.icon);
                return /* @__PURE__ */ (0, import_jsx_runtime165.jsxs)(
                  "div",
                  {
                    className: "fields-create-template-part-modal__area-radio-wrapper",
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
                        "input",
                        {
                          type: "radio",
                          id: getAreaRadioId(
                            item.area,
                            instanceId
                          ),
                          name: `fields-create-template-part-modal__area-${instanceId}`,
                          value: item.area,
                          checked: area === item.area,
                          onChange: () => {
                            setArea(item.area);
                          },
                          "aria-describedby": getAreaRadioDescriptionId(
                            item.area,
                            instanceId
                          )
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
                        import_components20.Icon,
                        {
                          icon,
                          className: "fields-create-template-part-modal__area-radio-icon"
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
                        "label",
                        {
                          htmlFor: getAreaRadioId(
                            item.area,
                            instanceId
                          ),
                          className: "fields-create-template-part-modal__area-radio-label",
                          children: item.label
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
                        import_components20.Icon,
                        {
                          icon: check_default,
                          className: "fields-create-template-part-modal__area-radio-checkmark"
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
                        "p",
                        {
                          className: "fields-create-template-part-modal__area-radio-description",
                          id: getAreaRadioDescriptionId(
                            item.area,
                            instanceId
                          ),
                          children: item.description
                        }
                      )
                    ]
                  },
                  item.area
                );
              }
            ) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime165.jsxs)(import_components20.__experimentalHStack, { justify: "right", children: [
            /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
              import_components20.Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: () => {
                  closeModal2();
                },
                children: (0, import_i18n63.__)("Cancel")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime165.jsx)(
              import_components20.Button,
              {
                __next40pxDefaultSize: true,
                variant: "primary",
                type: "submit",
                "aria-disabled": !title || isSubmitting,
                isBusy: isSubmitting,
                children: confirmLabel
              }
            )
          ] })
        ] })
      }
    );
  }

  // packages/fields/build-module/actions/duplicate-template-part.mjs
  var import_jsx_runtime166 = __toESM(require_jsx_runtime(), 1);
  var duplicateTemplatePart = {
    id: "duplicate-template-part",
    label: (0, import_i18n64._x)("Duplicate", "action label"),
    isEligible: (item) => item.type === "wp_template_part",
    modalHeader: (0, import_i18n64._x)("Duplicate template part", "action label"),
    modalFocusOnMount: "firstContentElement",
    RenderModal: ({ items, closeModal: closeModal2 }) => {
      const [item] = items;
      const blocks = (0, import_element64.useMemo)(() => {
        return item.blocks ?? (0, import_blocks6.parse)(
          typeof item.content === "string" ? item.content : item.content.raw,
          {
            __unstableSkipMigrationLogs: true
          }
        );
      }, [item.content, item.blocks]);
      const { createSuccessNotice } = (0, import_data29.useDispatch)(import_notices12.store);
      function onTemplatePartSuccess(templatePart) {
        createSuccessNotice(
          (0, import_i18n64.sprintf)(
            // translators: %s: The new template part's title e.g. 'Call to action (copy)'.
            (0, import_i18n64._x)('"%s" duplicated.', "template part"),
            getItemTitle(templatePart)
          ),
          { type: "snackbar", id: "edit-site-patterns-success" }
        );
        closeModal2?.();
      }
      return /* @__PURE__ */ (0, import_jsx_runtime166.jsx)(
        CreateTemplatePartModalContents,
        {
          blocks,
          defaultArea: item.area,
          defaultTitle: (0, import_i18n64.sprintf)(
            /* translators: %s: Existing template part title */
            (0, import_i18n64._x)("%s (Copy)", "template part"),
            getItemTitle(item)
          ),
          onCreate: onTemplatePartSuccess,
          onError: closeModal2,
          confirmLabel: (0, import_i18n64._x)("Duplicate", "action label"),
          closeModal: closeModal2 ?? (() => {
          })
        }
      );
    }
  };
  var duplicate_template_part_default = duplicateTemplatePart;

  // packages/media-fields/build-module/alt_text/index.mjs
  var import_i18n65 = __toESM(require_i18n(), 1);
  var import_components21 = __toESM(require_components(), 1);
  var import_jsx_runtime167 = __toESM(require_jsx_runtime(), 1);
  var altTextField = {
    id: "alt_text",
    type: "text",
    label: (0, import_i18n65.__)("Alt text"),
    isVisible: (item) => item?.media_type === "image",
    render: ({ item }) => item?.alt_text || "-",
    Edit: ({ field, onChange, data }) => {
      return /* @__PURE__ */ (0, import_jsx_runtime167.jsx)(
        import_components21.TextareaControl,
        {
          label: field.label,
          value: data.alt_text || "",
          onChange: (value) => onChange({ alt_text: value }),
          help: /* @__PURE__ */ (0, import_jsx_runtime167.jsxs)(import_jsx_runtime167.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime167.jsx)(
              Link,
              {
                href: (
                  // translators: Localized tutorial, if one exists. W3C Web Accessibility Initiative link has list of existing translations.
                  (0, import_i18n65.__)(
                    "https://www.w3.org/WAI/tutorials/images/decision-tree/"
                  )
                ),
                openInNewTab: true,
                children: (0, import_i18n65.__)("Describe the purpose of the image.")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime167.jsx)("br", {}),
            (0, import_i18n65.__)("Leave empty if decorative.")
          ] }),
          rows: 2
        }
      );
    },
    enableSorting: false,
    filterBy: false
  };
  var alt_text_default = altTextField;

  // packages/media-fields/build-module/attached_to/index.mjs
  var import_i18n68 = __toESM(require_i18n(), 1);

  // packages/media-fields/build-module/attached_to/view.mjs
  var import_element65 = __toESM(require_element(), 1);
  var import_i18n66 = __toESM(require_i18n(), 1);

  // packages/media-fields/build-module/utils/get-rendered-content.mjs
  function getRenderedContent(content) {
    if (!content) {
      return "";
    }
    if (typeof content === "string") {
      return content;
    }
    if (typeof content === "object") {
      return content.rendered || content.raw || "";
    }
    return "";
  }

  // packages/media-fields/build-module/attached_to/view.mjs
  var import_jsx_runtime168 = __toESM(require_jsx_runtime(), 1);
  function MediaAttachedToView({
    item
  }) {
    const [attachedPostTitle, setAttachedPostTitle] = (0, import_element65.useState)(null);
    const parentId = item.post;
    const embeddedPostId = item._embedded?.["wp:attached-to"]?.[0]?.id;
    const embeddedPostTitle = item._embedded?.["wp:attached-to"]?.[0]?.title;
    (0, import_element65.useEffect)(() => {
      if (!!parentId && parentId === embeddedPostId) {
        setAttachedPostTitle(
          getRenderedContent(embeddedPostTitle) || (0, import_i18n66.__)("(no title)")
        );
      }
      if (!parentId) {
        setAttachedPostTitle((0, import_i18n66.__)("(Unattached)"));
      }
    }, [parentId, embeddedPostId, embeddedPostTitle]);
    return /* @__PURE__ */ (0, import_jsx_runtime168.jsx)(import_jsx_runtime168.Fragment, { children: attachedPostTitle });
  }

  // packages/media-fields/build-module/attached_to/edit.mjs
  var import_core_data26 = __toESM(require_core_data(), 1);
  var import_components22 = __toESM(require_components(), 1);
  var import_i18n67 = __toESM(require_i18n(), 1);
  var import_element66 = __toESM(require_element(), 1);
  var import_compose5 = __toESM(require_compose(), 1);
  var import_data30 = __toESM(require_data(), 1);
  var import_jsx_runtime169 = __toESM(require_jsx_runtime(), 1);
  function MediaAttachedToEdit({
    data,
    onChange
  }) {
    const defaultPost = !!data.post && !!data?._embedded?.["wp:attached-to"]?.[0] ? [
      {
        label: getRenderedContent(
          data._embedded?.["wp:attached-to"]?.[0]?.title
        ),
        value: data.post.toString()
      }
    ] : [];
    const [options, setOptions] = (0, import_element66.useState)(defaultPost);
    const [searchResults, setSearchResults] = (0, import_element66.useState)(
      []
    );
    const [isLoading, setIsLoading] = (0, import_element66.useState)(false);
    const [value, setValue] = (0, import_element66.useState)(
      data?.post?.toString() ?? null
    );
    const postTypes = (0, import_data30.useSelect)(
      (select9) => select9(import_core_data26.store).getPostTypes(),
      []
    );
    const handleDetach = () => {
      onChange({
        post: 0,
        _embedded: { ...data?._embedded, "wp:attached-to": void 0 }
      });
      setValue(null);
    };
    const onValueChange = async (filterValue) => {
      setIsLoading(true);
      const results = await (0, import_core_data26.__experimentalFetchLinkSuggestions)(
        filterValue,
        /*
         * @TODO `fetchLinkSuggestions()` should accept `perPage` as an option argument.
         * `isInitialSuggestions` limits the result to 3, otherwise it's hardcoded to 20.
         */
        { type: "post", isInitialSuggestions: true },
        {}
      );
      setSearchResults(results);
      const suggestions = results.map((result) => {
        return {
          label: result.title,
          value: result.id.toString()
        };
      });
      const includeCurrent = !filterValue && suggestions.findIndex((s3) => s3.value === value) === -1;
      setOptions(suggestions.concat(includeCurrent ? defaultPost : []));
      setIsLoading(false);
    };
    const debouncedValueChange = (0, import_compose5.useDebounce)((0, import_compose5.useEvent)(onValueChange), 300);
    const handleSelectOption = (selectedPostId) => {
      if (!selectedPostId) {
        handleDetach();
        return;
      }
      setValue(selectedPostId);
      if (selectedPostId) {
        const selectedPost = searchResults.find(
          (result) => result.id === Number(selectedPostId)
        );
        if (selectedPost && postTypes) {
          const postType2 = postTypes.find(
            (_postType) => _postType.slug === selectedPost?.type
          );
          const attachedTo = {
            ...postType2 && { type: postType2.slug },
            id: Number(selectedPostId),
            title: {
              raw: selectedPost.title,
              rendered: selectedPost.title
            }
          };
          onChange({
            post: Number(selectedPostId),
            _embedded: {
              ...data?._embedded,
              "wp:attached-to": [attachedTo]
            }
          });
        }
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime169.jsx)(
      import_components22.ComboboxControl,
      {
        className: "dataviews-media-field__attached-to",
        isLoading,
        label: (0, import_i18n67.__)("Attached to"),
        help: (0, import_i18n67.__)("Attach this file to a single post or page."),
        value,
        options,
        onFilterValueChange: (filterValue) => debouncedValueChange(filterValue),
        onChange: handleSelectOption,
        hideLabelFromVision: true,
        expandOnFocus: false
      }
    );
  }

  // packages/media-fields/build-module/attached_to/index.mjs
  var attachedToField = {
    id: "attached_to",
    type: "text",
    label: (0, import_i18n68.__)("Attached to"),
    Edit: MediaAttachedToEdit,
    render: MediaAttachedToView,
    enableSorting: false,
    filterBy: false
  };
  var attached_to_default = attachedToField;

  // packages/media-fields/build-module/author/index.mjs
  var import_i18n70 = __toESM(require_i18n(), 1);
  var import_data31 = __toESM(require_data(), 1);
  var import_core_data27 = __toESM(require_core_data(), 1);

  // packages/media-fields/build-module/author/view.mjs
  var import_i18n69 = __toESM(require_i18n(), 1);
  var import_element67 = __toESM(require_element(), 1);
  var import_components23 = __toESM(require_components(), 1);
  var import_jsx_runtime170 = __toESM(require_jsx_runtime(), 1);
  function AuthorView2({
    item
  }) {
    const author = item?._embedded?.author?.[0];
    const text = author?.name;
    const imageUrl = author?.avatar_urls?.[48];
    const [loadingState, setLoadingState] = (0, import_element67.useState)("loading");
    (0, import_element67.useEffect)(() => {
      setLoadingState("loading");
    }, [imageUrl]);
    const imgRef = (0, import_element67.useCallback)((img) => {
      if (img?.complete) {
        setLoadingState("instant");
      }
    }, []);
    const handleLoad = () => {
      if (loadingState === "loading") {
        setLoadingState("loaded");
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime170.jsxs)(import_components23.__experimentalHStack, { alignment: "left", spacing: 0, children: [
      !!imageUrl && /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(
        "div",
        {
          className: clsx_default("media-author-field__avatar", {
            "is-loading": loadingState === "loading",
            "is-loaded": loadingState === "loaded"
          }),
          children: /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(
            "img",
            {
              ref: imgRef,
              onLoad: handleLoad,
              alt: (0, import_i18n69.__)("Author avatar"),
              src: imageUrl
            }
          )
        }
      ),
      !imageUrl && /* @__PURE__ */ (0, import_jsx_runtime170.jsx)("div", { className: "media-author-field__icon", children: /* @__PURE__ */ (0, import_jsx_runtime170.jsx)(import_components23.Icon, { icon: comment_author_avatar_default }) }),
      /* @__PURE__ */ (0, import_jsx_runtime170.jsx)("span", { className: "media-author-field__name", children: text })
    ] });
  }

  // packages/media-fields/build-module/author/index.mjs
  var authorField2 = {
    label: (0, import_i18n70.__)("Author"),
    id: "author",
    type: "integer",
    getElements: async () => {
      const authors = await (0, import_data31.resolveSelect)(import_core_data27.store).getEntityRecords(
        "root",
        "user",
        {
          per_page: -1,
          who: "authors",
          _fields: "id,name",
          context: "view"
        }
      ) ?? [];
      return authors.map(({ id, name: name2 }) => ({
        value: id,
        label: name2
      }));
    },
    render: AuthorView2,
    sort: (a3, b3, direction) => {
      const nameA = a3._embedded?.author?.[0]?.name || "";
      const nameB = b3._embedded?.author?.[0]?.name || "";
      return direction === "asc" ? nameA.localeCompare(nameB) : nameB.localeCompare(nameA);
    },
    filterBy: {
      operators: ["isAny", "isNone"]
    },
    readOnly: true
  };
  var author_default2 = authorField2;

  // packages/media-fields/build-module/caption/index.mjs
  var import_i18n71 = __toESM(require_i18n(), 1);
  var import_components24 = __toESM(require_components(), 1);

  // packages/media-fields/build-module/utils/get-raw-content.mjs
  function getRawContent(content) {
    if (!content) {
      return "";
    }
    if (typeof content === "string") {
      return content;
    }
    if (typeof content === "object" && "raw" in content) {
      return content.raw || "";
    }
    return "";
  }

  // packages/media-fields/build-module/caption/index.mjs
  var import_jsx_runtime171 = __toESM(require_jsx_runtime(), 1);
  var captionField = {
    id: "caption",
    type: "text",
    label: (0, import_i18n71.__)("Caption"),
    getValue: ({ item }) => getRawContent(item?.caption),
    render: ({ item }) => getRawContent(item?.caption) || "-",
    Edit: ({ field, onChange, data }) => {
      return /* @__PURE__ */ (0, import_jsx_runtime171.jsx)(
        import_components24.TextareaControl,
        {
          label: field.label,
          value: getRawContent(data.caption) || "",
          onChange: (value) => onChange({ caption: value }),
          rows: 2
        }
      );
    },
    enableSorting: false,
    filterBy: false
  };
  var caption_default = captionField;

  // packages/media-fields/build-module/date_added/index.mjs
  var import_i18n72 = __toESM(require_i18n(), 1);
  var dateAddedField = {
    id: "date",
    type: "datetime",
    label: (0, import_i18n72.__)("Date added"),
    filterBy: {
      operators: ["before", "after"]
    },
    readOnly: true
  };
  var date_added_default = dateAddedField;

  // packages/media-fields/build-module/description/index.mjs
  var import_i18n73 = __toESM(require_i18n(), 1);
  var import_components25 = __toESM(require_components(), 1);
  var import_jsx_runtime172 = __toESM(require_jsx_runtime(), 1);
  var descriptionField2 = {
    id: "description",
    type: "text",
    label: (0, import_i18n73.__)("Description"),
    getValue: ({ item }) => getRawContent(item?.description),
    render: ({ item }) => /* @__PURE__ */ (0, import_jsx_runtime172.jsx)("div", { children: getRawContent(item?.description) || "-" }),
    Edit: ({ field, onChange, data }) => {
      return /* @__PURE__ */ (0, import_jsx_runtime172.jsx)(
        import_components25.TextareaControl,
        {
          label: field.label,
          value: getRawContent(data.description) || "",
          onChange: (value) => onChange({ description: value }),
          rows: 5
        }
      );
    },
    enableSorting: false,
    filterBy: false
  };
  var description_default2 = descriptionField2;

  // packages/media-fields/build-module/filename/index.mjs
  var import_i18n74 = __toESM(require_i18n(), 1);
  var import_url10 = __toESM(require_url(), 1);

  // packages/media-fields/build-module/filename/view.mjs
  var import_element68 = __toESM(require_element(), 1);
  var import_url9 = __toESM(require_url(), 1);
  var import_jsx_runtime173 = __toESM(require_jsx_runtime(), 1);
  var TRUNCATE_LENGTH = 15;
  function FileNameView({
    item
  }) {
    const fileName = (0, import_element68.useMemo)(
      () => item?.source_url ? (0, import_url9.getFilename)(item.source_url) : null,
      [item?.source_url]
    );
    if (!fileName) {
      return "";
    }
    if (fileName.length <= TRUNCATE_LENGTH) {
      return /* @__PURE__ */ (0, import_jsx_runtime173.jsx)("span", { className: "dataviews-media-field__filename", children: fileName });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime173.jsxs)(tooltip_exports.Root, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(
        tooltip_exports.Trigger,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime173.jsx)("span", { className: "dataviews-media-field__filename", children: fileName })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime173.jsx)(tooltip_exports.Popup, { children: fileName })
    ] });
  }

  // packages/media-fields/build-module/filename/index.mjs
  var filenameField = {
    id: "filename",
    type: "text",
    label: (0, import_i18n74.__)("File name"),
    getValue: ({ item }) => (0, import_url10.getFilename)(item?.source_url || ""),
    render: FileNameView,
    enableSorting: false,
    filterBy: false,
    readOnly: true
  };
  var filename_default = filenameField;

  // packages/media-fields/build-module/filesize/index.mjs
  var import_i18n75 = __toESM(require_i18n(), 1);
  var KB_IN_BYTES = 1024;
  var MB_IN_BYTES = 1024 * KB_IN_BYTES;
  var GB_IN_BYTES = 1024 * MB_IN_BYTES;
  var TB_IN_BYTES = 1024 * GB_IN_BYTES;
  var PB_IN_BYTES = 1024 * TB_IN_BYTES;
  var EB_IN_BYTES = 1024 * PB_IN_BYTES;
  var ZB_IN_BYTES = 1024 * EB_IN_BYTES;
  var YB_IN_BYTES = 1024 * ZB_IN_BYTES;
  function getBytesString(bytes, unitSymbol, decimals = 2) {
    return (0, import_i18n75.sprintf)(
      // translators: 1: Actual bytes of a file. 2: The unit symbol (e.g. MB).
      (0, import_i18n75._x)("%1$s %2$s", "file size"),
      bytes.toLocaleString(void 0, {
        minimumFractionDigits: 0,
        maximumFractionDigits: decimals
      }),
      unitSymbol
    );
  }
  function formatFileSize(bytes, decimals = 2) {
    if (bytes === 0) {
      return getBytesString(0, (0, import_i18n75._x)("B", "unit symbol"), decimals);
    }
    const quant = {
      /* translators: Unit symbol for yottabyte. */
      [(0, import_i18n75._x)("YB", "unit symbol")]: YB_IN_BYTES,
      /* translators: Unit symbol for zettabyte. */
      [(0, import_i18n75._x)("ZB", "unit symbol")]: ZB_IN_BYTES,
      /* translators: Unit symbol for exabyte. */
      [(0, import_i18n75._x)("EB", "unit symbol")]: EB_IN_BYTES,
      /* translators: Unit symbol for petabyte. */
      [(0, import_i18n75._x)("PB", "unit symbol")]: PB_IN_BYTES,
      /* translators: Unit symbol for terabyte. */
      [(0, import_i18n75._x)("TB", "unit symbol")]: TB_IN_BYTES,
      /* translators: Unit symbol for gigabyte. */
      [(0, import_i18n75._x)("GB", "unit symbol")]: GB_IN_BYTES,
      /* translators: Unit symbol for megabyte. */
      [(0, import_i18n75._x)("MB", "unit symbol")]: MB_IN_BYTES,
      /* translators: Unit symbol for kilobyte. */
      [(0, import_i18n75._x)("KB", "unit symbol")]: KB_IN_BYTES,
      /* translators: Unit symbol for byte. */
      [(0, import_i18n75._x)("B", "unit symbol")]: 1
    };
    for (const [unit, mag] of Object.entries(quant)) {
      if (bytes >= mag) {
        return getBytesString(bytes / mag, unit, decimals);
      }
    }
    return "";
  }
  var filesizeField = {
    id: "filesize",
    type: "text",
    label: (0, import_i18n75.__)("File size"),
    getValue: ({ item }) => item?.media_details?.filesize ? formatFileSize(item?.media_details?.filesize) : "",
    isVisible: (item) => {
      return !!item?.media_details?.filesize;
    },
    enableSorting: false,
    filterBy: false,
    readOnly: true
  };
  var filesize_default = filesizeField;

  // packages/media-fields/build-module/media_dimensions/index.mjs
  var import_i18n76 = __toESM(require_i18n(), 1);
  var mediaDimensionsField = {
    id: "media_dimensions",
    type: "text",
    label: (0, import_i18n76.__)("Dimensions"),
    getValue: ({ item }) => item?.media_details?.width && item?.media_details?.height ? (0, import_i18n76.sprintf)(
      // translators: 1: Width. 2: Height.
      (0, import_i18n76._x)("%1$s \xD7 %2$s", "image dimensions"),
      item?.media_details?.width?.toString(),
      item?.media_details?.height?.toString()
    ) : "",
    isVisible: (item) => {
      return !!(item?.media_details?.width && item?.media_details?.height);
    },
    enableSorting: false,
    filterBy: false,
    readOnly: true
  };
  var media_dimensions_default = mediaDimensionsField;

  // packages/media-fields/build-module/mime_type/index.mjs
  var import_i18n77 = __toESM(require_i18n(), 1);
  var mimeTypeField = {
    id: "mime_type",
    type: "text",
    label: (0, import_i18n77.__)("File type"),
    getValue: ({ item }) => item?.mime_type || "",
    render: ({ item }) => item?.mime_type || "-",
    // Disable sorting until REST API support for ordering my `mime_type` is added.
    // See: https://core.trac.wordpress.org/ticket/64073
    enableSorting: false,
    filterBy: false,
    readOnly: true
  };
  var mime_type_default = mimeTypeField;

  // packages/editor/build-module/dataviews/fields/content-preview/index.mjs
  var import_i18n203 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/dataviews/fields/content-preview/content-preview-view.mjs
  var import_i18n202 = __toESM(require_i18n(), 1);
  var import_block_editor34 = __toESM(require_block_editor(), 1);
  var import_data86 = __toESM(require_data(), 1);
  var import_core_data54 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/provider/index.mjs
  var import_element217 = __toESM(require_element(), 1);
  var import_data85 = __toESM(require_data(), 1);
  var import_i18n201 = __toESM(require_i18n(), 1);
  var import_core_data53 = __toESM(require_core_data(), 1);
  var import_block_editor33 = __toESM(require_block_editor(), 1);
  var import_notices18 = __toESM(require_notices(), 1);
  var import_patterns8 = __toESM(require_patterns(), 1);
  var import_blocks18 = __toESM(require_blocks(), 1);
  var import_url13 = __toESM(require_url(), 1);

  // packages/editor/build-module/components/provider/with-registry-provider.mjs
  var import_element69 = __toESM(require_element(), 1);
  var import_data32 = __toESM(require_data(), 1);
  var import_compose6 = __toESM(require_compose(), 1);
  var import_block_editor4 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime174 = __toESM(require_jsx_runtime(), 1);
  function getSubRegistry(subRegistries, registry, useSubRegistry) {
    if (!useSubRegistry) {
      return registry;
    }
    let subRegistry = subRegistries.get(registry);
    if (!subRegistry) {
      subRegistry = (0, import_data32.createRegistry)(
        {
          "core/block-editor": import_block_editor4.storeConfig
        },
        registry
      );
      subRegistry.registerStore("core/editor", storeConfig);
      subRegistries.set(registry, subRegistry);
    }
    return subRegistry;
  }
  var withRegistryProvider = (0, import_compose6.createHigherOrderComponent)(
    (WrappedComponent) => ({ useSubRegistry = true, ...props }) => {
      const registry = (0, import_data32.useRegistry)();
      const [subRegistries] = (0, import_element69.useState)(() => /* @__PURE__ */ new WeakMap());
      const subRegistry = getSubRegistry(
        subRegistries,
        registry,
        useSubRegistry
      );
      if (subRegistry === registry) {
        return /* @__PURE__ */ (0, import_jsx_runtime174.jsx)(WrappedComponent, { registry, ...props });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime174.jsx)(import_data32.RegistryProvider, { value: subRegistry, children: /* @__PURE__ */ (0, import_jsx_runtime174.jsx)(WrappedComponent, { registry: subRegistry, ...props }) });
    },
    "withRegistryProvider"
  );
  var with_registry_provider_default = withRegistryProvider;

  // packages/editor/build-module/components/provider/use-block-editor-settings.mjs
  var import_element201 = __toESM(require_element(), 1);
  var import_data65 = __toESM(require_data(), 1);
  var import_core_data45 = __toESM(require_core_data(), 1);
  var import_i18n190 = __toESM(require_i18n(), 1);
  var import_preferences6 = __toESM(require_preferences(), 1);
  var import_compose34 = __toESM(require_compose(), 1);
  var import_blocks12 = __toESM(require_blocks(), 1);
  var import_block_editor21 = __toESM(require_block_editor(), 1);

  // packages/media-editor/build-module/components/media-editor-provider/index.mjs
  var import_element70 = __toESM(require_element(), 1);
  var import_jsx_runtime175 = __toESM(require_jsx_runtime(), 1);
  var MediaEditorContext = (0, import_element70.createContext)(
    void 0
  );
  function MediaEditorProvider({
    value,
    onChange,
    settings = {},
    children
  }) {
    const contextValue = {
      media: value,
      onChange,
      fields: settings.fields || []
    };
    return /* @__PURE__ */ (0, import_jsx_runtime175.jsx)(MediaEditorContext.Provider, { value: contextValue, children });
  }
  function useMediaEditorContext() {
    const context = (0, import_element70.useContext)(MediaEditorContext);
    if (!context) {
      throw new Error(
        "useMediaEditorContext must be used within MediaEditorProvider"
      );
    }
    return context;
  }

  // packages/media-editor/build-module/components/media-preview/index.mjs
  var import_components26 = __toESM(require_components(), 1);
  var import_element71 = __toESM(require_element(), 1);
  var import_i18n78 = __toESM(require_i18n(), 1);

  // packages/media-editor/build-module/utils/get-media-type.mjs
  function getMediaTypeFromMimeType(mimeType) {
    if (!mimeType) {
      return { type: "application" };
    }
    if (mimeType.startsWith("image/")) {
      return { type: "image" };
    }
    if (mimeType.startsWith("video/")) {
      return { type: "video" };
    }
    if (mimeType.startsWith("audio/")) {
      return { type: "audio" };
    }
    return { type: "application" };
  }

  // packages/media-editor/build-module/components/media-preview/index.mjs
  var import_jsx_runtime176 = __toESM(require_jsx_runtime(), 1);
  function MediaPreviewContent({
    mediaType,
    mediaUrl,
    altText,
    displayTitle,
    mimeType,
    onLoad,
    onError,
    loadingState
  }) {
    switch (mediaType.type) {
      case "image":
        return /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
          "img",
          {
            className: loadingState === "loaded" ? "loaded" : "",
            src: mediaUrl,
            alt: altText || "",
            onLoad,
            onError
          }
        );
      case "video":
        return /* @__PURE__ */ (0, import_jsx_runtime176.jsx)("video", { src: mediaUrl, controls: true, onError, children: displayTitle });
      case "audio":
        return /* @__PURE__ */ (0, import_jsx_runtime176.jsx)("audio", { src: mediaUrl, controls: true, onError, children: displayTitle });
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime176.jsxs)("div", { className: "media-editor-preview__file-info", children: [
          /* @__PURE__ */ (0, import_jsx_runtime176.jsx)("p", { className: "media-editor-preview__file-name", children: displayTitle }),
          /* @__PURE__ */ (0, import_jsx_runtime176.jsx)("p", { className: "media-editor-preview__mime-type", children: mimeType }),
          /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
            "a",
            {
              href: mediaUrl,
              target: "_blank",
              rel: "noopener",
              className: "media-editor-preview__download-link",
              children: (0, import_i18n78.__)("View file")
            }
          )
        ] });
    }
  }
  function MediaPreview2(props) {
    const [loadingState, setLoadingState] = (0, import_element71.useState)("loading");
    const { media } = useMediaEditorContext();
    const {
      source_url: mediaUrl,
      mime_type: mimeType,
      alt_text: altText,
      title
    } = media || {};
    const mediaType = getMediaTypeFromMimeType(mimeType);
    if (!mediaUrl) {
      return /* @__PURE__ */ (0, import_jsx_runtime176.jsx)("div", { className: "media-editor-preview media-editor-preview--empty", children: /* @__PURE__ */ (0, import_jsx_runtime176.jsx)("p", { children: (0, import_i18n78.__)("No media file available.") }) });
    }
    if (loadingState === "error") {
      return /* @__PURE__ */ (0, import_jsx_runtime176.jsxs)("div", { className: "media-editor-preview media-editor-preview--error", children: [
        /* @__PURE__ */ (0, import_jsx_runtime176.jsx)("p", { children: (0, import_i18n78.__)("Failed to load media file.") }),
        /* @__PURE__ */ (0, import_jsx_runtime176.jsx)("p", { className: "media-editor-preview__url", children: mediaUrl })
      ] });
    }
    const displayTitle = typeof title === "string" ? title : title?.rendered || title?.raw;
    return /* @__PURE__ */ (0, import_jsx_runtime176.jsxs)(
      "div",
      {
        ...props,
        className: `media-editor-preview media-editor-preview--${mediaType.type}`,
        children: [
          mediaType.type === "image" && loadingState === "loading" && /* @__PURE__ */ (0, import_jsx_runtime176.jsx)("div", { className: "media-editor-preview__spinner", children: /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(import_components26.Spinner, {}) }),
          /* @__PURE__ */ (0, import_jsx_runtime176.jsx)(
            MediaPreviewContent,
            {
              mediaType,
              mediaUrl,
              altText,
              displayTitle,
              mimeType,
              onLoad: () => setLoadingState("loaded"),
              onError: () => setLoadingState("error"),
              loadingState
            }
          )
        ]
      }
    );
  }

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

  // packages/dataviews/build-module/constants.mjs
  var import_i18n79 = __toESM(require_i18n(), 1);
  var OPERATOR_IS_ANY2 = "isAny";
  var OPERATOR_IS_NONE = "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_BEFORE = "before";
  var OPERATOR_AFTER = "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_i18n79.__)("Sort ascending"),
    desc: (0, import_i18n79.__)("Sort descending")
  };
  var sortIcons = {
    asc: arrow_up_default,
    desc: arrow_down_default
  };
  var LAYOUT_TABLE = "table";
  var LAYOUT_GRID = "grid";
  var LAYOUT_LIST = "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_element72.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_element72.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_i18n100 = __toESM(require_i18n(), 1);

  // packages/dataviews/build-module/components/dataviews-layouts/table/index.mjs
  var import_i18n87 = __toESM(require_i18n(), 1);
  var import_components32 = __toESM(require_components(), 1);
  var import_element81 = __toESM(require_element(), 1);
  var import_keycodes2 = __toESM(require_keycodes(), 1);

  // packages/dataviews/build-module/components/dataviews-selection-checkbox/index.mjs
  var import_components27 = __toESM(require_components(), 1);
  var import_i18n80 = __toESM(require_i18n(), 1);
  var import_jsx_runtime177 = __toESM(require_jsx_runtime(), 1);
  var SELECTION_CHECKBOX_CLASS = "dataviews-selection-checkbox";
  function DataViewsSelectionCheckbox({
    selection,
    onChangeSelection,
    item,
    getItemId: getItemId2,
    titleField: titleField2,
    disabled: disabled2,
    ...extraProps
  }) {
    const id = getItemId2(item);
    const isInSelectionArray = selection.includes(id);
    const checked = !disabled2 && isInSelectionArray;
    const selectionLabel = titleField2?.getValue?.({ item }) || (0, import_i18n80.__)("(no title)");
    return /* @__PURE__ */ (0, import_jsx_runtime177.jsx)(
      import_components27.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_components28 = __toESM(require_components(), 1);
  var import_i18n81 = __toESM(require_i18n(), 1);
  var import_element73 = __toESM(require_element(), 1);
  var import_data33 = __toESM(require_data(), 1);
  var import_compose7 = __toESM(require_compose(), 1);

  // packages/dataviews/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/dataviews"
  );

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

  // packages/dataviews/build-module/components/dataviews-bulk-actions/index.mjs
  var import_components29 = __toESM(require_components(), 1);
  var import_i18n83 = __toESM(require_i18n(), 1);
  var import_element74 = __toESM(require_element(), 1);
  var import_data34 = __toESM(require_data(), 1);
  var import_compose8 = __toESM(require_compose(), 1);

  // packages/dataviews/build-module/utils/get-footer-message.mjs
  var import_i18n82 = __toESM(require_i18n(), 1);
  function getFooterMessage(selectionCount, itemsCount, totalItems, onlyTotalCount = false) {
    if (selectionCount > 0) {
      return (0, import_i18n82.sprintf)(
        /* translators: %d: number of items. */
        (0, import_i18n82._n)("%d Item selected", "%d Items selected", selectionCount),
        selectionCount
      );
    }
    if (onlyTotalCount || totalItems <= itemsCount) {
      return (0, import_i18n82.sprintf)(
        /* translators: %d: number of items. */
        (0, import_i18n82._n)("%d Item", "%d Items", totalItems),
        totalItems
      );
    }
    return (0, import_i18n82.sprintf)(
      /* translators: %1$d: number of items. %2$d: total number of items. */
      (0, import_i18n82._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_runtime179 = __toESM(require_jsx_runtime(), 1);
  function hasAPossibleBulkAction(actions2, item) {
    return actions2.some(
      (action) => action.supportsBulk && (!action.isEligible || action.isEligible(item))
    );
  }
  function useHasAPossibleBulkAction(actions2, item) {
    return (0, import_element74.useMemo)(
      () => hasAPossibleBulkAction(actions2, item),
      [actions2, item]
    );
  }
  function useSomeItemHasAPossibleBulkAction(actions2, data) {
    return (0, import_element74.useMemo)(
      () => data.some((item) => hasAPossibleBulkAction(actions2, item)),
      [actions2, data]
    );
  }
  function BulkSelectionCheckbox({
    selection,
    onChangeSelection,
    data,
    actions: actions2,
    getItemId: getItemId2,
    disableSelectAll = false
  }) {
    const selectableItems = (0, import_element74.useMemo)(() => {
      return data.filter((item) => {
        return actions2.some(
          (action) => action.supportsBulk && (!action.isEligible || action.isEligible(item))
        );
      });
    }, [data, actions2]);
    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_runtime179.jsx)(
        import_components29.CheckboxControl,
        {
          className: "dataviews-view-table-selection-checkbox",
          checked: hasSelection,
          disabled: !hasSelection,
          onChange: () => {
            onChangeSelection([]);
          },
          "aria-label": (0, import_i18n83.__)("Deselect all")
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime179.jsx)(
      import_components29.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_i18n83.__)("Deselect all") : (0, import_i18n83.__)("Select all")
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-layouts/table/column-header-menu.mjs
  var import_i18n84 = __toESM(require_i18n(), 1);
  var import_components30 = __toESM(require_components(), 1);
  var import_element75 = __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(
      (f3) => !togglableFields.includes(f3.id) && f3.type !== "media" && f3.enableHiding !== false
    );
  }

  // packages/dataviews/build-module/components/dataviews-layouts/table/column-header-menu.mjs
  var import_jsx_runtime180 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu2 } = unlock5(import_components30.privateApis);
  function WithMenuSeparators({ children }) {
    return import_element75.Children.toArray(children).filter(Boolean).map((child, i3) => /* @__PURE__ */ (0, import_jsx_runtime180.jsxs)(import_element75.Fragment, { children: [
      i3 > 0 && /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.Separator, {}),
      child
    ] }, i3));
  }
  var _HeaderMenu = (0, import_element75.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((f3) => f3.id === fieldId);
    const { setIsShowingFilter } = (0, import_element75.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(
      (f3) => !visibleFieldIds.includes(f3.id)
    );
    const canInsert = (canInsertLeft || canInsertRight) && !!hiddenFields.length;
    const isRtl = (0, import_i18n84.isRTL)();
    return /* @__PURE__ */ (0, import_jsx_runtime180.jsxs)(Menu2, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime180.jsxs)(
        Menu2.TriggerButton,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
            import_components30.Button,
            {
              size: "compact",
              className: "dataviews-view-table-header-button",
              ref,
              variant: "tertiary"
            }
          ),
          children: [
            header,
            view.sort && isSorted && /* @__PURE__ */ (0, import_jsx_runtime180.jsx)("span", { "aria-hidden": "true", children: sortArrows[view.sort.direction] })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.Popover, { style: { minWidth: "240px" }, children: /* @__PURE__ */ (0, import_jsx_runtime180.jsxs)(WithMenuSeparators, { children: [
        isSortable && /* @__PURE__ */ (0, import_jsx_runtime180.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_runtime180.jsx)(
              Menu2.RadioItem,
              {
                name: "view-table-sorting",
                value,
                checked: isChecked,
                onChange: () => {
                  onChangeView({
                    ...view,
                    sort: {
                      field: fieldId,
                      direction
                    },
                    showLevels: false
                  });
                },
                children: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.ItemLabel, { children: sortLabels[direction] })
              },
              value
            );
          }
        ) }),
        canAddFilter && /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.Group, { children: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
          Menu2.Item,
          {
            prefix: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(import_components30.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_runtime180.jsx)(Menu2.ItemLabel, { children: (0, import_i18n84.__)("Add filter") })
          }
        ) }),
        (canMove || isHidable || canInsert) && field && /* @__PURE__ */ (0, import_jsx_runtime180.jsxs)(Menu2.Group, { children: [
          canMove && /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
            Menu2.Item,
            {
              prefix: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(import_components30.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_runtime180.jsx)(Menu2.ItemLabel, { children: (0, import_i18n84.__)("Move left") })
            }
          ),
          canMove && /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
            Menu2.Item,
            {
              prefix: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(import_components30.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_runtime180.jsx)(Menu2.ItemLabel, { children: (0, import_i18n84.__)("Move right") })
            }
          ),
          canInsertLeft && !!hiddenFields.length && /* @__PURE__ */ (0, import_jsx_runtime180.jsxs)(Menu2, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.SubmenuTriggerItem, { children: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.ItemLabel, { children: (0, import_i18n84.__)("Insert left") }) }),
            /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.Popover, { children: hiddenFields.map((hiddenField) => {
              const insertIndex = isRtl ? index2 + 1 : index2;
              return /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
                Menu2.Item,
                {
                  onClick: () => {
                    onChangeView({
                      ...view,
                      fields: [
                        ...visibleFieldIds.slice(
                          0,
                          insertIndex
                        ),
                        hiddenField.id,
                        ...visibleFieldIds.slice(
                          insertIndex
                        )
                      ]
                    });
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.ItemLabel, { children: hiddenField.label })
                },
                hiddenField.id
              );
            }) })
          ] }),
          canInsertRight && !!hiddenFields.length && /* @__PURE__ */ (0, import_jsx_runtime180.jsxs)(Menu2, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.SubmenuTriggerItem, { children: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.ItemLabel, { children: (0, import_i18n84.__)("Insert right") }) }),
            /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.Popover, { children: hiddenFields.map((hiddenField) => {
              const insertIndex = isRtl ? index2 : index2 + 1;
              return /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
                Menu2.Item,
                {
                  onClick: () => {
                    onChangeView({
                      ...view,
                      fields: [
                        ...visibleFieldIds.slice(
                          0,
                          insertIndex
                        ),
                        hiddenField.id,
                        ...visibleFieldIds.slice(
                          insertIndex
                        )
                      ]
                    });
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.ItemLabel, { children: hiddenField.label })
                },
                hiddenField.id
              );
            }) })
          ] }),
          isHidable && field && /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(
            Menu2.Item,
            {
              prefix: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(import_components30.Icon, { icon: unseen_default }),
              onClick: () => {
                onHide(field);
                onChangeView({
                  ...view,
                  fields: visibleFieldIds.filter(
                    (id) => id !== fieldId
                  )
                });
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime180.jsx)(Menu2.ItemLabel, { children: (0, import_i18n84.__)("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_element76 = __toESM(require_element(), 1);
  var import_jsx_runtime181 = __toESM(require_jsx_runtime(), 1);
  function getClickableItemProps({
    item,
    isItemClickable: isItemClickable2,
    onClickItem,
    className
  }) {
    if (!isItemClickable2(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: isItemClickable2,
    onClickItem,
    renderItemLink,
    className,
    children,
    ...extraProps
  }) {
    if (!isItemClickable2(item)) {
      return /* @__PURE__ */ (0, import_jsx_runtime181.jsx)("div", { className, ...extraProps, children });
    }
    if (renderItemLink) {
      const renderedElement = renderItemLink({
        item,
        className: `${className} ${className}--clickable`,
        ...extraProps,
        children
      });
      return (0, import_element76.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: isItemClickable2,
      onClickItem,
      className
    });
    return /* @__PURE__ */ (0, import_jsx_runtime181.jsx)("div", { ...clickProps, ...extraProps, children });
  }

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

  // packages/dataviews/build-module/components/dataviews-layouts/table/use-scroll-state.mjs
  var import_element77 = __toESM(require_element(), 1);
  var import_i18n85 = __toESM(require_i18n(), 1);
  var isScrolledToEnd = (element) => {
    if ((0, import_i18n85.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_element77.useState)(false);
    const [isVerticallyScrolled, setIsVerticallyScrolled] = (0, import_element77.useState)(false);
    const handleScroll = (0, import_element77.useCallback)(() => {
      const scrollContainer = scrollContainerRef.current;
      if (!scrollContainer) {
        return;
      }
      if (enabledHorizontal) {
        setIsHorizontalScrollEnd(isScrolledToEnd(scrollContainer));
      }
      setIsVerticallyScrolled(scrollContainer.scrollTop > 0);
    }, [scrollContainerRef, enabledHorizontal]);
    (0, import_element77.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_element78 = __toESM(require_element(), 1);
  var import_keycodes = __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 distance2 = Math.abs(index2 - targetIndex);
      if (distance2 < closestDistance) {
        closestDistance = distance2;
        closestId = id;
      }
    });
    return closestId;
  }
  function useSelectionProps({
    data,
    actions: actions2,
    getItemId: getItemId2,
    selection,
    onChangeSelection
  }) {
    const gestureRef = (0, import_element78.useRef)(null);
    const isTouchDeviceRef = (0, import_element78.useRef)(false);
    (0, import_element78.useEffect)(() => {
      const markTouchDevice = () => {
        isTouchDeviceRef.current = true;
      };
      document.addEventListener("touchstart", markTouchDevice, {
        once: true
      });
      return () => document.removeEventListener("touchstart", markTouchDevice);
    }, []);
    const selectableIds = data.filter((item) => hasAPossibleBulkAction(actions2, 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_keycodes.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_components31 = __toESM(require_components(), 1);
  var import_i18n86 = __toESM(require_i18n(), 1);
  var import_element79 = __toESM(require_element(), 1);
  var import_jsx_runtime183 = __toESM(require_jsx_runtime(), 1);
  function FieldItem({
    field,
    isVisible: isVisible2,
    onToggleVisibility
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(import_components31.__experimentalItem, { onClick: field.enableHiding ? onToggleVisibility : void 0, children: /* @__PURE__ */ (0, import_jsx_runtime183.jsxs)(Stack, { direction: "row", gap: "sm", justify: "flex-start", align: "center", children: [
      /* @__PURE__ */ (0, import_jsx_runtime183.jsx)("div", { style: { height: 24, width: 24 }, children: isVisible2 && /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(import_components31.Icon, { icon: check_default }) }),
      /* @__PURE__ */ (0, import_jsx_runtime183.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_element79.useContext)(dataviews_context_default);
    const regularFields = getHideableFields(view, fields2);
    if (!regularFields?.length) {
      return null;
    }
    const titleField2 = fields2.find((f3) => f3.id === view.titleField);
    const previewField = fields2.find((f3) => f3.id === view.mediaField);
    const descriptionField3 = fields2.find(
      (f3) => f3.id === view.descriptionField
    );
    const lockedFields = [
      {
        field: titleField2,
        isVisibleFlag: "showTitle"
      },
      {
        field: previewField,
        isVisibleFlag: "showMedia"
      },
      {
        field: descriptionField3,
        isVisibleFlag: "showDescription"
      }
    ].filter(({ field }) => isDefined(field));
    const visibleFieldIds = view.fields ?? [];
    const visibleRegularFieldsCount = regularFields.filter(
      (f3) => visibleFieldIds.includes(f3.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_runtime183.jsxs)(Stack, { direction: "column", className: "dataviews-field-control", children: [
      showLabel && /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(import_components31.BaseControl.VisualLabel, { children: (0, import_i18n86.__)("Properties") }),
      /* @__PURE__ */ (0, import_jsx_runtime183.jsx)(
        Stack,
        {
          direction: "column",
          className: "dataviews-view-config__properties",
          children: /* @__PURE__ */ (0, import_jsx_runtime183.jsxs)(import_components31.__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_runtime183.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_runtime183.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_element80 = __toESM(require_element(), 1);
  function useDelayedLoading(isLoading, options = { delay: 400 }) {
    const [showLoader, setShowLoader] = (0, import_element80.useState)(false);
    (0, import_element80.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_runtime184 = __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((f3) => f3.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_runtime184.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(field.render, { item, field }) });
  }
  function TableRow({
    hasBulkActions,
    item,
    level,
    actions: actions2,
    fields: fields2,
    id,
    view,
    titleField: titleField2,
    mediaField,
    descriptionField: descriptionField3,
    selection,
    getItemId: getItemId2,
    isItemClickable: isItemClickable2,
    onClickItem,
    renderItemLink,
    onChangeSelection,
    onMouseDown,
    onClickCapture,
    isActionsColumnSticky,
    posinset
  }) {
    const { paginationInfo } = (0, import_element81.useContext)(dataviews_context_default);
    const hasPossibleBulkAction = useHasAPossibleBulkAction(actions2, item);
    const isSelected2 = hasPossibleBulkAction && selection.includes(id);
    const {
      showTitle = true,
      showMedia = true,
      showDescription = true,
      infiniteScrollEnabled
    } = view;
    const columns = view.fields ?? [];
    const hasPrimaryColumn = titleField2 && showTitle || mediaField && showMedia || descriptionField3 && showDescription;
    return /* @__PURE__ */ (0, import_jsx_runtime184.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_keycodes2.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_runtime184.jsx)("td", { className: "dataviews-view-table__checkbox-column", children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("div", { className: "dataviews-view-table__cell-content-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
            DataViewsSelectionCheckbox,
            {
              item,
              selection,
              onChangeSelection,
              getItemId: getItemId2,
              titleField: titleField2,
              disabled: !hasPossibleBulkAction
            }
          ) }) }),
          hasPrimaryColumn && /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("td", { children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
            column_primary_default,
            {
              item,
              level,
              titleField: showTitle ? titleField2 : void 0,
              mediaField: showMedia ? mediaField : void 0,
              descriptionField: showDescription ? descriptionField3 : void 0,
              isItemClickable: isItemClickable2,
              onClickItem,
              renderItemLink
            }
          ) }),
          columns.map((column) => {
            const { width, maxWidth, minWidth, align } = view.layout?.styles?.[column] ?? {};
            const field = fields2.find((f3) => f3.id === column);
            const effectiveAlign = getEffectiveAlign(align, field?.type);
            return /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
              "td",
              {
                style: {
                  width,
                  maxWidth,
                  minWidth
                },
                children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
                  TableColumnField,
                  {
                    fields: fields2,
                    item,
                    column,
                    align: effectiveAlign
                  }
                )
              },
              column
            );
          }),
          !!actions2?.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_runtime184.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: (e3) => e3.stopPropagation(),
              children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(ItemActions, { item, actions: actions2 })
            }
          )
        ]
      }
    );
  }
  function ViewTable({
    actions: actions2,
    data,
    fields: fields2,
    getItemId: getItemId2,
    getItemLevel,
    isLoading = false,
    onChangeView,
    onChangeSelection,
    selection,
    setOpenedFilter,
    onClickItem,
    isItemClickable: isItemClickable2,
    renderItemLink,
    view,
    className,
    empty
  }) {
    const { containerRef } = (0, import_element81.useContext)(dataviews_context_default);
    const isDelayedLoading = useDelayedLoading(isLoading);
    const groupField = view.groupBy?.field ? fields2.find((f3) => f3.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: actions2,
      getItemId: getItemId2,
      selection,
      onChangeSelection
    });
    const headerMenuRefs = (0, import_element81.useRef)(/* @__PURE__ */ new Map());
    const headerMenuToFocusRef = (0, import_element81.useRef)(void 0);
    const [nextHeaderMenuToFocus, setNextHeaderMenuToFocus] = (0, import_element81.useState)();
    const [contextMenuAnchor, setContextMenuAnchor] = (0, import_element81.useState)(null);
    (0, import_element81.useEffect)(() => {
      if (headerMenuToFocusRef.current) {
        headerMenuToFocusRef.current.focus();
        headerMenuToFocusRef.current = void 0;
      }
    });
    const tableNoticeId = (0, import_element81.useId)();
    const { isHorizontalScrollEnd, isVerticallyScrolled } = useScrollState({
      scrollContainerRef: containerRef,
      enabledHorizontal: !!actions2?.length
    });
    const hasBulkActions = useSomeItemHasAPossibleBulkAction(actions2, 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 titleField2 = fields2.find((field) => field.id === view.titleField);
    const mediaField = fields2.find((field) => field.id === view.mediaField);
    const descriptionField3 = fields2.find(
      (field) => field.id === view.descriptionField
    );
    const { showTitle = true, showMedia = true, showDescription = true } = view;
    const hasPrimaryColumn = titleField2 && showTitle || mediaField && showMedia || descriptionField3 && 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_i18n87.isRTL)();
    if (!hasData) {
      return /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
        "div",
        {
          className: clsx_default("dataviews-no-results", {
            "is-refreshing": isDelayedLoading
          }),
          id: tableNoticeId,
          children: empty
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime184.jsxs)(import_jsx_runtime184.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime184.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_runtime184.jsxs)("colgroup", { children: [
              hasBulkActions && /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("col", { className: "dataviews-view-table__col-checkbox" }),
              hasPrimaryColumn && /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("col", { className: "dataviews-view-table__col-first-data" }),
              columns.map((column, index2) => /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
                "col",
                {
                  className: clsx_default(
                    `dataviews-view-table__col-${column}`,
                    {
                      "dataviews-view-table__col-expand": !hasPrimaryColumn && index2 === columns.length - 1
                    }
                  )
                },
                `col-${column}`
              )),
              !!actions2?.length && /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("col", { className: "dataviews-view-table__col-actions" })
            ] }),
            contextMenuAnchor && /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
              import_components32.Popover,
              {
                anchor: contextMenuAnchor,
                onClose: () => setContextMenuAnchor(null),
                placement: "bottom-start",
                children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(PropertiesSection, { showLabel: false })
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
              "thead",
              {
                className: clsx_default({
                  "dataviews-view-table__thead--stuck": isVerticallyScrolled
                }),
                onContextMenu: handleHeaderContextMenu,
                children: /* @__PURE__ */ (0, import_jsx_runtime184.jsxs)("tr", { className: "dataviews-view-table__row", children: [
                  hasBulkActions && /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
                    "th",
                    {
                      className: "dataviews-view-table__checkbox-column",
                      scope: "col",
                      onContextMenu: handleHeaderContextMenu,
                      children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
                        BulkSelectionCheckbox,
                        {
                          selection,
                          onChangeSelection,
                          data,
                          actions: actions2,
                          getItemId: getItemId2
                        }
                      )
                    }
                  ),
                  hasPrimaryColumn && /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("th", { scope: "col", children: titleField2 && /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
                    column_header_menu_default,
                    {
                      ref: headerMenuRef(
                        titleField2.id,
                        0
                      ),
                      fieldId: titleField2.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(
                      (f3) => f3.id === column
                    );
                    const effectiveAlign = getEffectiveAlign(
                      align,
                      field?.type
                    );
                    const canInsertOrMove = view.layout?.enableMoving ?? true;
                    return /* @__PURE__ */ (0, import_jsx_runtime184.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_runtime184.jsx)(
                          column_header_menu_default,
                          {
                            ref: headerMenuRef(column, index2),
                            fieldId: column,
                            view,
                            fields: fields2,
                            onChangeView,
                            onHide,
                            setOpenedFilter,
                            canMove: canInsertOrMove,
                            canInsertLeft: canInsertOrMove,
                            canInsertRight: canInsertOrMove
                          }
                        )
                      },
                      column
                    );
                  }),
                  !!actions2?.length && /* @__PURE__ */ (0, import_jsx_runtime184.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_runtime184.jsx)("span", { className: "dataviews-view-table-header", children: (0, import_i18n87.__)("Actions") })
                    }
                  )
                ] })
              }
            ),
            hasData && groupField && dataByGroup ? Array.from(dataByGroup.entries()).map(
              ([groupName, groupItems]) => /* @__PURE__ */ (0, import_jsx_runtime184.jsxs)("tbody", { children: [
                /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("tr", { className: "dataviews-view-table__group-header-row", children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
                  "td",
                  {
                    colSpan: columns.length + (hasPrimaryColumn ? 1 : 0) + (hasBulkActions ? 1 : 0) + (actions2?.length ? 1 : 0),
                    className: "dataviews-view-table__group-header-cell",
                    children: view.groupBy?.showLabel === false ? groupName : (0, import_i18n87.sprintf)(
                      // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                      (0, import_i18n87.__)("%1$s: %2$s"),
                      groupField.label,
                      groupName
                    )
                  }
                ) }),
                groupItems.map((item, index2) => {
                  const id = getItemId2(item) || index2.toString();
                  return /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
                    TableRow,
                    {
                      item,
                      level: view.showLevels && typeof getItemLevel === "function" ? getItemLevel(item) : void 0,
                      hasBulkActions,
                      actions: actions2,
                      fields: fields2,
                      id,
                      view,
                      titleField: titleField2,
                      mediaField,
                      descriptionField: descriptionField3,
                      selection,
                      getItemId: getItemId2,
                      onChangeSelection,
                      ...getSelectionProps(id),
                      onClickItem,
                      renderItemLink,
                      isItemClickable: isItemClickable2,
                      isActionsColumnSticky: !isHorizontalScrollEnd
                    },
                    getItemId2(item)
                  );
                })
              ] }, `group-${groupName}`)
            ) : /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("tbody", { children: hasData && data.map((item, index2) => {
              const id = getItemId2(item) || index2.toString();
              return /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(
                TableRow,
                {
                  item,
                  level: view.showLevels && typeof getItemLevel === "function" ? getItemLevel(item) : void 0,
                  hasBulkActions,
                  actions: actions2,
                  fields: fields2,
                  id,
                  view,
                  titleField: titleField2,
                  mediaField,
                  descriptionField: descriptionField3,
                  selection,
                  getItemId: getItemId2,
                  onChangeSelection,
                  ...getSelectionProps(id),
                  onClickItem,
                  renderItemLink,
                  isItemClickable: isItemClickable2,
                  isActionsColumnSticky: !isHorizontalScrollEnd,
                  posinset: isInfiniteScroll ? index2 + 1 : void 0
                },
                getItemId2(item)
              );
            }) })
          ]
        }
      ),
      isInfiniteScroll && isLoading && /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("div", { className: "dataviews-loading", id: tableNoticeId, children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime184.jsx)(import_components32.Spinner, {}) }) })
    ] });
  }
  var table_default = ViewTable;

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

  // packages/dataviews/build-module/components/dataviews-layouts/grid/composite-grid.mjs
  var import_components34 = __toESM(require_components(), 1);
  var import_i18n89 = __toESM(require_i18n(), 1);
  var import_compose9 = __toESM(require_compose(), 1);
  var import_element85 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataviews-layouts/grid/preview-size-picker.mjs
  var import_components33 = __toESM(require_components(), 1);
  var import_i18n88 = __toESM(require_i18n(), 1);
  var import_element82 = __toESM(require_element(), 1);
  var import_jsx_runtime185 = __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_element82.useContext)(dataviews_context_default);
    const view = context.view;
    return (0, import_element82.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_element83 = __toESM(require_element(), 1);
  var import_jsx_runtime186 = __toESM(require_jsx_runtime(), 1);
  var GridItems = (0, import_element83.forwardRef)(({ className, previewSize, ...props }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime186.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_element84 = __toESM(require_element(), 1);
  function useIntersectionObserver(elementRef, posinset) {
    const { intersectionObserver } = (0, import_element84.useContext)(dataviews_context_default);
    (0, import_element84.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_runtime187 = __toESM(require_jsx_runtime(), 1);
  var { Badge: WCBadge2 } = unlock5(import_components34.privateApis);
  function chunk(array, size4) {
    const chunks = [];
    for (let i3 = 0, j2 = array.length; i3 < j2; i3 += size4) {
      chunks.push(array.slice(i3, i3 + size4));
    }
    return chunks;
  }
  var GridItem = (0, import_element85.forwardRef)(
    function GridItem2({
      view,
      selection,
      onChangeSelection,
      onClickItem,
      isItemClickable: isItemClickable2,
      renderItemLink,
      getItemId: getItemId2,
      item,
      actions: actions2,
      mediaField,
      titleField: titleField2,
      descriptionField: descriptionField3,
      regularFields,
      badgeFields,
      hasBulkActions,
      config: config2,
      posinset,
      setsize,
      ...props
    }, forwardedRef) {
      const {
        showTitle = true,
        showMedia = true,
        showDescription = true
      } = view;
      const hasBulkAction = useHasAPossibleBulkAction(actions2, item);
      const id = getItemId2(item);
      const elementRef = (0, import_element85.useRef)(null);
      const setRefs = (0, import_element85.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_compose9.useInstanceId)(GridItem2);
      const isSelected2 = selection.includes(id);
      const mediaPlaceholder = /* @__PURE__ */ (0, import_jsx_runtime187.jsx)("span", { className: "dataviews-view-grid__media-placeholder" });
      const rendersMediaField = showMedia && mediaField?.render;
      const renderedMediaField = rendersMediaField ? /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
        mediaField.render,
        {
          item,
          field: mediaField,
          config: config2
        }
      ) : mediaPlaceholder;
      const renderedTitleField = showTitle && titleField2?.render ? /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(titleField2.render, { item, field: titleField2 }) : null;
      let mediaA11yProps;
      let titleA11yProps;
      if (isItemClickable2(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_i18n89.__)("Navigate to item")
          };
        }
      }
      return /* @__PURE__ */ (0, import_jsx_runtime187.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_runtime187.jsx)(
              ItemClickWrapper,
              {
                item,
                isItemClickable: isItemClickable2,
                onClickItem,
                renderItemLink,
                className: clsx_default("dataviews-view-grid__media", {
                  "dataviews-view-grid__media--placeholder": !rendersMediaField
                }),
                ...mediaA11yProps,
                children: renderedMediaField
              }
            ),
            hasBulkActions && /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
              DataViewsSelectionCheckbox,
              {
                item,
                selection,
                onChangeSelection,
                getItemId: getItemId2,
                titleField: titleField2,
                disabled: !hasBulkAction
              }
            ),
            !!actions2?.length && /* @__PURE__ */ (0, import_jsx_runtime187.jsx)("div", { className: "dataviews-view-grid__media-actions", children: /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
              ItemActions,
              {
                item,
                actions: actions2,
                isCompact: true
              }
            ) }),
            showTitle && /* @__PURE__ */ (0, import_jsx_runtime187.jsx)("div", { className: "dataviews-view-grid__title-actions", children: /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
              ItemClickWrapper,
              {
                item,
                isItemClickable: isItemClickable2,
                onClickItem,
                renderItemLink,
                className: "dataviews-view-grid__title-field dataviews-title-field",
                ...titleA11yProps,
                title: titleField2?.getValueFormatted({
                  item,
                  field: titleField2
                }) || void 0,
                children: renderedTitleField
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime187.jsxs)(Stack, { direction: "column", gap: "xs", children: [
              showDescription && descriptionField3?.render && /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
                descriptionField3.render,
                {
                  item,
                  field: descriptionField3
                }
              ),
              !!badgeFields?.length && /* @__PURE__ */ (0, import_jsx_runtime187.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_runtime187.jsx)(
                      WCBadge2,
                      {
                        className: "dataviews-view-grid__field-value",
                        children: /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
                          field.render,
                          {
                            item,
                            field
                          }
                        )
                      },
                      field.id
                    );
                  })
                }
              ),
              !!regularFields?.length && /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
                Stack,
                {
                  direction: "column",
                  className: "dataviews-view-grid__fields",
                  gap: "xs",
                  children: regularFields.map((field) => {
                    return /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
                      import_components34.Flex,
                      {
                        className: "dataviews-view-grid__field",
                        gap: 1,
                        justify: "flex-start",
                        expanded: true,
                        style: { height: "auto" },
                        direction: "row",
                        children: /* @__PURE__ */ (0, import_jsx_runtime187.jsxs)(import_jsx_runtime187.Fragment, { children: [
                          /* @__PURE__ */ (0, import_jsx_runtime187.jsxs)(tooltip_exports.Root, { children: [
                            /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
                              tooltip_exports.Trigger,
                              {
                                render: /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(import_components34.FlexItem, { className: "dataviews-view-grid__field-name", children: field.header })
                              }
                            ),
                            /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(tooltip_exports.Popup, { children: field.label })
                          ] }),
                          /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
                            import_components34.FlexItem,
                            {
                              className: "dataviews-view-grid__field-value",
                              style: { maxHeight: "none" },
                              children: /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
                                field.render,
                                {
                                  item,
                                  field
                                }
                              )
                            }
                          )
                        ] })
                      },
                      field.id
                    );
                  })
                }
              )
            ] })
          ]
        }
      );
    }
  );
  function CompositeGrid({
    data,
    isInfiniteScroll,
    className,
    inert,
    isLoading,
    view,
    fields: fields2,
    selection,
    onChangeSelection,
    onClickItem,
    isItemClickable: isItemClickable2,
    renderItemLink,
    getItemId: getItemId2,
    actions: actions2,
    getSelectionProps
  }) {
    const { paginationInfo, resizeObserverRef } = (0, import_element85.useContext)(dataviews_context_default);
    const gridColumns = useGridColumns();
    const hasBulkActions = useSomeItemHasAPossibleBulkAction(actions2, data);
    const titleField2 = fields2.find(
      (field) => field.id === view?.titleField
    );
    const mediaField = fields2.find(
      (field) => field.id === view?.mediaField
    );
    const descriptionField3 = fields2.find(
      (field) => field.id === view?.descriptionField
    );
    const otherFields = view.fields ?? [];
    const { regularFields, badgeFields } = otherFields.reduce(
      (accumulator, fieldId) => {
        const field = fields2.find((f3) => f3.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_runtime187.jsxs)(import_jsx_runtime187.Fragment, {
      // Render infinite scroll layout (no rows, feed semantics)
      children: [
        isInfiniteScroll && /* @__PURE__ */ (0, import_jsx_runtime187.jsxs)(
          import_components34.Composite,
          {
            render: /* @__PURE__ */ (0, import_jsx_runtime187.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_runtime187.jsx)(
                  import_components34.Composite.Item,
                  {
                    render: (props) => /* @__PURE__ */ (0, import_jsx_runtime187.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_runtime187.jsx)(
                  import_components34.Composite.Item,
                  {
                    render: (props) => /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
                      GridItem,
                      {
                        ...props,
                        id: itemId,
                        role: "article",
                        view,
                        selection,
                        onChangeSelection,
                        onClickItem,
                        isItemClickable: isItemClickable2,
                        renderItemLink,
                        getItemId: getItemId2,
                        item,
                        actions: actions2,
                        onMouseDown: (event) => {
                          props.onMouseDown?.(event);
                          selectionProps.onMouseDown(
                            event
                          );
                        },
                        onClickCapture: (event) => {
                          props.onClickCapture?.(event);
                          selectionProps.onClickCapture(
                            event
                          );
                        },
                        mediaField,
                        titleField: titleField2,
                        descriptionField: descriptionField3,
                        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_runtime187.jsx)(
          import_components34.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, i3) => /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
              import_components34.Composite.Row,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
                  "div",
                  {
                    role: "row",
                    "aria-rowindex": i3 + 1,
                    "aria-label": (0, import_i18n89.sprintf)(
                      /* translators: %d: The row number in the grid */
                      (0, import_i18n89.__)("Row %d"),
                      i3 + 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_runtime187.jsx)(
                    import_components34.Composite.Item,
                    {
                      render: (props) => /* @__PURE__ */ (0, import_jsx_runtime187.jsx)(
                        GridItem,
                        {
                          ...props,
                          id: itemId,
                          role: "gridcell",
                          view,
                          selection,
                          onChangeSelection,
                          onClickItem,
                          isItemClickable: isItemClickable2,
                          renderItemLink,
                          getItemId: getItemId2,
                          item,
                          actions: actions2,
                          onMouseDown: (event) => {
                            props.onMouseDown?.(
                              event
                            );
                            selectionProps.onMouseDown(
                              event
                            );
                          },
                          onClickCapture: (event) => {
                            props.onClickCapture?.(
                              event
                            );
                            selectionProps.onClickCapture(
                              event
                            );
                          },
                          mediaField,
                          titleField: titleField2,
                          descriptionField: descriptionField3,
                          regularFields,
                          badgeFields,
                          hasBulkActions,
                          config: {
                            sizes: size4
                          }
                        }
                      )
                    },
                    itemId
                  );
                })
              },
              i3
            ))
          }
        )
      ]
    });
  }

  // packages/dataviews/build-module/components/dataviews-layouts/grid/index.mjs
  var import_jsx_runtime188 = __toESM(require_jsx_runtime(), 1);
  function ViewGrid({
    actions: actions2,
    data,
    fields: fields2,
    getItemId: getItemId2,
    isLoading,
    onChangeSelection,
    onClickItem,
    isItemClickable: isItemClickable2,
    renderItemLink,
    selection,
    view,
    className,
    empty
  }) {
    const isDelayedLoading = useDelayedLoading(!!isLoading);
    const hasData = !!data?.length;
    const groupField = view.groupBy?.field ? fields2.find((f3) => f3.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: actions2,
      getItemId: getItemId2,
      selection,
      onChangeSelection
    });
    if (!hasData) {
      return /* @__PURE__ */ (0, import_jsx_runtime188.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: isItemClickable2,
      renderItemLink,
      getItemId: getItemId2,
      actions: actions2,
      getSelectionProps
    };
    return /* @__PURE__ */ (0, import_jsx_runtime188.jsxs)(import_jsx_runtime188.Fragment, {
      // Render multiple groups.
      children: [
        hasData && groupField && dataByGroup && /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(Stack, { direction: "column", gap: "lg", children: Array.from(dataByGroup.entries()).map(
          ([groupName, groupItems]) => /* @__PURE__ */ (0, import_jsx_runtime188.jsxs)(
            Stack,
            {
              direction: "column",
              gap: "sm",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime188.jsx)("h3", { className: "dataviews-view-grid__group-header", children: view.groupBy?.showLabel === false ? groupName : (0, import_i18n90.sprintf)(
                  // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                  (0, import_i18n90.__)("%1$s: %2$s"),
                  groupField.label,
                  groupName
                ) }),
                /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
                  CompositeGrid,
                  {
                    ...gridProps,
                    data: groupItems,
                    isInfiniteScroll: false
                  }
                )
              ]
            },
            groupName
          )
        ) }),
        // Render a single grid with all data.
        !dataByGroup && /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(
          CompositeGrid,
          {
            ...gridProps,
            data,
            isInfiniteScroll: !!isInfiniteScroll
          }
        ),
        isInfiniteScroll && isLoading && /* @__PURE__ */ (0, import_jsx_runtime188.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime188.jsx)(import_components35.Spinner, {}) })
      ]
    });
  }
  var grid_default = ViewGrid;

  // packages/dataviews/build-module/components/dataviews-layouts/list/index.mjs
  var import_compose10 = __toESM(require_compose(), 1);
  var import_components36 = __toESM(require_components(), 1);
  var import_element86 = __toESM(require_element(), 1);
  var import_i18n91 = __toESM(require_i18n(), 1);
  var import_data35 = __toESM(require_data(), 1);
  var import_jsx_runtime189 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu3 } = unlock5(import_components36.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_data35.useRegistry)();
    const [isModalOpen, setIsModalOpen] = (0, import_element86.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_runtime189.jsx)("div", { role: "gridcell", children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
      import_components36.Composite.Item,
      {
        id: compositeItemId,
        render: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
          import_components36.Button,
          {
            disabled: !!primaryAction.disabled,
            accessibleWhenDisabled: true,
            text: label,
            size: "small",
            onClick: () => setIsModalOpen(true)
          }
        ),
        children: isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
          ActionModal,
          {
            action: primaryAction,
            items: [item],
            closeModal: () => setIsModalOpen(false)
          }
        )
      }
    ) }, primaryAction.id) : /* @__PURE__ */ (0, import_jsx_runtime189.jsx)("div", { role: "gridcell", children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
      import_components36.Composite.Item,
      {
        id: compositeItemId,
        render: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
          import_components36.Button,
          {
            disabled: !!primaryAction.disabled,
            accessibleWhenDisabled: true,
            size: "small",
            onClick: () => {
              primaryAction.callback([item], { registry });
            },
            children: label
          }
        )
      }
    ) }, primaryAction.id);
  }
  function ListItem({
    view,
    actions: actions2,
    idPrefix,
    isSelected: isSelected2,
    item,
    titleField: titleField2,
    mediaField,
    descriptionField: descriptionField3,
    onSelect,
    otherFields,
    onDropdownTriggerKeyDown,
    posinset
  }) {
    const {
      showTitle = true,
      showMedia = true,
      showDescription = true,
      infiniteScrollEnabled
    } = view;
    const itemRef = (0, import_element86.useRef)(null);
    const labelId = `${idPrefix}-label`;
    const descriptionId = `${idPrefix}-description`;
    const registry = (0, import_data35.useRegistry)();
    const [isHovered, setIsHovered] = (0, import_element86.useState)(false);
    const [activeModalAction, setActiveModalAction] = (0, import_element86.useState)(
      null
    );
    const handleHover = ({ type }) => {
      const isHover = type === "mouseenter";
      setIsHovered(isHover);
    };
    const { paginationInfo } = (0, import_element86.useContext)(dataviews_context_default);
    (0, import_element86.useEffect)(() => {
      if (isSelected2) {
        itemRef.current?.scrollIntoView({
          behavior: "auto",
          block: "nearest",
          inline: "nearest"
        });
      }
    }, [isSelected2]);
    const { primaryAction, eligibleActions } = (0, import_element86.useMemo)(() => {
      const _eligibleActions = actions2.filter(
        (action) => !action.isEligible || action.isEligible(item)
      );
      const _primaryActions = _eligibleActions.filter(
        (action) => action.isPrimary
      );
      return {
        primaryAction: _primaryActions[0],
        eligibleActions: _eligibleActions
      };
    }, [actions2, item]);
    const hasOnlyOnePrimaryAction = primaryAction && actions2.length === 1;
    const renderedMediaField = showMedia && mediaField?.render ? /* @__PURE__ */ (0, import_jsx_runtime189.jsx)("div", { className: "dataviews-view-list__media-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
      mediaField.render,
      {
        item,
        field: mediaField,
        config: { sizes: "52px" }
      }
    ) }) : null;
    const renderedTitleField = showTitle && titleField2?.render ? /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(titleField2.render, { item, field: titleField2 }) : null;
    const renderDescription = showDescription && descriptionField3?.render;
    const hasOnlyMediaAndTitle = !!renderedMediaField && !renderDescription && !otherFields.length;
    const usedActions = eligibleActions?.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime189.jsxs)(
      Stack,
      {
        direction: "row",
        gap: "md",
        className: "dataviews-view-list__item-actions",
        children: [
          primaryAction && /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
            PrimaryActionGridCell,
            {
              idPrefix,
              primaryAction,
              item
            }
          ),
          !hasOnlyOnePrimaryAction && /* @__PURE__ */ (0, import_jsx_runtime189.jsxs)("div", { role: "gridcell", children: [
            /* @__PURE__ */ (0, import_jsx_runtime189.jsxs)(Menu3, { placement: "bottom-end", children: [
              /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                Menu3.TriggerButton,
                {
                  render: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                    import_components36.Composite.Item,
                    {
                      id: generateDropdownTriggerCompositeId(
                        idPrefix
                      ),
                      render: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                        import_components36.Button,
                        {
                          size: "small",
                          icon: more_vertical_default,
                          label: (0, import_i18n91.__)("Actions"),
                          accessibleWhenDisabled: true,
                          disabled: !actions2.length,
                          onKeyDown: onDropdownTriggerKeyDown
                        }
                      )
                    }
                  )
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(Menu3.Popover, { children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                ActionsMenuGroup,
                {
                  actions: eligibleActions,
                  item,
                  registry,
                  setActiveModalAction
                }
              ) })
            ] }),
            !!activeModalAction && /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
              ActionModal,
              {
                action: activeModalAction,
                items: [item],
                closeModal: () => setActiveModalAction(null)
              }
            )
          ] })
        ]
      }
    );
    return /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
      import_components36.Composite.Row,
      {
        ref: itemRef,
        render: (
          /* aria-posinset breaks Composite.Row if passed to it directly. */
          /* @__PURE__ */ (0, import_jsx_runtime189.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_runtime189.jsxs)(
          Stack,
          {
            direction: "row",
            className: "dataviews-view-list__item-wrapper",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime189.jsx)("div", { role: "gridcell", children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                import_components36.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_runtime189.jsxs)(
                Stack,
                {
                  direction: "row",
                  gap: "md",
                  justify: "start",
                  align: hasOnlyMediaAndTitle ? "center" : "flex-start",
                  style: { flex: 1, minWidth: 0 },
                  children: [
                    renderedMediaField,
                    /* @__PURE__ */ (0, import_jsx_runtime189.jsxs)(
                      Stack,
                      {
                        direction: "column",
                        gap: "xs",
                        className: "dataviews-view-list__field-wrapper",
                        children: [
                          /* @__PURE__ */ (0, import_jsx_runtime189.jsxs)(Stack, { direction: "row", align: "center", children: [
                            /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                              "div",
                              {
                                className: "dataviews-title-field dataviews-view-list__title-field",
                                id: labelId,
                                children: renderedTitleField
                              }
                            ),
                            usedActions
                          ] }),
                          renderDescription && /* @__PURE__ */ (0, import_jsx_runtime189.jsx)("div", { className: "dataviews-view-list__field", children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                            descriptionField3.render,
                            {
                              item,
                              field: descriptionField3
                            }
                          ) }),
                          /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                            "div",
                            {
                              className: "dataviews-view-list__fields",
                              id: descriptionId,
                              children: otherFields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime189.jsxs)(
                                "div",
                                {
                                  className: "dataviews-view-list__field",
                                  children: [
                                    /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                                      VisuallyHidden,
                                      {
                                        className: "dataviews-view-list__field-label",
                                        render: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)("span", {}),
                                        children: field.label
                                      }
                                    ),
                                    /* @__PURE__ */ (0, import_jsx_runtime189.jsx)("span", { className: "dataviews-view-list__field-value", children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                                      field.render,
                                      {
                                        item,
                                        field
                                      }
                                    ) })
                                  ]
                                },
                                field.id
                              ))
                            }
                          )
                        ]
                      }
                    )
                  ]
                }
              )
            ]
          }
        )
      }
    );
  }
  function isDefined2(item) {
    return !!item;
  }
  function ViewList(props) {
    const {
      actions: actions2,
      data,
      fields: fields2,
      getItemId: getItemId2,
      isLoading,
      onChangeSelection,
      selection,
      view,
      className,
      empty
    } = props;
    const baseId = (0, import_compose10.useInstanceId)(ViewList, "view-list");
    const isDelayedLoading = useDelayedLoading(!!isLoading);
    const { paginationInfo } = (0, import_element86.useContext)(dataviews_context_default);
    const selectedItem = data?.findLast(
      (item) => selection.includes(getItemId2(item))
    );
    const titleField2 = fields2.find((field) => field.id === view.titleField);
    const mediaField = fields2.find((field) => field.id === view.mediaField);
    const descriptionField3 = fields2.find(
      (field) => field.id === view.descriptionField
    );
    const otherFields = (view?.fields ?? []).map((fieldId) => fields2.find((f3) => fieldId === f3.id)).filter(isDefined2);
    const onSelect = (item) => onChangeSelection([getItemId2(item)]);
    const generateCompositeItemIdPrefix = (0, import_element86.useCallback)(
      (item) => `${baseId}-${getItemId2(item)}`,
      [baseId, getItemId2]
    );
    const isActiveCompositeItem = (0, import_element86.useCallback)(
      (item, idToCheck) => {
        return idToCheck.startsWith(
          generateCompositeItemIdPrefix(item)
        );
      },
      [generateCompositeItemIdPrefix]
    );
    const [activeCompositeId, setActiveCompositeId] = (0, import_element86.useState)(void 0);
    const compositeRef = (0, import_element86.useRef)(null);
    (0, import_element86.useEffect)(() => {
      if (selectedItem) {
        setActiveCompositeId(
          generateItemWrapperCompositeId(
            generateCompositeItemIdPrefix(selectedItem)
          )
        );
      }
    }, [selectedItem, generateCompositeItemIdPrefix]);
    const activeItemIndex = data.findIndex(
      (item) => isActiveCompositeItem(item, activeCompositeId ?? "")
    );
    const previousActiveItemIndex = (0, import_compose10.usePrevious)(activeItemIndex);
    const isActiveIdInList = activeItemIndex !== -1;
    const selectCompositeItem = (0, import_element86.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_element86.useEffect)(() => {
      const wasActiveIdInList = previousActiveItemIndex !== void 0 && previousActiveItemIndex !== -1;
      if (!isActiveIdInList && wasActiveIdInList) {
        selectCompositeItem(
          previousActiveItemIndex,
          generateItemWrapperCompositeId
        );
      }
    }, [isActiveIdInList, selectCompositeItem, previousActiveItemIndex]);
    const onDropdownTriggerKeyDown = (0, import_element86.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_runtime189.jsx)("div", {}),
      activeId: activeCompositeId,
      setActiveId: setActiveCompositeId,
      inert: !isInfiniteScroll && !!isLoading ? "true" : void 0
    };
    if (!hasData) {
      return /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
        "div",
        {
          className: clsx_default("dataviews-no-results", {
            "is-refreshing": isDelayedLoading
          }),
          children: empty
        }
      );
    }
    if (hasData && groupField && dataByGroup) {
      return /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
        import_components36.Composite,
        {
          ...compositeProps,
          className: "dataviews-view-list__group",
          role: "grid",
          children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(Stack, { direction: "column", gap: "lg", className: listClassName, children: Array.from(dataByGroup.entries()).map(
            ([groupName, groupItems]) => /* @__PURE__ */ (0, import_jsx_runtime189.jsxs)(Stack, { direction: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime189.jsx)("h3", { className: "dataviews-view-list__group-header", children: view.groupBy?.showLabel === false ? groupName : (0, import_i18n91.sprintf)(
                // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                (0, import_i18n91.__)("%1$s: %2$s"),
                groupField.label,
                groupName
              ) }),
              groupItems.map((item) => {
                const id = generateCompositeItemIdPrefix(item);
                return /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
                  ListItem,
                  {
                    view,
                    idPrefix: id,
                    actions: actions2,
                    item,
                    isSelected: item === selectedItem,
                    onSelect,
                    mediaField,
                    titleField: titleField2,
                    descriptionField: descriptionField3,
                    otherFields,
                    onDropdownTriggerKeyDown
                  },
                  id
                );
              })
            ] }, groupName)
          ) })
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime189.jsxs)(import_jsx_runtime189.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
        import_components36.Composite,
        {
          ...compositeProps,
          className: listClassName,
          role: view.infiniteScrollEnabled ? "feed" : "grid",
          children: data.map((item, index2) => {
            const id = generateCompositeItemIdPrefix(item);
            return /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(
              ListItem,
              {
                view,
                idPrefix: id,
                actions: actions2,
                item,
                isSelected: item === selectedItem,
                onSelect,
                mediaField,
                titleField: titleField2,
                descriptionField: descriptionField3,
                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_runtime189.jsx)(
        "p",
        {
          className: "dataviews-loading-more",
          "aria-hidden": !isLoading,
          children: /* @__PURE__ */ (0, import_jsx_runtime189.jsx)(import_components36.Spinner, {})
        }
      )
    ] });
  }

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

  // packages/dataviews/build-module/components/dataviews-layouts/activity/activity-group.mjs
  var import_i18n92 = __toESM(require_i18n(), 1);
  var import_element87 = __toESM(require_element(), 1);
  var import_jsx_runtime190 = __toESM(require_jsx_runtime(), 1);
  function ActivityGroup({
    groupName,
    groupData,
    groupField,
    showLabel = true,
    children
  }) {
    const groupHeader = showLabel ? (0, import_element87.createInterpolateElement)(
      // translators: %s: The label of the field e.g. "Status".
      (0, import_i18n92.sprintf)((0, import_i18n92.__)("%s: <groupName />"), groupField.label).trim(),
      {
        groupName: /* @__PURE__ */ (0, import_jsx_runtime190.jsx)(
          groupField.render,
          {
            item: groupData[0],
            field: groupField
          }
        )
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime190.jsx)(groupField.render, { item: groupData[0], field: groupField });
    return /* @__PURE__ */ (0, import_jsx_runtime190.jsxs)(
      Stack,
      {
        direction: "column",
        className: "dataviews-view-activity__group",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime190.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_element88 = __toESM(require_element(), 1);
  var import_data36 = __toESM(require_data(), 1);
  var import_compose11 = __toESM(require_compose(), 1);
  var import_jsx_runtime191 = __toESM(require_jsx_runtime(), 1);
  function ActivityItem(props) {
    const {
      view,
      actions: actions2,
      item,
      titleField: titleField2,
      mediaField,
      descriptionField: descriptionField3,
      otherFields,
      posinset,
      onClickItem,
      renderItemLink,
      isItemClickable: isItemClickable2
    } = props;
    const {
      showTitle = true,
      showMedia = true,
      showDescription = true,
      infiniteScrollEnabled
    } = view;
    const itemRef = (0, import_element88.useRef)(null);
    const registry = (0, import_data36.useRegistry)();
    const { paginationInfo } = (0, import_element88.useContext)(dataviews_context_default);
    const { primaryActions, eligibleActions } = (0, import_element88.useMemo)(() => {
      const _eligibleActions = actions2.filter(
        (action) => !action.isEligible || action.isEligible(item)
      );
      const _primaryActions = _eligibleActions.filter(
        (action) => action.isPrimary
      );
      return {
        primaryActions: _primaryActions,
        eligibleActions: _eligibleActions
      };
    }, [actions2, item]);
    const isMobileViewport = (0, import_compose11.useViewportMatch)("medium", "<");
    const density = view.layout?.density ?? "balanced";
    const mediaContent = showMedia && density !== "compact" && mediaField?.render ? /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
      mediaField.render,
      {
        item,
        field: mediaField,
        config: {
          sizes: density === "comfortable" ? "32px" : "24px"
        }
      }
    ) : null;
    const renderedMediaField = /* @__PURE__ */ (0, import_jsx_runtime191.jsx)("div", { className: "dataviews-view-activity__item-type-icon", children: mediaContent || /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
      "span",
      {
        className: "dataviews-view-activity__item-bullet",
        "aria-hidden": "true"
      }
    ) });
    const renderedTitleField = showTitle && titleField2?.render ? /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(titleField2.render, { item, field: titleField2 }) : null;
    const verticalGap = (0, import_element88.useMemo)(() => {
      switch (density) {
        case "comfortable":
          return "md";
        default:
          return "sm";
      }
    }, [density]);
    return /* @__PURE__ */ (0, import_jsx_runtime191.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_runtime191.jsxs)(Stack, { direction: "row", gap: "lg", justify: "start", align: "flex-start", children: [
          /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
            Stack,
            {
              direction: "column",
              gap: "xs",
              align: "center",
              className: "dataviews-view-activity__item-type",
              children: renderedMediaField
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime191.jsxs)(
            Stack,
            {
              direction: "column",
              gap: verticalGap,
              align: "flex-start",
              className: "dataviews-view-activity__item-content",
              children: [
                renderedTitleField && /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
                  ItemClickWrapper,
                  {
                    item,
                    isItemClickable: isItemClickable2,
                    onClickItem,
                    renderItemLink,
                    className: "dataviews-view-activity__item-title",
                    children: renderedTitleField
                  }
                ),
                showDescription && descriptionField3 && /* @__PURE__ */ (0, import_jsx_runtime191.jsx)("div", { className: "dataviews-view-activity__item-description", children: /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
                  descriptionField3.render,
                  {
                    item,
                    field: descriptionField3
                  }
                ) }),
                /* @__PURE__ */ (0, import_jsx_runtime191.jsx)("div", { className: "dataviews-view-activity__item-fields", children: otherFields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime191.jsxs)(
                  "div",
                  {
                    className: "dataviews-view-activity__item-field",
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
                        VisuallyHidden,
                        {
                          className: "dataviews-view-activity__item-field-label",
                          render: /* @__PURE__ */ (0, import_jsx_runtime191.jsx)("span", {}),
                          children: field.label
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime191.jsx)("span", { className: "dataviews-view-activity__item-field-value", children: /* @__PURE__ */ (0, import_jsx_runtime191.jsx)(
                        field.render,
                        {
                          item,
                          field
                        }
                      ) })
                    ]
                  },
                  field.id
                )) }),
                !!primaryActions?.length && /* @__PURE__ */ (0, import_jsx_runtime191.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_runtime191.jsx)("div", { className: "dataviews-view-activity__item-actions", children: /* @__PURE__ */ (0, import_jsx_runtime191.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_react16 = __toESM(require_react(), 1);
  function isDefined3(item) {
    return !!item;
  }
  function ActivityItems(props) {
    const { data, fields: fields2, getItemId: getItemId2, view } = props;
    const titleField2 = fields2.find((field) => field.id === view.titleField);
    const mediaField = fields2.find((field) => field.id === view.mediaField);
    const descriptionField3 = fields2.find(
      (field) => field.id === view.descriptionField
    );
    const otherFields = (view?.fields ?? []).map((fieldId) => fields2.find((f3) => fieldId === f3.id)).filter(isDefined3);
    return data.map((item, index2) => {
      return /* @__PURE__ */ (0, import_react16.createElement)(
        activity_item_default,
        {
          ...props,
          key: getItemId2(item),
          item,
          mediaField,
          titleField: titleField2,
          descriptionField: descriptionField3,
          otherFields,
          posinset: view.infiniteScrollEnabled ? index2 + 1 : void 0
        }
      );
    });
  }

  // packages/dataviews/build-module/components/dataviews-layouts/activity/index.mjs
  var import_jsx_runtime192 = __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_runtime192.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_runtime192.jsx)(
        Stack,
        {
          direction: "column",
          gap: "sm",
          className: wrapperClassName,
          inert: isInert ? "true" : void 0,
          children: groupedEntries.map(
            ([groupName, groupData]) => /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
              ActivityGroup,
              {
                groupName,
                groupData,
                groupField,
                showLabel: view.groupBy?.showLabel !== false,
                children: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
                  ActivityItems,
                  {
                    ...props,
                    data: groupData
                  }
                )
              },
              groupName
            )
          )
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime192.jsxs)(import_jsx_runtime192.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(
        "div",
        {
          className: wrapperClassName,
          role: view.infiniteScrollEnabled ? "feed" : void 0,
          inert: isInert ? "true" : void 0,
          children: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(ActivityItems, { ...props })
        }
      ),
      isInfiniteScroll && isLoading && /* @__PURE__ */ (0, import_jsx_runtime192.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime192.jsx)(import_components37.Spinner, {}) })
    ] });
  }

  // packages/dataviews/build-module/components/dataviews-layouts/picker-grid/index.mjs
  var import_components40 = __toESM(require_components(), 1);
  var import_i18n95 = __toESM(require_i18n(), 1);
  var import_compose12 = __toESM(require_compose(), 1);
  var import_element91 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataviews-picker-footer/index.mjs
  var import_components39 = __toESM(require_components(), 1);
  var import_data37 = __toESM(require_data(), 1);
  var import_element90 = __toESM(require_element(), 1);
  var import_i18n94 = __toESM(require_i18n(), 1);

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

  // packages/dataviews/build-module/components/dataviews-picker-footer/index.mjs
  var import_jsx_runtime194 = __toESM(require_jsx_runtime(), 1);
  var EMPTY_ARRAY6 = [];
  function useIsMultiselectPicker(actions2) {
    return (0, import_element90.useMemo)(() => {
      return !!actions2?.length && actions2?.every((action) => action.supportsBulk);
    }, [actions2]);
  }
  function BulkSelectionCheckbox2({
    selection,
    selectedItems,
    onChangeSelection,
    data,
    getItemId: getItemId2,
    disableSelectAll = false
  }) {
    const hasSelection = selection.length > 0;
    const areAllSelected = selectedItems.length === data.length;
    if (disableSelectAll) {
      return /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
        import_components39.CheckboxControl,
        {
          className: "dataviews-view-table-selection-checkbox",
          checked: hasSelection,
          disabled: !hasSelection,
          onChange: () => {
            onChangeSelection([]);
          },
          "aria-label": (0, import_i18n94.__)("Deselect all")
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
      import_components39.CheckboxControl,
      {
        className: "dataviews-view-table-selection-checkbox",
        checked: areAllSelected,
        indeterminate: !areAllSelected && !!selectedItems.length,
        onChange: () => {
          if (areAllSelected) {
            onChangeSelection(
              selection.filter(
                (id) => !data.some(
                  (item) => id === getItemId2(item)
                )
              )
            );
          } else {
            const selectionSet = /* @__PURE__ */ new Set([
              ...selection,
              ...data.map((item) => getItemId2(item))
            ]);
            onChangeSelection(Array.from(selectionSet));
          }
        },
        "aria-label": areAllSelected ? (0, import_i18n94.__)("Deselect all") : (0, import_i18n94.__)("Select all")
      }
    );
  }
  function ActionButtons({
    actions: actions2,
    items,
    selection
  }) {
    const registry = (0, import_data37.useRegistry)();
    const [actionInProgress, setActionInProgress] = (0, import_element90.useState)(
      null
    );
    return /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(Stack, { direction: "row", gap: "xs", children: actions2.map((action) => {
      if (!("callback" in action)) {
        return null;
      }
      const { id, label, icon, isPrimary, callback } = action;
      const _label = typeof label === "string" ? label : label(items);
      const variant = isPrimary ? "primary" : "tertiary";
      const isInProgress = id === actionInProgress;
      return /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
        import_components39.Button,
        {
          accessibleWhenDisabled: true,
          icon,
          disabled: isInProgress || !selection?.length,
          isBusy: isInProgress,
          onClick: async () => {
            setActionInProgress(id);
            await callback(items, {
              registry
            });
            setActionInProgress(null);
          },
          size: "compact",
          variant,
          children: _label
        },
        id
      );
    }) });
  }
  function PickerBulkSelectionInfo() {
    const {
      data,
      selection,
      onChangeSelection,
      getItemId: getItemId2,
      actions: actions2 = EMPTY_ARRAY6,
      paginationInfo,
      view
    } = (0, import_element90.useContext)(dataviews_context_default);
    const isMultiselect = useIsMultiselectPicker(actions2);
    const selectedItems = (0, import_element90.useMemo)(
      () => data.filter((item) => selection.includes(getItemId2(item))),
      [selection, getItemId2, data]
    );
    if (!actions2.length) {
      return null;
    }
    const message2 = getFooterMessage(
      selection.length,
      data.length,
      paginationInfo.totalItems,
      !!view.infiniteScrollEnabled
    );
    return /* @__PURE__ */ (0, import_jsx_runtime194.jsxs)(
      Stack,
      {
        direction: "row",
        className: "dataviews-picker-footer__bulk-selection",
        gap: "md",
        align: "center",
        children: [
          isMultiselect && /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
            BulkSelectionCheckbox2,
            {
              selection,
              selectedItems,
              onChangeSelection,
              data,
              getItemId: getItemId2,
              disableSelectAll: !!view.infiniteScrollEnabled
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime194.jsx)("span", { className: "dataviews-bulk-actions-footer__item-count", children: message2 })
        ]
      }
    );
  }
  function PickerActions() {
    const {
      data,
      selection,
      getItemId: getItemId2,
      actions: actions2 = EMPTY_ARRAY6
    } = (0, import_element90.useContext)(dataviews_context_default);
    const selectedItems = (0, import_element90.useMemo)(
      () => data.filter((item) => selection.includes(getItemId2(item))),
      [selection, getItemId2, data]
    );
    if (!actions2.length) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime194.jsx)("div", { className: "dataviews-picker-footer__actions", children: /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(
      ActionButtons,
      {
        actions: actions2,
        items: selectedItems,
        selection
      }
    ) });
  }
  function DataViewsPickerBulkActionToolbar() {
    return /* @__PURE__ */ (0, import_jsx_runtime194.jsxs)(Stack, { direction: "row", gap: "md", align: "center", children: [
      /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(PickerBulkSelectionInfo, {}),
      /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(PickerActions, {})
    ] });
  }
  function DataViewsPickerFooter() {
    const {
      actions: actions2 = EMPTY_ARRAY6,
      paginationInfo,
      view
    } = (0, import_element90.useContext)(dataviews_context_default);
    const hasPagination = !view.infiniteScrollEnabled && !!paginationInfo.totalItems && paginationInfo.totalPages > 1;
    if (!actions2.length && !hasPagination) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime194.jsxs)(
      Stack,
      {
        direction: "row",
        justify: "space-between",
        align: "center",
        className: "dataviews-footer",
        gap: "sm",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(PickerBulkSelectionInfo, {}),
          /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(dataviews_pagination_default, {}),
          /* @__PURE__ */ (0, import_jsx_runtime194.jsx)(PickerActions, {})
        ]
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-layouts/picker-grid/index.mjs
  var import_jsx_runtime195 = __toESM(require_jsx_runtime(), 1);
  var { Badge: WCBadge3 } = unlock5(import_components40.privateApis);
  function GridItem3({
    view,
    multiselect,
    selection,
    onChangeSelection,
    getItemId: getItemId2,
    item,
    mediaField,
    titleField: titleField2,
    descriptionField: descriptionField3,
    regularFields,
    badgeFields,
    config: config2,
    posinset,
    setsize
  }) {
    const { showTitle = true, showMedia = true, showDescription = true } = view;
    const id = getItemId2(item);
    const elementRef = (0, import_element91.useRef)(null);
    const isSelected2 = selection.includes(id);
    useIntersectionObserver(elementRef, posinset);
    const renderedMediaField = mediaField?.render ? /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
      mediaField.render,
      {
        item,
        field: mediaField,
        config: config2
      }
    ) : null;
    const renderedTitleField = showTitle && titleField2?.render ? /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(titleField2.render, { item, field: titleField2 }) : null;
    return /* @__PURE__ */ (0, import_jsx_runtime195.jsxs)(
      import_components40.Composite.Item,
      {
        ref: elementRef,
        "aria-label": titleField2 ? titleField2.getValue({ item }) || (0, import_i18n95.__)("(no title)") : void 0,
        render: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime195.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_runtime195.jsx)("div", { className: "dataviews-view-picker-grid__media", children: renderedMediaField }),
          showMedia && renderedMediaField && /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
            DataViewsSelectionCheckbox,
            {
              item,
              selection,
              onChangeSelection,
              getItemId: getItemId2,
              titleField: titleField2,
              disabled: false,
              "aria-hidden": true,
              tabIndex: -1
            }
          ),
          showTitle && /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
            Stack,
            {
              direction: "row",
              justify: "space-between",
              className: "dataviews-view-picker-grid__title-actions",
              children: /* @__PURE__ */ (0, import_jsx_runtime195.jsx)("div", { className: "dataviews-view-picker-grid__title-field dataviews-title-field", children: renderedTitleField })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime195.jsxs)(Stack, { direction: "column", gap: "xs", children: [
            showDescription && descriptionField3?.render && /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
              descriptionField3.render,
              {
                item,
                field: descriptionField3
              }
            ),
            !!badgeFields?.length && /* @__PURE__ */ (0, import_jsx_runtime195.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_runtime195.jsx)(
                    WCBadge3,
                    {
                      className: "dataviews-view-picker-grid__field-value",
                      children: /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
                        field.render,
                        {
                          item,
                          field
                        }
                      )
                    },
                    field.id
                  );
                })
              }
            ),
            !!regularFields?.length && /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
              Stack,
              {
                direction: "column",
                className: "dataviews-view-picker-grid__fields",
                gap: "xs",
                children: regularFields.map((field) => {
                  return /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
                    import_components40.Flex,
                    {
                      className: "dataviews-view-picker-grid__field",
                      gap: 1,
                      justify: "flex-start",
                      expanded: true,
                      style: { height: "auto" },
                      direction: "row",
                      children: /* @__PURE__ */ (0, import_jsx_runtime195.jsxs)(import_jsx_runtime195.Fragment, { children: [
                        /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(import_components40.FlexItem, { className: "dataviews-view-picker-grid__field-name", children: field.header }),
                        /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
                          import_components40.FlexItem,
                          {
                            className: "dataviews-view-picker-grid__field-value",
                            style: { maxHeight: "none" },
                            children: /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
                              field.render,
                              {
                                item,
                                field
                              }
                            )
                          }
                        )
                      ] })
                    },
                    field.id
                  );
                })
              }
            )
          ] })
        ]
      },
      id
    );
  }
  function GridGroup({
    groupName,
    groupField,
    showLabel = true,
    children
  }) {
    const headerId = (0, import_compose12.useInstanceId)(
      GridGroup,
      "dataviews-view-picker-grid-group__header"
    );
    return /* @__PURE__ */ (0, import_jsx_runtime195.jsxs)(
      Stack,
      {
        direction: "column",
        gap: "sm",
        role: "group",
        "aria-labelledby": headerId,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
            "h3",
            {
              className: "dataviews-view-picker-grid-group__header",
              id: headerId,
              children: showLabel ? (0, import_i18n95.sprintf)(
                // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                (0, import_i18n95.__)("%1$s: %2$s"),
                groupField.label,
                groupName
              ) : groupName
            }
          ),
          children
        ]
      },
      groupName
    );
  }
  function ViewPickerGrid({
    actions: actions2,
    data,
    fields: fields2,
    getItemId: getItemId2,
    isLoading,
    onChangeSelection,
    selection,
    view,
    className,
    empty
  }) {
    const { resizeObserverRef, paginationInfo, itemListLabel } = (0, import_element91.useContext)(dataviews_context_default);
    const titleField2 = fields2.find(
      (field) => field.id === view?.titleField
    );
    const mediaField = fields2.find(
      (field) => field.id === view?.mediaField
    );
    const descriptionField3 = fields2.find(
      (field) => field.id === view?.descriptionField
    );
    const otherFields = view.fields ?? [];
    const { regularFields, badgeFields } = otherFields.reduce(
      (accumulator, fieldId) => {
        const field = fields2.find((f3) => f3.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(actions2);
    const size4 = "900px";
    const groupField = view.groupBy?.field ? fields2.find((f3) => f3.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_runtime195.jsxs)(import_jsx_runtime195.Fragment, {
      // Render multiple groups.
      children: [
        hasData && groupField && dataByGroup && /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
          import_components40.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_runtime195.jsx)(
              Stack,
              {
                direction: "column",
                gap: "lg",
                children,
                ...props
              }
            ),
            children: Array.from(dataByGroup.entries()).map(
              ([groupName, groupItems]) => /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
                GridGroup,
                {
                  groupName,
                  groupField,
                  showLabel: view.groupBy?.showLabel !== false,
                  children: /* @__PURE__ */ (0, import_jsx_runtime195.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_runtime195.jsx)(
                          GridItem3,
                          {
                            view,
                            multiselect: isMultiselect,
                            selection,
                            onChangeSelection,
                            getItemId: getItemId2,
                            item,
                            mediaField,
                            titleField: titleField2,
                            descriptionField: descriptionField3,
                            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_runtime195.jsxs)(
          import_components40.Composite,
          {
            render: /* @__PURE__ */ (0, import_jsx_runtime195.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_runtime195.jsx)(
                  import_components40.Composite.Item,
                  {
                    render: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime195.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_runtime195.jsx)(
                  GridItem3,
                  {
                    view,
                    multiselect: isMultiselect,
                    selection,
                    onChangeSelection,
                    getItemId: getItemId2,
                    item,
                    mediaField,
                    titleField: titleField2,
                    descriptionField: descriptionField3,
                    regularFields,
                    badgeFields,
                    config: {
                      sizes: size4
                    },
                    posinset,
                    setsize: setSize
                  },
                  getItemId2(item)
                );
              })
            ]
          }
        ),
        // Render empty state.
        !hasData && /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(
          "div",
          {
            className: clsx_default({
              "dataviews-loading": isLoading,
              "dataviews-no-results": !isLoading
            }),
            children: isLoading ? /* @__PURE__ */ (0, import_jsx_runtime195.jsx)("p", { children: /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(import_components40.Spinner, {}) }) : empty
          }
        ),
        hasData && isLoading && /* @__PURE__ */ (0, import_jsx_runtime195.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime195.jsx)(import_components40.Spinner, {}) })
      ]
    });
  }
  var picker_grid_default = ViewPickerGrid;

  // packages/dataviews/build-module/components/dataviews-layouts/picker-table/index.mjs
  var import_i18n96 = __toESM(require_i18n(), 1);
  var import_components41 = __toESM(require_components(), 1);
  var import_element92 = __toESM(require_element(), 1);
  var import_jsx_runtime196 = __toESM(require_jsx_runtime(), 1);
  function TableColumnField2({
    item,
    fields: fields2,
    column,
    align
  }) {
    const field = fields2.find((f3) => f3.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_runtime196.jsx)("div", { className, children: /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(field.render, { item, field }) });
  }
  function TableRow2({
    item,
    fields: fields2,
    id,
    view,
    titleField: titleField2,
    mediaField,
    descriptionField: descriptionField3,
    selection,
    getItemId: getItemId2,
    onChangeSelection,
    multiselect,
    posinset
  }) {
    const { paginationInfo } = (0, import_element92.useContext)(dataviews_context_default);
    const isSelected2 = selection.includes(id);
    const [isHovered, setIsHovered] = (0, import_element92.useState)(false);
    const elementRef = (0, import_element92.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 = titleField2 && showTitle || mediaField && showMedia || descriptionField3 && showDescription;
    return /* @__PURE__ */ (0, import_jsx_runtime196.jsxs)(
      import_components41.Composite.Item,
      {
        ref: elementRef,
        render: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime196.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_runtime196.jsx)(
            "td",
            {
              className: "dataviews-view-table__checkbox-column",
              role: "presentation",
              children: /* @__PURE__ */ (0, import_jsx_runtime196.jsx)("div", { className: "dataviews-view-table__cell-content-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
                DataViewsSelectionCheckbox,
                {
                  item,
                  selection,
                  onChangeSelection,
                  getItemId: getItemId2,
                  titleField: titleField2,
                  disabled: false,
                  "aria-hidden": true,
                  tabIndex: -1
                }
              ) })
            }
          ),
          hasPrimaryColumn && /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
            "td",
            {
              role: "presentation",
              children: /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
                column_primary_default,
                {
                  item,
                  titleField: showTitle ? titleField2 : void 0,
                  mediaField: showMedia ? mediaField : void 0,
                  descriptionField: showDescription ? descriptionField3 : void 0,
                  isItemClickable: () => false
                }
              )
            }
          ),
          columns.map((column) => {
            const { width, maxWidth, minWidth, align } = view.layout?.styles?.[column] ?? {};
            return /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
              "td",
              {
                style: {
                  width,
                  maxWidth,
                  minWidth
                },
                role: "presentation",
                children: /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
                  TableColumnField2,
                  {
                    fields: fields2,
                    item,
                    column,
                    align
                  }
                )
              },
              column
            );
          })
        ]
      },
      id
    );
  }
  function ViewPickerTable({
    actions: actions2,
    data,
    fields: fields2,
    getItemId: getItemId2,
    isLoading = false,
    onChangeView,
    onChangeSelection,
    selection,
    setOpenedFilter,
    view,
    className,
    empty
  }) {
    const headerMenuRefs = (0, import_element92.useRef)(/* @__PURE__ */ new Map());
    const headerMenuToFocusRef = (0, import_element92.useRef)(void 0);
    const [nextHeaderMenuToFocus, setNextHeaderMenuToFocus] = (0, import_element92.useState)();
    const isMultiselect = useIsMultiselectPicker(actions2) ?? false;
    (0, import_element92.useEffect)(() => {
      if (headerMenuToFocusRef.current) {
        headerMenuToFocusRef.current.focus();
        headerMenuToFocusRef.current = void 0;
      }
    });
    const groupField = view.groupBy?.field ? fields2.find((f3) => f3.id === view.groupBy?.field) : null;
    const dataByGroup = groupField ? getDataByGroup(data, groupField) : null;
    const isInfiniteScroll = view.infiniteScrollEnabled && !dataByGroup;
    const tableNoticeId = (0, import_element92.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 titleField2 = fields2.find((field) => field.id === view.titleField);
    const mediaField = fields2.find((field) => field.id === view.mediaField);
    const descriptionField3 = fields2.find(
      (field) => field.id === view.descriptionField
    );
    const { showTitle = true, showMedia = true, showDescription = true } = view;
    const hasPrimaryColumn = titleField2 && showTitle || mediaField && showMedia || descriptionField3 && 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_runtime196.jsxs)(import_jsx_runtime196.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime196.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_runtime196.jsx)("thead", { role: "presentation", children: /* @__PURE__ */ (0, import_jsx_runtime196.jsxs)(
              "tr",
              {
                className: "dataviews-view-table__row",
                role: "presentation",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime196.jsx)("th", { className: "dataviews-view-table__checkbox-column", children: isMultiselect && /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
                    BulkSelectionCheckbox,
                    {
                      selection,
                      onChangeSelection,
                      data,
                      actions: actions2,
                      getItemId: getItemId2,
                      disableSelectAll: isInfiniteScroll
                    }
                  ) }),
                  hasPrimaryColumn && /* @__PURE__ */ (0, import_jsx_runtime196.jsx)("th", { children: titleField2 && /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
                    column_header_menu_default,
                    {
                      ref: headerMenuRef(
                        titleField2.id,
                        0
                      ),
                      fieldId: titleField2.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_runtime196.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_runtime196.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_runtime196.jsxs)(
                import_components41.Composite,
                {
                  virtualFocus: true,
                  orientation: "vertical",
                  render: /* @__PURE__ */ (0, import_jsx_runtime196.jsx)("tbody", { role: "group" }),
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
                      "tr",
                      {
                        className: "dataviews-view-table__group-header-row",
                        role: "presentation",
                        children: /* @__PURE__ */ (0, import_jsx_runtime196.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_i18n96.sprintf)(
                              // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                              (0, import_i18n96.__)("%1$s: %2$s"),
                              groupField.label,
                              groupName
                            )
                          }
                        )
                      }
                    ),
                    groupItems.map((item, index2) => /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
                      TableRow2,
                      {
                        item,
                        fields: fields2,
                        id: getItemId2(item) || index2.toString(),
                        view,
                        titleField: titleField2,
                        mediaField,
                        descriptionField: descriptionField3,
                        selection,
                        getItemId: getItemId2,
                        onChangeSelection,
                        multiselect: isMultiselect
                      },
                      getItemId2(item)
                    ))
                  ]
                },
                `group-${groupName}`
              )
            ) : /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(
              import_components41.Composite,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime196.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_runtime196.jsx)(
                    TableRow2,
                    {
                      item,
                      fields: fields2,
                      id: itemId || index2.toString(),
                      view,
                      titleField: titleField2,
                      mediaField,
                      descriptionField: descriptionField3,
                      selection,
                      getItemId: getItemId2,
                      onChangeSelection,
                      multiselect: isMultiselect,
                      posinset
                    },
                    itemId
                  );
                })
              }
            )
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime196.jsxs)(
        "div",
        {
          className: clsx_default({
            "dataviews-loading": isLoading,
            "dataviews-no-results": !hasData && !isLoading
          }),
          id: tableNoticeId,
          children: [
            !hasData && (isLoading ? /* @__PURE__ */ (0, import_jsx_runtime196.jsx)("p", { children: /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(import_components41.Spinner, {}) }) : empty),
            hasData && isLoading && /* @__PURE__ */ (0, import_jsx_runtime196.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime196.jsx)(import_components41.Spinner, {}) })
          ]
        }
      )
    ] });
  }
  var picker_table_default = ViewPickerTable;

  // packages/dataviews/build-module/components/dataviews-layouts/picker-activity/index.mjs
  var import_components42 = __toESM(require_components(), 1);
  var import_element93 = __toESM(require_element(), 1);
  var import_compose13 = __toESM(require_compose(), 1);
  var import_i18n97 = __toESM(require_i18n(), 1);
  var import_jsx_runtime197 = __toESM(require_jsx_runtime(), 1);
  function isDefined4(item) {
    return !!item;
  }
  function PickerActivityItem({
    view,
    multiselect,
    selection,
    onChangeSelection,
    getItemId: getItemId2,
    item,
    titleField: titleField2,
    mediaField,
    descriptionField: descriptionField3,
    otherFields,
    posinset,
    setsize
  }) {
    const elementRef = (0, import_element93.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_runtime197.jsx)(
      mediaField.render,
      {
        item,
        field: mediaField,
        config: {
          sizes: density === "comfortable" ? "32px" : "24px"
        }
      }
    ) : null;
    const renderedMediaField = /* @__PURE__ */ (0, import_jsx_runtime197.jsx)("div", { className: "dataviews-view-picker-activity__item-type-icon", children: mediaContent || /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
      "span",
      {
        className: "dataviews-view-picker-activity__item-bullet",
        "aria-hidden": "true"
      }
    ) });
    const renderedTitleField = showTitle && titleField2?.render ? /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(titleField2.render, { item, field: titleField2 }) : null;
    const renderedDescriptionField = showDescription && descriptionField3?.render ? /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(descriptionField3.render, { item, field: descriptionField3 }) : null;
    const verticalGap = (0, import_element93.useMemo)(() => {
      switch (density) {
        case "comfortable":
          return "md";
        default:
          return "sm";
      }
    }, [density]);
    return /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
      import_components42.Composite.Item,
      {
        ref: elementRef,
        role: "option",
        "aria-label": titleField2 ? titleField2.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_runtime197.jsx)("div", {}),
        children: /* @__PURE__ */ (0, import_jsx_runtime197.jsxs)(Stack, { direction: "row", gap: "lg", justify: "start", align: "flex-start", children: [
          /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
            Stack,
            {
              direction: "column",
              gap: "xs",
              align: "center",
              className: "dataviews-view-picker-activity__item-type",
              children: renderedMediaField
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime197.jsxs)(
            Stack,
            {
              direction: "column",
              gap: verticalGap,
              align: "flex-start",
              className: "dataviews-view-picker-activity__item-content",
              children: [
                renderedTitleField && /* @__PURE__ */ (0, import_jsx_runtime197.jsx)("div", { className: "dataviews-view-picker-activity__item-title", children: renderedTitleField }),
                renderedDescriptionField && /* @__PURE__ */ (0, import_jsx_runtime197.jsx)("div", { className: "dataviews-view-picker-activity__item-description", children: renderedDescriptionField }),
                /* @__PURE__ */ (0, import_jsx_runtime197.jsx)("div", { className: "dataviews-view-picker-activity__item-fields", children: otherFields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime197.jsxs)(
                  "div",
                  {
                    className: "dataviews-view-picker-activity__item-field",
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
                        VisuallyHidden,
                        {
                          render: /* @__PURE__ */ (0, import_jsx_runtime197.jsx)("span", {}),
                          className: "dataviews-view-picker-activity__item-field-label",
                          children: field.label
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime197.jsx)("span", { className: "dataviews-view-picker-activity__item-field-value", children: /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
                        field.render,
                        {
                          item,
                          field
                        }
                      ) })
                    ]
                  },
                  field.id
                )) })
              ]
            }
          )
        ] })
      }
    );
  }
  function PickerActivityGroup({
    groupName,
    groupField,
    showLabel = true,
    children
  }) {
    const headerId = (0, import_compose13.useInstanceId)(
      PickerActivityGroup,
      "dataviews-view-picker-activity-group__header"
    );
    return /* @__PURE__ */ (0, import_jsx_runtime197.jsxs)(
      Stack,
      {
        direction: "column",
        role: "group",
        "aria-labelledby": headerId,
        className: "dataviews-view-picker-activity-group",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
            "h3",
            {
              className: "dataviews-view-picker-activity-group__header",
              id: headerId,
              children: showLabel ? (0, import_i18n97.sprintf)(
                // translators: 1: The label of the field e.g. "Date". 2: The value of the field, e.g.: "May 2022".
                (0, import_i18n97.__)("%1$s: %2$s"),
                groupField.label,
                groupName
              ) : groupName
            }
          ),
          children
        ]
      }
    );
  }
  function ViewPickerActivity({
    data,
    fields: fields2,
    getItemId: getItemId2,
    isLoading,
    onChangeSelection,
    selection,
    view,
    actions: actions2,
    className,
    empty
  }) {
    const { itemListLabel, paginationInfo } = (0, import_element93.useContext)(dataviews_context_default);
    const isMultiselect = useIsMultiselectPicker(actions2);
    const titleField2 = fields2.find(
      (field) => field.id === view?.titleField
    );
    const mediaField = fields2.find(
      (field) => field.id === view?.mediaField
    );
    const descriptionField3 = fields2.find(
      (field) => field.id === view?.descriptionField
    );
    const otherFields = (view?.fields ?? []).map((fieldId) => fields2.find((f3) => fieldId === f3.id)).filter(isDefined4);
    const groupField = view.groupBy?.field ? fields2.find((f3) => f3.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_runtime197.jsx)(
      PickerActivityItem,
      {
        view,
        multiselect: isMultiselect,
        selection,
        onChangeSelection,
        getItemId: getItemId2,
        item,
        titleField: titleField2,
        mediaField,
        descriptionField: descriptionField3,
        otherFields,
        posinset: item.position,
        setsize
      },
      getItemId2(item)
    );
    if (!hasData) {
      return /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
        "div",
        {
          className: clsx_default({
            "dataviews-loading": isLoading,
            "dataviews-no-results": !isLoading
          }),
          children: isLoading ? /* @__PURE__ */ (0, import_jsx_runtime197.jsx)("p", { children: /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(import_components42.Spinner, {}) }) : empty
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime197.jsxs)(import_jsx_runtime197.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(
        import_components42.Composite,
        {
          virtualFocus: true,
          orientation: "vertical",
          role: "listbox",
          "aria-multiselectable": isMultiselect,
          "aria-label": itemListLabel,
          "aria-busy": isLoading,
          render: isGrouped ? /* @__PURE__ */ (0, import_jsx_runtime197.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_runtime197.jsx)(
              PickerActivityGroup,
              {
                groupName,
                groupField,
                showLabel: view.groupBy?.showLabel !== false,
                children: groupItems.map(renderItem)
              },
              groupName
            )
          ) : data.map(renderItem)
        }
      ),
      isLoading && /* @__PURE__ */ (0, import_jsx_runtime197.jsx)("p", { className: "dataviews-loading-more", children: /* @__PURE__ */ (0, import_jsx_runtime197.jsx)(import_components42.Spinner, {}) })
    ] });
  }

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

  // packages/dataviews/build-module/components/dataviews-layouts/utils/preview-size-picker.mjs
  var import_components44 = __toESM(require_components(), 1);
  var import_i18n99 = __toESM(require_i18n(), 1);
  var import_element95 = __toESM(require_element(), 1);
  var import_jsx_runtime199 = __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_element95.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((a3, b3) => b3.value - a3.value)[0]?.index ?? 0;
    const marks = breakValues.map((size4, index2) => {
      return {
        value: index2
      };
    });
    return /* @__PURE__ */ (0, import_jsx_runtime199.jsx)(
      import_components44.RangeControl,
      {
        showTooltip: false,
        label: (0, import_i18n99.__)("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_runtime200 = __toESM(require_jsx_runtime(), 1);
  function GridConfigOptions() {
    return /* @__PURE__ */ (0, import_jsx_runtime200.jsxs)(import_jsx_runtime200.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime200.jsx)(DensityPicker, {}),
      /* @__PURE__ */ (0, import_jsx_runtime200.jsx)(PreviewSizePicker, {})
    ] });
  }

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

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

  // packages/dataviews/build-module/components/dataviews-filters/filter.mjs
  var import_components47 = __toESM(require_components(), 1);
  var import_i18n103 = __toESM(require_i18n(), 1);
  var import_element100 = __toESM(require_element(), 1);

  // node_modules/@ariakit/react-components/dist/focusable/focusable-context.js
  var import_react17 = __toESM(require_react(), 1);
  var FocusableContext = (0, import_react17.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 noop6(..._) {
  }
  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(str3) {
    return str3.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 = noop6) {
    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, a3], [indexB, b3]) => {
      const elementA = getElement(a3);
      const elementB = getElement(b3);
      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(a3, b3) {
    return Boolean(b3.compareDocumentPosition(a3) & 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 redo2 = await callback?.();
      return createUndoCallback(async () => {
        await redo2?.();
        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 undo2 = async () => {
      if (!canUndo()) return;
      currentGroup = null;
      redoStack.push(await undoStack.pop()?.());
    };
    const redo2 = 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: undo2,
      redo: redo2,
      execute
    };
  }

  // node_modules/@ariakit/react-utils/dist/index.js
  var React75 = __toESM(require_react(), 1);
  var import_react18 = __toESM(require_react(), 1);
  var import_jsx_runtime201 = __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_react18.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 = { ...React75 };
  var useReactId = _React.useId;
  var useReactDeferredValue = _React.useDeferredValue;
  var useReactInsertionEffect = _React.useInsertionEffect;
  var useSafeLayoutEffect = canUseDOM ? import_react18.useLayoutEffect : import_react18.useEffect;
  function useInitialValue(value) {
    const [initialValue] = (0, import_react18.useState)(value);
    return initialValue;
  }
  function useLiveRef(value) {
    const ref = (0, import_react18.useRef)(value);
    useSafeLayoutEffect(() => {
      ref.current = value;
    });
    return ref;
  }
  function useEvent2(callback) {
    const ref = (0, import_react18.useRef)(() => {
      throw new Error("Cannot call an event handler while rendering.");
    });
    if (useReactInsertionEffect) useReactInsertionEffect(() => {
      ref.current = callback;
    });
    else ref.current = callback;
    return (0, import_react18.useCallback)((...args) => ref.current?.(...args), []);
  }
  function useTransactionState(callback) {
    const [state2, setState] = (0, import_react18.useState)(null);
    useSafeLayoutEffect(() => {
      if (state2 == null) return;
      if (!callback) return;
      let prevState = null;
      callback((prev) => {
        prevState = prev;
        return state2;
      });
      return () => {
        callback(prevState);
      };
    }, [state2, callback]);
    return [state2, setState];
  }
  function useMergeRefs2(...refs) {
    return (0, import_react18.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_react18.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_react18.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_react18.useState)(initialValue);
    (0, import_react18.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_react18.useRef)(false);
    (0, import_react18.useEffect)(() => {
      if (mounted.current) return effect();
      mounted.current = true;
    }, deps);
    (0, import_react18.useEffect)(() => () => {
      mounted.current = false;
    }, []);
  }
  function useUpdateLayoutEffect(effect, deps) {
    const mounted = (0, import_react18.useRef)(false);
    useSafeLayoutEffect(() => {
      if (mounted.current) return effect();
      mounted.current = true;
    }, deps);
    useSafeLayoutEffect(() => () => {
      mounted.current = false;
    }, []);
  }
  function useForceUpdate2() {
    return (0, import_react18.useReducer)(() => [], []);
  }
  function useBooleanEvent(booleanOrCallback) {
    return useEvent2(typeof booleanOrCallback === "function" ? booleanOrCallback : () => booleanOrCallback);
  }
  function useWrapElement(props, callback, deps = []) {
    const wrapElement = (0, import_react18.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_react18.useMemo)(() => {
      return Object.assign(() => {
      }, parent, ...value !== void 0 ? [{ [key]: value }] : []);
    }, [
      parent,
      key,
      value
    ]);
    return [parent?.[key], { onLoadedMetadataCapture }];
  }
  var hasInstalledGlobalEventListeners = false;
  function useIsMouseMoving() {
    (0, import_react18.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 useEvent2(() => 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 forwardRef54(render5) {
    const Role = React75.forwardRef((props, ref) => render5({
      ...props,
      ref
    }));
    Role.displayName = render5.displayName || render5.name;
    return Role;
  }
  function memo4(Component3, propsAreEqual) {
    return React75.memo(Component3, propsAreEqual);
  }
  function createElement5(Type, props) {
    const { wrapElement, render: render5, ...rest } = props;
    const mergedRef = useMergeRefs2(props.ref, getRefProperty(render5));
    let element;
    if (React75.isValidElement(render5)) {
      const renderProps = {
        ...render5.props,
        ref: mergedRef
      };
      element = React75.cloneElement(render5, mergeProps2(rest, renderProps));
    } else if (render5) element = render5(rest);
    else element = /* @__PURE__ */ (0, import_jsx_runtime201.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 = React75.createContext(void 0);
    const scopedContext = React75.createContext(void 0);
    const useContext72 = () => React75.useContext(context);
    const useScopedContext = (onlyScoped = false) => {
      const scoped = React75.useContext(scopedContext);
      const store4 = useContext72();
      if (onlyScoped) return scoped;
      return scoped || store4;
    };
    const useProviderContext = () => {
      const scoped = React75.useContext(scopedContext);
      const store4 = useContext72();
      if (scoped && scoped === store4) return;
      return store4;
    };
    const ContextProvider = (props) => {
      return providers.reduceRight((children, Provider2) => /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(Provider2, {
        ...props,
        children
      }), /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(context.Provider, { ...props }));
    };
    const ScopedContextProvider = (props) => {
      return /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(ContextProvider, {
        ...props,
        children: scopedProviders.reduceRight((children, Provider2) => /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(Provider2, {
          ...props,
          children
        }), /* @__PURE__ */ (0, import_jsx_runtime201.jsx)(scopedContext.Provider, { ...props }))
      });
    };
    return {
      context,
      scopedContext,
      useContext: useContext72,
      useScopedContext,
      useProviderContext,
      ContextProvider,
      ScopedContextProvider
    };
  }

  // node_modules/@ariakit/react-components/dist/focusable/focusable.js
  var import_react19 = __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 useEvent2((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_react19.useRef)(null);
    const [parentAccessibleWhenDisabled, metadataProps] = useMetadataProps(props, accessibleWhenDisabledSymbol, accessibleWhenDisabled);
    accessibleWhenDisabled ??= parentAccessibleWhenDisabled;
    (0, import_react19.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_react19.useState)(false);
    const focusVisibleRef = (0, import_react19.useRef)(false);
    const nativeSubmitObserverCleanupRef = (0, import_react19.useRef)(null);
    const cleanupFocusVisible = useEvent2((element) => {
      nativeSubmitObserverCleanupRef.current?.();
      nativeSubmitObserverCleanupRef.current = null;
      focusVisibleRef.current = false;
      element?.removeAttribute("data-focus-visible");
    });
    (0, import_react19.useEffect)(() => {
      if (!focusable2) return;
      if (!trulyDisabled) return;
      cleanupFocusVisible(ref.current);
      if (focusVisible) setFocusVisible(false);
    }, [
      focusable2,
      trulyDisabled,
      focusVisible,
      cleanupFocusVisible
    ]);
    (0, import_react19.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_react19.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 = useEvent2((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 = useEvent2((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 = useEvent2((event) => {
      onBlurProp?.(event);
      if (!focusable2) return;
      if (!isFocusEventOutside(event)) return;
      cleanupFocusVisible(event.currentTarget);
      setFocusVisible(false);
    });
    const autoFocusOnShow = (0, import_react19.useContext)(FocusableContext);
    const autoFocusRef = useEvent2((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_react19.useState)(false);
    if (isSafariBrowser) (0, import_react19.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_react19.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: useMergeRefs2(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 = forwardRef54(function Focusable2(props) {
    return createElement5(TagName, useFocusable(props));
  });

  // node_modules/@ariakit/react-components/dist/command/command.js
  var import_react20 = __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_react20.useRef)(null);
    const [isNativeButton, setIsNativeButton] = (0, import_react20.useState)(false);
    (0, import_react20.useEffect)(() => {
      if (!ref.current) return;
      setIsNativeButton(isButton(ref.current));
    }, []);
    const [active, setActive] = (0, import_react20.useState)(false);
    const activeRef = (0, import_react20.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 = useEvent2((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 = useEvent2((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 = useEvent2((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: useMergeRefs2(ref, props.ref),
      onKeyDown,
      onKeyUp,
      onBlur
    };
    props = useFocusable(props);
    return props;
  });
  var Command = forwardRef54(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_react21 = __toESM(require_react(), 1);
  var TagName3 = "div";
  var useCollectionItem = createHook(function useCollectionItem2({ store: store4, shouldRegisterItem = true, getItem = identity, element, ...props }) {
    const context = useCollectionContext();
    store4 = store4 || context;
    const id = useId5(props.id);
    const ref = (0, import_react21.useRef)(element);
    (0, import_react21.useEffect)(() => {
      const element2 = ref.current;
      if (!id) return;
      if (!element2) return;
      if (!shouldRegisterItem) return;
      const item = getItem({
        id,
        element: element2
      });
      return store4?.renderItem(item);
    }, [
      id,
      shouldRegisterItem,
      getItem,
      store4
    ]);
    props = {
      ...props,
      ref: useMergeRefs2(ref, props.ref)
    };
    return removeUndefinedValues(props);
  });
  var CollectionItem = forwardRef54(function CollectionItem2(props) {
    return createElement5(TagName3, useCollectionItem(props));
  });

  // node_modules/@ariakit/react-components/dist/composite/composite-context.js
  var import_react22 = __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_react22.createContext)(void 0);
  var CompositeRowContext = (0, import_react22.createContext)(void 0);

  // node_modules/@ariakit/store/dist/index.js
  function getInternal(store4, key) {
    const internals = store4.__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, state2, stateBeforeCleanup, updatedKey) {
    let cleanupPrevState;
    for (const key of getKeys(state2)) {
      if (isSameValue(state2[key], stateBeforeCleanup[key])) continue;
      if (updatedKey !== void 0 && hasUpdatedKey([key], updatedKey)) continue;
      cleanupPrevState ??= { ...prevState };
      cleanupPrevState[key] = state2[key];
    }
    return cleanupPrevState;
  }
  var MAX_REPAIR_PASSES = 100;
  function addKeyedListener(map, keys, listener) {
    if (!keys) return;
    for (const key of keys) {
      let listeners2 = map.get(key);
      if (!listeners2) {
        listeners2 = /* @__PURE__ */ new Set();
        map.set(key, listeners2);
      }
      listeners2.add(listener);
    }
  }
  function deleteKeyedListener(map, keys, listener) {
    if (!map) return;
    if (!keys) return;
    for (const key of keys) {
      const listeners2 = map.get(key);
      if (!listeners2) continue;
      listeners2.delete(listener);
      if (!listeners2.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, state2, prevState, getState2, 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 = state2;
      cleanup();
      state2 = getState2?.() ?? state2;
      if (state2 !== stateBeforeCleanup) prevState = getCleanupPrevState(prevState, state2, stateBeforeCleanup, updatedKey) ?? prevState;
    }
    const result = listener(state2, prevState);
    if (result) setListenerCleanup(group, listener, result);
  }
  function runLiveListeners({ group, getState: getState2, 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, getState2(), prevState, getState2, updatedKey);
    }
  }
  function createStore(initialState, ...stores) {
    let state2 = initialState;
    let prevStateBatch = state2;
    let destroy = noop6;
    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(state2);
      const desyncs = [];
      for (const store4 of stores) {
        const storeState = store4?.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(store4, [key], (state3) => {
            setState(key, state3[key], true);
          }));
          continue;
        }
        desyncs.push(subscribe3(store4, keys, (state3, prevState) => {
          for (const key of keys) {
            if (state3[key] === prevState[key]) continue;
            setState(key, state3[key], true);
          }
        }));
        for (const key of keys) {
          const liveState = store4?.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 = state2;
        runPendingCleanup(group, listener);
        if (state2 !== stateBeforeCleanups) cleanupPrevState = getCleanupPrevState(prevState, state2, stateBeforeCleanups);
        const cleanup = listener(state2, 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, state2);
      return registerListener(keys, listener);
    };
    const storeBatch = (keys, listener) => {
      if (!batchListenerGroup.listeners.size && !inDispatch) prevStateBatch = state2;
      runInitialListener(batchListenerGroup, listener, prevStateBatch);
      return registerListener(keys, listener, batchListenerGroup);
    };
    const storePick = (keys) => createStore(pick(state2, keys), finalStore);
    const storeOmit = (keys) => createStore(omit(state2, keys), finalStore);
    const getState2 = () => state2;
    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, state2, prevState, getState2, updatedKey);
            if (!group.allKeysListeners?.size && !frame.recoverToLive) continue;
            const notifiedListeners = frame.notifiedListeners ?? getFastPathNotifiedListeners(frame);
            frame.notifiedListeners = notifiedListeners;
            frame.recovering = true;
            runLiveListeners({
              group,
              getState: getState2,
              prevState,
              updatedKey,
              notifiedListeners
            });
            return;
          }
        } finally {
          fastPathFrames.pop();
        }
        return;
      }
      runLiveListeners({
        group,
        getState: getState2,
        prevState,
        updatedKey
      });
    };
    const setState = (key, value, fromStores = false) => {
      if (!hasOwnProperty(state2, key)) return;
      const currentValue = state2[key];
      const nextValue = typeof value === "function" ? value(currentValue) : value;
      if (isSameValue(nextValue, currentValue)) return;
      const wasInDispatch = inDispatch;
      inDispatch = true;
      const prevState = state2;
      const nextState = {
        ...state2,
        [key]: nextValue
      };
      state2 = nextState;
      let superseded = false;
      try {
        if (!fromStores && stores.length) {
          for (const store4 of stores) {
            store4?.setState?.(key, nextValue);
            if (isSameValue(state2[key], nextValue)) continue;
            superseded = true;
            break;
          }
          if (superseded) {
            let pass = 0;
            for (; pass < MAX_REPAIR_PASSES; pass += 1) {
              let changed = false;
              for (const store4 of stores) {
                const previousValue = state2[key];
                store4?.setState?.(key, previousValue);
                if (!isSameValue(state2[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, state2 === nextState ? prevState : {
          ...state2,
          [key]: prevState[key]
        }, key);
      } finally {
        inDispatch = wasInDispatch;
      }
      if (!batchListenerGroup.listeners.size) {
        if (!inDispatch) prevStateBatch = state2;
        return;
      }
      updatedKeys.add(key);
      if (batchPending) return;
      batchPending = true;
      queueMicrotask(() => {
        batchPending = false;
        const snapshot = state2;
        const updatedKeysSnapshot = updatedKeys;
        updatedKeys = /* @__PURE__ */ new Set();
        const prevStateBatchBefore = prevStateBatch;
        runListeners(batchListenerGroup, prevStateBatchBefore, updatedKeysSnapshot);
        if (prevStateBatch === prevStateBatchBefore) prevStateBatch = snapshot;
      });
    };
    const finalStore = {
      getState: getState2,
      setState,
      __unstableInternals: {
        setup: storeSetup,
        init: storeInit,
        subscribe: storeSubscribe,
        sync: storeSync,
        batch: storeBatch,
        pick: storePick,
        omit: storeOmit
      }
    };
    return finalStore;
  }
  function setup(store4, ...args) {
    if (!store4) return;
    return getInternal(store4, "setup")(...args);
  }
  function init(store4, ...args) {
    if (!store4) return;
    return getInternal(store4, "init")(...args);
  }
  function subscribe3(store4, ...args) {
    if (!store4) return;
    return getInternal(store4, "subscribe")(...args);
  }
  function sync2(store4, ...args) {
    if (!store4) return;
    return getInternal(store4, "sync")(...args);
  }
  function batch(store4, ...args) {
    if (!store4) return;
    return getInternal(store4, "batch")(...args);
  }
  function omit2(store4, ...args) {
    if (!store4) return;
    return getInternal(store4, "omit")(...args);
  }
  function pick2(store4, ...args) {
    if (!store4) return;
    return getInternal(store4, "pick")(...args);
  }
  function mergeStore(...stores) {
    const initialState = {};
    for (const store5 of stores) {
      const nextState = store5?.getState?.();
      if (nextState) Object.assign(initialState, nextState);
    }
    const store4 = createStore(initialState, ...stores);
    return Object.assign({}, ...stores, store4);
  }
  function throwOnConflictingProps(props, store4) {
    if (false) return;
    if (!store4) 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 = store4.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(store4) {
    return store4?.__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, (i3) => i3.element);
      privateStore.setState("renderedItems", sortedItems);
      collection.setState("renderedItems", sortedItems);
    };
    setup(collection, () => init(privateStore));
    setup(privateStore, () => {
      return batch(privateStore, ["items"], (state2) => {
        collection.setState("items", state2.items);
      });
    });
    setup(privateStore, () => {
      return batch(privateStore, ["renderedItems"], (state2) => {
        let firstRun = true;
        let raf2 = requestAnimationFrame(() => {
          const { renderedItems } = collection.getState();
          if (state2.renderedItems === renderedItems) return;
          sortItems(state2.renderedItems);
        });
        if (typeof IntersectionObserver !== "function") return () => cancelAnimationFrame(raf2);
        const ioCallback = () => {
          if (firstRun) {
            firstRun = false;
            return;
          }
          cancelAnimationFrame(raf2);
          raf2 = requestAnimationFrame(() => sortItems(state2.renderedItems));
        };
        const root = getCommonParent(state2.renderedItems);
        const observer = new IntersectionObserver(ioCallback, { root });
        for (const item of state2.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 i3 = fromIndex; i3 >= 0 && i3 < items.length; i3 += step) {
      const item = items[i3];
      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: length2 } of array) if (length2 > maxLength) maxLength = length2;
    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 i3 = 0; i3 < maxLength; i3 += 1) {
      const item = row[i3];
      if (!item || focusShift && item.disabled) {
        const previousItem = i3 === 0 && focusShift ? findFirstEnabledItem(row) : row[i3 - 1];
        row[i3] = 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 i3 = 0; i3 < maxLength; i3 += 1) for (const row of rows) {
      const item = row[i3];
      if (item) verticalized.push({
        ...item,
        rowId: item.rowId ? `${i3}` : 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"], (state2) => {
      composite.setState("activeId", (activeId2) => {
        if (activeId2 !== void 0) return activeId2;
        return findFirstEnabledItem(state2.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(store4, id) {
    if (!id) return null;
    return store4.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(store4, element, exclude) {
    if (!element) return false;
    if (element === exclude) return false;
    const item = store4.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_react23 = __toESM(require_react(), 1);
  var import_jsx_runtime202 = __toESM(require_jsx_runtime(), 1);

  // node_modules/@ariakit/react-store/dist/index.js
  var React76 = __toESM(require_react(), 1);
  var import_shim3 = __toESM(require_shim(), 1);
  var noopSubscribe = () => () => {
  };
  function useStoreState(store4, keyOrSelector = identity) {
    const storeSubscribe = React76.useCallback((callback) => {
      if (!store4) return noopSubscribe();
      return subscribe3(store4, null, callback);
    }, [store4]);
    const getSnapshot2 = () => {
      const key = typeof keyOrSelector === "string" ? keyOrSelector : null;
      const selector2 = typeof keyOrSelector === "function" ? keyOrSelector : null;
      const state2 = store4?.getState();
      if (selector2) return selector2(state2);
      if (!state2) return;
      if (!key) return;
      if (!hasOwnProperty(state2, key)) return;
      return state2[key];
    };
    return (0, import_shim3.useSyncExternalStore)(storeSubscribe, getSnapshot2, getSnapshot2);
  }
  function useStoreStateObject(store4, object) {
    const objRef = React76.useRef({});
    const storeSubscribe = React76.useCallback((callback) => {
      if (!store4) return noopSubscribe();
      return subscribe3(store4, null, callback);
    }, [store4]);
    const getSnapshot2 = () => {
      const state2 = store4?.getState();
      let updated = false;
      const obj = objRef.current;
      for (const prop in object) {
        const keyOrSelector = object[prop];
        if (typeof keyOrSelector === "function") {
          const value = keyOrSelector(state2);
          if (!Object.is(value, obj[prop])) {
            obj[prop] = value;
            updated = true;
          }
        }
        if (typeof keyOrSelector === "string") {
          if (!state2) continue;
          if (!hasOwnProperty(state2, keyOrSelector)) continue;
          const value = state2[keyOrSelector];
          if (!Object.is(value, obj[prop])) {
            obj[prop] = value;
            updated = true;
          }
        }
      }
      if (updated) objRef.current = { ...obj };
      return objRef.current;
    };
    return (0, import_shim3.useSyncExternalStore)(storeSubscribe, getSnapshot2, getSnapshot2);
  }
  function useStoreProps(store4, 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(store4, [key], (state2, prev) => {
        const { value: value2, setValue } = propsRef.current;
        if (!setValue) return;
        if (state2[key] === prev[key]) return;
        if (state2[key] === value2) return;
        setValue(state2[key]);
      });
    }, [store4, key]);
    useSafeLayoutEffect(() => {
      if (value === void 0) return;
      store4.setState(key, value);
      return batch(store4, [key], () => {
        if (value === void 0) return;
        store4.setState(key, value);
      });
    });
  }
  function useStore2(createStore2, props) {
    const [store4, setStore] = React76.useState(() => createStore2(props));
    useSafeLayoutEffect(() => init(store4), [store4]);
    const useState161 = React76.useCallback((keyOrSelector) => useStoreState(store4, keyOrSelector), [store4]);
    return [React76.useMemo(() => ({
      ...store4,
      useState: useState161
    }), [store4, useState161]), useEvent2(() => {
      setStore((store5) => createStore2({
        ...props,
        ...store5.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, store4, next, pageUp = false) {
    if (!store4) return;
    if (!next) return;
    const { renderedItems } = store4.getState();
    const scrollingElement = getScrollingElement(element);
    if (!scrollingElement) return;
    const nextPageOffset = getNextPageOffset(scrollingElement, pageUp);
    let id;
    let prevDifference;
    for (let i3 = 0; i3 < renderedItems.length; i3 += 1) {
      const previousId = id;
      id = next(i3);
      if (!id) break;
      if (id === previousId) continue;
      const itemElement = getEnabledItem(store4, 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, store4) {
    if (isSelfTarget(event)) return false;
    return isItem(store4, event.target);
  }
  var useCompositeItem2 = createHook(function useCompositeItem3({ store: store4, rowId: rowIdProp, preventScrollOnKeyDown = false, moveOnKeyPress = true, tabbable: tabbable2 = false, getItem: getItemProp, "aria-setsize": ariaSetSizeProp, "aria-posinset": ariaPosInSetProp, ...props }) {
    const context = useCompositeScopedContext();
    store4 = store4 || context;
    const id = useId5(props.id);
    const ref = (0, import_react23.useRef)(null);
    const row = (0, import_react23.useContext)(CompositeRowContext);
    const trulyDisabled = disabledFromProps(props) && !props.accessibleWhenDisabled;
    const shouldRegisterItem = props.shouldRegisterItem;
    const getRowId = (state2) => {
      if (rowIdProp) return rowIdProp;
      if (!state2) return;
      if (!row?.baseElement) return;
      if (row.baseElement !== state2.baseElement) return;
      return row.id;
    };
    const { rowId, baseElement, isActiveItem, ariaSetSize, ariaPosInSet, isTabbable } = useStoreStateObject(store4, {
      rowId: getRowId,
      baseElement(state2) {
        return state2?.baseElement || void 0;
      },
      isActiveItem(state2) {
        return !!state2 && state2.activeId === id;
      },
      ariaSetSize(state2) {
        if (ariaSetSizeProp != null) return ariaSetSizeProp;
        if (!state2) return;
        if (!row?.ariaSetSize) return;
        if (row.baseElement !== state2.baseElement) return;
        return row.ariaSetSize;
      },
      ariaPosInSet(state2) {
        if (ariaPosInSetProp != null) return ariaPosInSetProp;
        if (!state2) return;
        if (!row?.ariaPosInSet) return;
        if (row.baseElement !== state2.baseElement) return;
        const rowId2 = getRowId(state2);
        const itemsInRow = state2.renderedItems.filter((item) => item.rowId === rowId2);
        return row.ariaPosInSet + itemsInRow.findIndex((item) => item.id === id);
      },
      isTabbable(state2) {
        if (!state2?.renderedItems.length) return true;
        if (state2.virtualFocus) return false;
        if (tabbable2) return true;
        if (state2.activeId === null) return false;
        const item = store4?.item(state2.activeId);
        if (item?.disabled) return true;
        if (!item?.element) return true;
        return state2.activeId === id;
      }
    });
    const getItem = (0, import_react23.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_react23.useRef)(false);
    const cancelScheduledFocusRedirectRef = (0, import_react23.useRef)(null);
    const onFocus = useEvent2((event) => {
      onFocusProp?.(event);
      if (event.defaultPrevented) return;
      if (isPortalEvent(event)) return;
      if (!id) return;
      if (!store4) return;
      if (targetIsAnotherItem(event, store4)) return;
      const { virtualFocus, baseElement: baseElement2 } = store4.getState();
      store4.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(store4, 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 = subscribe3(store4, null, () => {
        if (getActiveElement(currentTarget) !== currentTarget) {
          cancelScheduledFocusRedirect();
          return;
        }
        const state2 = store4.getState();
        const nextBaseElement = state2.baseElement;
        if (!nextBaseElement?.isConnected) return;
        cancelScheduledFocusRedirect();
        if (!state2.virtualFocus) return;
        redirectFocusToBaseElement(currentTarget, relatedTarget, nextBaseElement);
      });
    });
    const onBlurCaptureProp = props.onBlurCapture;
    const onBlurCapture = useEvent2((event) => {
      onBlurCaptureProp?.(event);
      if (event.defaultPrevented) return;
      if (store4?.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 = useEvent2((event) => {
      onKeyDownProp?.(event);
      if (event.defaultPrevented) return;
      if (!isSelfTarget(event)) return;
      if (!store4) return;
      const { currentTarget } = event;
      const state2 = store4.getState();
      const isGrid2 = !!store4.item(id)?.rowId;
      const isVertical = state2.orientation !== "horizontal";
      const isHorizontal = state2.orientation !== "vertical";
      const canHomeEnd = () => {
        if (isGrid2) return true;
        if (isHorizontal) return true;
        if (!state2.baseElement) return true;
        if (!isTextField(state2.baseElement)) return true;
        return false;
      };
      const action = {
        ArrowUp: (isGrid2 || isVertical) && store4.up,
        ArrowRight: (isGrid2 || isHorizontal) && store4.next,
        ArrowDown: (isGrid2 || isVertical) && store4.down,
        ArrowLeft: (isGrid2 || isHorizontal) && store4.previous,
        Home: () => {
          if (!canHomeEnd()) return;
          if (!isGrid2 || event.ctrlKey) return store4?.first();
          return store4?.previous(-1);
        },
        End: () => {
          if (!canHomeEnd()) return;
          if (!isGrid2 || event.ctrlKey) return store4?.last();
          return store4?.next(-1);
        },
        PageUp: () => {
          return findNextPageItemId(currentTarget, store4, store4?.up, true);
        },
        PageDown: () => {
          return findNextPageItemId(currentTarget, store4, store4?.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();
          store4.move(nextId2);
        }
      }
    });
    const providerValue = (0, import_react23.useMemo)(() => ({
      id,
      baseElement
    }), [id, baseElement]);
    props = useWrapElement(props, (element) => /* @__PURE__ */ (0, import_jsx_runtime202.jsx)(CompositeItemContext.Provider, {
      value: providerValue,
      children: element
    }), [providerValue]);
    props = {
      "data-active-item": isActiveItem || void 0,
      ...props,
      id,
      ref: useMergeRefs2(ref, props.ref),
      tabIndex: isTabbable ? props.tabIndex : -1,
      onFocus,
      onBlurCapture,
      onKeyDown
    };
    props = useCommand(props);
    props = useCollectionItem({
      store: store4,
      ...props,
      getItem,
      shouldRegisterItem: id ? shouldRegisterItem : false
    });
    return removeUndefinedValues({
      ...props,
      "aria-setsize": ariaSetSize,
      "aria-posinset": ariaPosInSet
    });
  });
  var CompositeItem = memo4(forwardRef54(function CompositeItem2(props) {
    return createElement5(TagName4, useCompositeItem2(props));
  }));

  // node_modules/@ariakit/react-components/dist/composite/composite.js
  var import_react24 = __toESM(require_react(), 1);
  var import_jsx_runtime203 = __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(store4, onKeyboardEvent, previousElementRef) {
    return useEvent2((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(store4, store4.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(store4, callback) {
    const { virtualFocus, baseElement } = store4.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(store4) {
    const [scheduled, setScheduled] = (0, import_react24.useState)(false);
    const schedule2 = (0, import_react24.useCallback)(() => setScheduled(true), []);
    const activeItem = useStoreState(store4, (state2) => scheduled ? getEnabledItem(store4, state2.activeId) : null);
    (0, import_react24.useEffect)(() => {
      const activeElement2 = activeItem?.element;
      if (!scheduled) return;
      if (!activeElement2) return;
      setScheduled(false);
      withBaseScrollPreserved(store4, () => {
        activeElement2.focus({ preventScroll: true });
      });
    }, [
      store4,
      activeItem,
      scheduled
    ]);
    return schedule2;
  }
  var CompositeFocusOnMove = memo4(function CompositeFocusOnMove2({ store: store4, focusOnMove, previousElementRef }) {
    const moves = useStoreState(store4, "moves");
    const baseElement = useStoreState(store4, "baseElement");
    (0, import_react24.useEffect)(() => {
      if (!moves) return;
      if (!focusOnMove) return;
      const { activeId } = store4.getState();
      const itemElement = getEnabledItem(store4, activeId)?.element;
      if (!itemElement) return;
      withBaseScrollPreserved(store4, () => focusIntoView(itemElement));
    }, [
      store4,
      moves,
      focusOnMove
    ]);
    useSafeLayoutEffect(() => {
      if (!moves) return;
      if (!baseElement) return;
      const { activeId } = store4.getState();
      if (!(activeId === null)) return;
      const previousElement = previousElementRef.current;
      previousElementRef.current = null;
      if (previousElement) fireBlurEvent(previousElement, { relatedTarget: baseElement });
      if (!hasFocus(baseElement)) baseElement.focus();
    }, [
      store4,
      moves,
      baseElement
    ]);
    return null;
  });
  var useComposite = createHook(function useComposite2({ store: store4, composite = true, focusOnMove = composite, moveOnKeyPress = true, ...props }) {
    const context = useCompositeProviderContext();
    store4 = store4 || context;
    invariant(store4, "Composite must receive a `store` prop or be wrapped in a CompositeProvider component.");
    const ref = (0, import_react24.useRef)(null);
    const previousElementRef = (0, import_react24.useRef)(null);
    const scheduleFocus = useScheduleFocus(store4);
    const [, setBaseElement] = useTransactionState(composite ? store4.setBaseElement : null);
    const virtualFocus = useStoreState(store4, "virtualFocus");
    const activeId = useStoreState(store4, (state2) => state2.virtualFocus ? state2.activeId : null);
    useSafeLayoutEffect(() => {
      if (!store4) return;
      if (!composite) return;
      if (!virtualFocus) return;
      const previousElement = previousElementRef.current;
      previousElementRef.current = null;
      if (!previousElement) return;
      const relatedTarget = getEnabledItem(store4, activeId)?.element || getActiveElement(previousElement);
      if (relatedTarget === previousElement) return;
      fireBlurEvent(previousElement, { relatedTarget });
    }, [
      store4,
      activeId,
      virtualFocus,
      composite
    ]);
    const onKeyDownCapture = useKeyboardEventProxy(store4, props.onKeyDownCapture, previousElementRef);
    const onKeyUpCapture = useKeyboardEventProxy(store4, props.onKeyUpCapture, previousElementRef);
    const onFocusCaptureProp = props.onFocusCapture;
    const onFocusCapture = useEvent2((event) => {
      onFocusCaptureProp?.(event);
      if (event.defaultPrevented) return;
      if (!store4) return;
      const { virtualFocus: virtualFocus2 } = store4.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 = useEvent2((event) => {
      onFocusProp?.(event);
      if (event.defaultPrevented) return;
      if (!composite) return;
      if (!store4) return;
      const { relatedTarget } = event;
      const { virtualFocus: virtualFocus2 } = store4.getState();
      if (virtualFocus2) {
        if (isSelfTarget(event) && !isItem(store4, relatedTarget)) queueMicrotask(scheduleFocus);
      } else if (isSelfTarget(event)) store4.setActiveId(null);
    });
    const onBlurCaptureProp = props.onBlurCapture;
    const onBlurCapture = useEvent2((event) => {
      onBlurCaptureProp?.(event);
      if (event.defaultPrevented) return;
      if (!store4) return;
      const { virtualFocus: virtualFocus2, activeId: activeId2 } = store4.getState();
      if (!virtualFocus2) return;
      const activeElement2 = getEnabledItem(store4, activeId2)?.element;
      const nextActiveElement = event.relatedTarget;
      const nextActiveElementIsItem = isItem(store4, 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(store4, event.target) && activeElement2) fireBlurEvent(activeElement2, event);
    });
    const onKeyDownProp = props.onKeyDown;
    const moveOnKeyPressProp = useBooleanEvent(moveOnKeyPress);
    const onKeyDown = useEvent2((event) => {
      onKeyDownProp?.(event);
      if (event.nativeEvent.isComposing) return;
      if (event.defaultPrevented) return;
      if (!store4) return;
      if (!isSelfTarget(event)) return;
      const { orientation, renderedItems, activeId: activeId2, rtl } = store4.getState();
      if (getEnabledItem(store4, 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 store4?.last();
      };
      const action = {
        ArrowUp: (grid || isVertical) && up,
        ArrowRight: (grid || isHorizontal) && (rtl ? store4.last : store4.first),
        ArrowDown: (grid || isVertical) && store4.first,
        ArrowLeft: (grid || isHorizontal) && (rtl ? store4.first : store4.last),
        Home: store4.first,
        End: store4.last,
        PageUp: store4.first,
        PageDown: store4.last
      }[event.key];
      if (action) {
        const id = action();
        if (id !== void 0) {
          if (!moveOnKeyPressProp(event)) return;
          event.preventDefault();
          store4.move(id);
        }
      }
    });
    props = useWrapElement(props, (element) => /* @__PURE__ */ (0, import_jsx_runtime203.jsxs)(CompositeScopedContextProvider, {
      value: store4,
      children: [element, composite && /* @__PURE__ */ (0, import_jsx_runtime203.jsx)(CompositeFocusOnMove, {
        store: store4,
        focusOnMove,
        previousElementRef
      })]
    }), [
      store4,
      composite,
      focusOnMove
    ]);
    props = {
      "aria-activedescendant": useStoreState(store4, (state2) => {
        if (!store4) return;
        if (!composite) return;
        if (!state2.virtualFocus) return;
        return getEnabledItem(store4, state2.activeId)?.id;
      }),
      ...props,
      ref: useMergeRefs2(ref, setBaseElement, props.ref),
      onKeyDownCapture,
      onKeyUpCapture,
      onFocusCapture,
      onFocus,
      onBlurCapture,
      onKeyDown
    };
    props = useFocusable({
      focusable: useStoreState(store4, (state2) => composite && (state2.virtualFocus || state2.activeId === null)),
      ...props
    });
    return props;
  });
  var Composite6 = forwardRef54(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_react25 = __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_react25.createContext)(void 0);
  var DialogDescriptionContext = (0, import_react25.createContext)(void 0);

  // node_modules/@ariakit/react-components/dist/disclosure/disclosure-content.js
  var import_react26 = __toESM(require_react(), 1);
  var import_jsx_runtime204 = __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: store4, alwaysVisible, unstable_otherElementRef: otherElementRef, ...props }) {
    const context = useDisclosureProviderContext();
    store4 = store4 || context;
    invariant(store4, "DisclosureContent must receive a `store` prop or be wrapped in a DisclosureProvider component.");
    const ref = (0, import_react26.useRef)(null);
    const id = useId5(props.id);
    const [transition, setTransition] = (0, import_react26.useState)(null);
    const open = useStoreState(store4, "open");
    const mounted = useStoreState(store4, "mounted");
    const animated2 = useStoreState(store4, "animated");
    const contentElement = useStoreState(store4, "contentElement");
    const otherElement = useStoreState(store4.disclosure, "contentElement");
    const hasClosedRef = (0, import_react26.useRef)(false);
    useSafeLayoutEffect(() => {
      if (!ref.current) return;
      store4?.setContentElement(ref.current);
    }, [store4]);
    useSafeLayoutEffect(() => {
      let previousAnimated;
      store4?.setState("animated", (animated3) => {
        previousAnimated = animated3;
        return true;
      });
      return () => {
        if (previousAnimated === void 0) return;
        store4?.setState("animated", previousAnimated);
      };
    }, [store4]);
    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 (!store4) return;
      if (!animated2) return;
      if (!transition) return;
      if (!contentElement) return;
      const stopAnimation = () => store4?.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") store4.setState("animated", false);
        stopAnimation();
        return;
      }
      return afterTimeout(Math.max(timeout - 1e3 / 60, 0), stopAnimationSync);
    }, [
      store4,
      animated2,
      contentElement,
      otherElement,
      otherElementRef,
      open,
      transition
    ]);
    props = useWrapElement(props, (element) => /* @__PURE__ */ (0, import_jsx_runtime204.jsx)(DialogScopedContextProvider, {
      value: store4,
      children: element
    }), [store4]);
    const hidden = isHidden(mounted, props.hidden, alwaysVisible);
    const styleProp = props.style;
    const style = (0, import_react26.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: useMergeRefs2(id ? store4.setContentElement : null, ref, props.ref),
      style
    };
    return removeUndefinedValues(props);
  });
  var DisclosureContentImpl = forwardRef54(function DisclosureContentImpl2(props) {
    return createElement5(TagName6, useDisclosureContent(props));
  });
  var DisclosureContent = forwardRef54(function DisclosureContent2({ unmountOnHide, ...props }) {
    const context = useDisclosureProviderContext();
    if (useStoreState(props.store || context, (state2) => !unmountOnHide || state2?.mounted) === false) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime204.jsx)(DisclosureContentImpl, { ...props });
  });

  // node_modules/@ariakit/components/dist/disclosure/disclosure-store.js
  function createDisclosureStore(props = {}) {
    const store4 = mergeStore(props.store, omit2(props.disclosure, ["contentElement", "disclosureElement"]));
    throwOnConflictingProps(props, store4);
    const syncState = store4?.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)
    }, store4);
    setup(disclosure, () => sync2(disclosure, ["animated", "animating"], (state2) => {
      if (state2.animated) return;
      disclosure.setState("animating", false);
    }));
    setup(disclosure, () => subscribe3(disclosure, ["open"], () => {
      if (!disclosure.getState().animated) return;
      disclosure.setState("animating", true);
    }));
    setup(disclosure, () => sync2(disclosure, ["open", "animating"], (state2) => {
      disclosure.setState("mounted", state2.open || state2.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(store4, update4, props) {
    useUpdateEffect(update4, [props.store, props.disclosure]);
    useStoreProps(store4, props, "open", "setOpen");
    useStoreProps(store4, props, "mounted", "setMounted");
    useStoreProps(store4, props, "animated");
    return Object.assign(store4, { 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_react27 = __toESM(require_react(), 1);
  var ComboboxListRoleContext = (0, import_react27.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_react27.createContext)(void 0);
  var ComboboxItemCheckedContext = (0, import_react27.createContext)(false);

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

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

  // 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(store4, update4, props) {
    return useDisclosureStoreProps(store4, update4, props);
  }

  // node_modules/@ariakit/components/dist/popover/popover-store.js
  function createPopoverStore({ popover: otherPopover, ...props } = {}) {
    const store4 = mergeStore(props.store, omit2(otherPopover, [
      "arrowElement",
      "anchorElement",
      "contentElement",
      "popoverElement",
      "disclosureElement"
    ]));
    throwOnConflictingProps(props, store4);
    const syncState = store4?.getState();
    const dialog = createDialogStore({
      ...props,
      store: store4
    });
    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, store4);
    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(store4, update4, props) {
    useUpdateEffect(update4, [props.popover]);
    useStoreProps(store4, props, "placement");
    return useDialogStoreProps(store4, update4, props);
  }

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

  // node_modules/@ariakit/react-components/dist/composite/composite-hover.js
  var import_react28 = __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: store4, focusOnHover = true, blurOnHoverEnd = !!focusOnHover, ...props }) {
    const context = useCompositeScopedContext();
    store4 = store4 || context;
    invariant(store4, "CompositeHover must be wrapped in a Composite component.");
    const isMouseMoving = useIsMouseMoving();
    const onMouseMoveProp = props.onMouseMove;
    const focusOnHoverProp = useBooleanEvent(focusOnHover);
    const onMouseMove = useEvent2((event) => {
      onMouseMoveProp?.(event);
      if (event.defaultPrevented) return;
      if (!isMouseMoving()) return;
      if (!focusOnHoverProp(event)) return;
      if (!hasFocusWithin(event.currentTarget)) {
        const baseElement = store4?.getState().baseElement;
        if (baseElement && !hasFocus(baseElement)) baseElement.focus();
      }
      store4?.setActiveId(event.currentTarget.id);
    });
    const onMouseLeaveProp = props.onMouseLeave;
    const blurOnHoverEndProp = useBooleanEvent(blurOnHoverEnd);
    const onMouseLeave = useEvent2((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;
      store4?.setActiveId(null);
      store4?.getState().baseElement?.focus();
    });
    const ref = (0, import_react28.useCallback)((element) => {
      if (!element) return;
      element[symbol2] = true;
    }, []);
    props = {
      ...props,
      ref: useMergeRefs2(ref, props.ref),
      onMouseMove,
      onMouseLeave
    };
    return removeUndefinedValues(props);
  });
  var CompositeHover = memo4(forwardRef54(function CompositeHover2(props) {
    return createElement5(TagName8, useCompositeHover(props));
  }));

  // node_modules/@ariakit/react-components/dist/combobox/combobox.js
  var import_react29 = __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: store4, 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();
    store4 = store4 || context;
    invariant(store4, "Combobox must receive a `store` prop or be wrapped in a ComboboxProvider component.");
    const ref = (0, import_react29.useRef)(null);
    const [valueUpdated, forceValueUpdate] = useForceUpdate2();
    const canAutoSelectRef = (0, import_react29.useRef)(false);
    const composingRef = (0, import_react29.useRef)(false);
    const autoSelect = useStoreState(store4, (state2) => state2.virtualFocus && autoSelectProp);
    const inline4 = autoComplete === "inline" || autoComplete === "both";
    const [canInline, setCanInline] = (0, import_react29.useState)(inline4);
    useUpdateLayoutEffect(() => {
      if (!inline4) return;
      setCanInline(true);
    }, [inline4]);
    const storeValue = useStoreState(store4, "value");
    const prevSelectedValueRef = (0, import_react29.useRef)(void 0);
    (0, import_react29.useEffect)(() => {
      return sync2(store4, ["selectedValue", "activeId"], (_, prev) => {
        prevSelectedValueRef.current = prev.selectedValue;
      });
    }, [store4]);
    const inlineActiveValue = useStoreState(store4, (state2) => {
      if (!inline4) return;
      if (!canInline) return;
      if (state2.activeValue && Array.isArray(state2.selectedValue)) {
        if (state2.selectedValue.includes(state2.activeValue)) return;
        if (prevSelectedValueRef.current?.includes(state2.activeValue)) return;
      }
      return state2.activeValue;
    });
    const items = useStoreState(store4, "renderedItems");
    const open = useStoreState(store4, "open");
    const contentElement = useStoreState(store4, "contentElement");
    const value = (0, import_react29.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_react29.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_react29.useEffect)(() => {
      if (!inline4) return;
      if (!canInline) return;
      if (!inlineActiveValue) return;
      if (!isFirstItemAutoSelected(items, inlineActiveValue, autoSelect)) return;
      if (!hasCompletionString(storeValue, inlineActiveValue)) return;
      let cleanup = noop6;
      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 = useEvent2(getAutoSelectId);
    const autoSelectIdRef = (0, import_react29.useRef)(null);
    const autoSelectMovedRef = (0, import_react29.useRef)(void 0);
    const userScrolledRef = (0, import_react29.useRef)(false);
    const isAutoScrollingRef = (0, import_react29.useRef)(false);
    (0, import_react29.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 (!store4) return;
        if (!canAutoSelectRef.current) return;
        const { activeId } = store4.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,
      store4
    ]);
    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(store4, "resetValueOnSelect");
    useUpdateEffect(() => {
      const canAutoSelect = canAutoSelectRef.current;
      if (!store4) return;
      if (!open) return;
      if (!canAutoSelect && (!resetValueOnSelect || userScrolledRef.current)) return;
      const { baseElement, contentElement: contentElement2, activeId } = store4.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) ?? store4.first();
        autoSelectIdRef.current = autoSelectId;
        const nextActiveId = autoSelectId ?? null;
        const nextActiveValue = store4.item(nextActiveId)?.value;
        const moved = autoSelectMovedRef.current;
        if (nextActiveId !== activeId || moved?.id !== nextActiveId || moved?.value !== nextActiveValue) {
          autoSelectMovedRef.current = {
            id: nextActiveId,
            value: nextActiveValue
          };
          store4.move(nextActiveId);
        } else store4.setState("activeValue", nextActiveValue);
      } else {
        const element = store4.item(activeId || store4.first())?.element;
        if (element && "scrollIntoView" in element) {
          isAutoScrollingRef.current = true;
          element.scrollIntoView({
            block: "nearest",
            inline: "nearest"
          });
          requestAnimationFrame(() => {
            isAutoScrollingRef.current = false;
          });
        }
      }
    }, [
      store4,
      open,
      valueUpdated,
      storeValue,
      autoSelect,
      resetValueOnSelect,
      getAutoSelectIdProp,
      items
    ]);
    (0, import_react29.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))) store4?.setValue(value);
      };
      for (const element of elements2) element.addEventListener("focusout", onBlur2);
      return () => {
        for (const element of elements2) element.removeEventListener("focusout", onBlur2);
      };
    }, [
      inline4,
      contentElement,
      store4,
      value
    ]);
    const canShow = (event) => {
      return event.currentTarget.value.length >= showMinLength;
    };
    const onChangeProp = props.onChange;
    const showOnChangeProp = useBooleanEvent(showOnChange ?? canShow);
    const setValueOnChangeProp = useBooleanEvent(setValueOnChange ?? !store4.tag);
    const onChange = useEvent2((event) => {
      onChangeProp?.(event);
      if (event.defaultPrevented) return;
      if (!store4) 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 === store4.getState().value;
        store4.setValue(value2);
        queueMicrotask(() => {
          setSelectionRange(currentTarget, selectionStart, selectionEnd);
        });
        if (inline4 && autoSelect && isSameValue2) forceValueUpdate();
      }
      if (showOnChangeProp(event)) store4.show();
      if (!autoSelect || !canAutoSelectRef.current) store4.setActiveId(null);
    });
    const onCompositionEndProp = props.onCompositionEnd;
    const onCompositionEnd = useEvent2((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 ?? (() => store4.getState().includesBaseElement));
    const setValueOnClickProp = useBooleanEvent(setValueOnClick);
    const showOnClickProp = useBooleanEvent(showOnClick ?? canShow);
    const onMouseDown = useEvent2((event) => {
      onMouseDownProp?.(event);
      if (event.defaultPrevented) return;
      if (event.button) return;
      if (event.ctrlKey) return;
      if (!store4) return;
      if (blurActiveItemOnClickProp(event)) store4.setActiveId(null);
      if (setValueOnClickProp(event)) store4.setValue(value);
      if (showOnClickProp(event)) queueBeforeEvent(event.currentTarget, "mouseup", store4.show);
    });
    const onKeyDownProp = props.onKeyDown;
    const showOnKeyPressProp = useBooleanEvent(showOnKeyPress ?? canShow);
    const onKeyDown = useEvent2((event) => {
      onKeyDownProp?.(event);
      if (!event.repeat) canAutoSelectRef.current = false;
      if (event.defaultPrevented) return;
      if (!store4) return;
      const { open: open2 } = store4.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();
          store4.show();
        }
      }
    });
    const onBlurProp = props.onBlur;
    const onBlur = useEvent2((event) => {
      canAutoSelectRef.current = false;
      onBlurProp?.(event);
    });
    const id = useId5(props.id);
    const ariaAutoComplete = isAriaAutoCompleteValue(autoComplete) ? autoComplete : void 0;
    const isActiveItem = useStoreState(store4, (state2) => state2.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: useMergeRefs2(ref, props.ref),
      onChange,
      onCompositionEnd,
      onMouseDown,
      onKeyDown,
      onBlur
    };
    props = useComposite({
      store: store4,
      focusable: focusable2,
      ...props,
      moveOnKeyPress: (event) => {
        if (isFalsyBooleanCallback(moveOnKeyPress, event)) return false;
        if (inline4) setCanInline(true);
        return true;
      }
    });
    props = usePopoverAnchor({
      store: store4,
      ...props
    });
    return {
      autoComplete: "off",
      ...props
    };
  });
  var Combobox = forwardRef54(function Combobox2(props) {
    return createElement5(TagName9, useCombobox(props));
  });

  // node_modules/@ariakit/react-components/dist/combobox/combobox-item.js
  var import_react30 = __toESM(require_react(), 1);
  var import_jsx_runtime205 = __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: store4, value, hideOnClick, setValueOnClick, selectValueOnClick = true, resetValueOnSelect, focusOnHover = false, moveOnKeyPress = true, getItem: getItemProp, ...props }) {
    const context = useComboboxScopedContext();
    store4 = store4 || context;
    invariant(store4, "ComboboxItem must be wrapped in a ComboboxList or ComboboxPopover component.");
    const { resetValueOnSelectState, multiSelectable, selected } = useStoreStateObject(store4, {
      resetValueOnSelectState: "resetValueOnSelect",
      multiSelectable(state2) {
        return Array.isArray(state2.selectedValue);
      },
      selected(state2) {
        return isSelected(state2.selectedValue, value);
      }
    });
    const getItem = (0, import_react30.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 = useEvent2((event) => {
      onClickProp?.(event);
      if (event.defaultPrevented) return;
      if (isDownloading(event)) return;
      if (isOpeningInNewTab(event)) return;
      if (value != null) {
        if (selectValueOnClickProp(event)) {
          if (resetValueOnSelectProp(event)) store4?.resetValue();
          store4?.setSelectedValue((prevValue) => {
            if (!Array.isArray(prevValue)) return value;
            if (prevValue.includes(value)) return prevValue.filter((v3) => v3 !== value);
            return [...prevValue, value];
          });
        }
        if (setValueOnClickProp(event)) store4?.setValue(value);
      }
      if (hideOnClickProp(event)) store4?.hide();
    });
    const onKeyDownProp = props.onKeyDown;
    const onKeyDown = useEvent2((event) => {
      onKeyDownProp?.(event);
      if (event.defaultPrevented) return;
      const baseElement = store4?.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)) store4?.setValue(baseElement.value);
      }
    });
    if (multiSelectable && selected != null) props = {
      "aria-selected": selected,
      ...props
    };
    props = useWrapElement(props, (element) => /* @__PURE__ */ (0, import_jsx_runtime205.jsx)(ComboboxItemValueContext.Provider, {
      value,
      children: /* @__PURE__ */ (0, import_jsx_runtime205.jsx)(ComboboxItemCheckedContext.Provider, {
        value: selected ?? false,
        children: element
      })
    }), [value, selected]);
    props = {
      role: getItemRole((0, import_react30.useContext)(ComboboxListRoleContext)),
      children: value,
      ...props,
      onClick,
      onKeyDown
    };
    const moveOnKeyPressProp = useBooleanEvent(moveOnKeyPress);
    props = useCompositeItem2({
      store: store4,
      ...props,
      getItem,
      moveOnKeyPress: (event) => {
        if (!moveOnKeyPressProp(event)) return false;
        const moveEvent = new Event("combobox-item-move");
        store4?.getState().baseElement?.dispatchEvent(moveEvent);
        return true;
      }
    });
    props = useCompositeHover({
      store: store4,
      focusOnHover,
      ...props
    });
    return props;
  });
  var ComboboxItem = memo4(forwardRef54(function ComboboxItem2(props) {
    return createElement5(TagName10, useComboboxItem(props));
  }));

  // node_modules/@ariakit/react-components/dist/combobox/combobox-item-value.js
  var import_react31 = __toESM(require_react(), 1);
  var import_jsx_runtime206 = __toESM(require_jsx_runtime(), 1);
  var TagName11 = "span";
  function normalizeValue2(value) {
    return normalizeString(value).toLowerCase();
  }
  function getOffsets(string, values) {
    const offsets = [];
    for (const value of values) {
      if (!value) continue;
      let pos = 0;
      const length2 = value.length;
      let index2 = string.indexOf(value, pos);
      while (index2 !== -1) {
        offsets.push([index2, length2]);
        pos = index2 + 1;
        index2 = string.indexOf(value, pos);
      }
    }
    return offsets;
  }
  function mergeOverlappingOffsets(offsets) {
    offsets.sort(([a3], [b3]) => a3 - b3);
    const merged = [];
    for (const [offset4, length2] of offsets) {
      const last = merged[merged.length - 1];
      if (last && offset4 < last[0] + last[1]) last[1] = Math.max(last[1], offset4 + length2 - last[0]);
      else merged.push([offset4, length2]);
    }
    return merged;
  }
  function getNormalizedIndexes(itemValue) {
    const starts = [];
    const ends = [];
    let index2 = 0;
    for (const char of itemValue) {
      const normalizedLength = normalizeValue2(char).length;
      for (let i3 = 0; i3 < normalizedLength; i3 += 1) {
        starts.push(i3 === 0 ? index2 : -1);
        ends.push(index2);
      }
      index2 += char.length;
    }
    starts.push(itemValue.length);
    ends.push(itemValue.length);
    let nextBoundary = itemValue.length;
    for (let i3 = starts.length - 1; i3 >= 0; i3 -= 1) {
      const start2 = starts[i3];
      if (start2 == null) continue;
      if (start2 === -1) starts[i3] = 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(normalizeValue2);
    const parts = [];
    const span = (value, autocomplete = false) => /* @__PURE__ */ (0, import_jsx_runtime206.jsx)("span", {
      "data-autocomplete-value": autocomplete ? "" : void 0,
      "data-user-value": autocomplete ? void 0 : "",
      children: value
    }, parts.length);
    const offsets = toOriginalOffsets(itemValue, mergeOverlappingOffsets(getOffsets(normalizeValue2(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, length2], i3) => {
      const value = itemValue.slice(offset4, offset4 + length2);
      const nextOffset = offsets[i3 + 1]?.[0];
      return [value, itemValue.slice(offset4 + length2, nextOffset)];
    })].forEach((value, i3) => {
      if (!value) return;
      parts.push(span(value, i3 % 2 === 0));
    });
    return parts;
  }
  var useComboboxItemValue = createHook(function useComboboxItemValue2({ store: store4, value, userValue, ...props }) {
    const context = useComboboxScopedContext();
    store4 = store4 || context;
    const itemContext = (0, import_react31.useContext)(ComboboxItemValueContext);
    const itemValue = value ?? itemContext;
    const inputValue = useStoreState(store4, (state2) => userValue ?? state2?.value);
    props = {
      children: (0, import_react31.useMemo)(() => {
        if (!itemValue) return;
        if (!inputValue) return itemValue;
        return splitValue(itemValue, inputValue);
      }, [itemValue, inputValue]),
      ...props
    };
    return removeUndefinedValues(props);
  });
  var ComboboxItemValue = forwardRef54(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: store4, ...props }) {
    const context = useComboboxProviderContext();
    store4 = store4 || context;
    invariant(store4, "ComboboxLabel must receive a `store` prop or be wrapped in a ComboboxProvider component.");
    props = {
      htmlFor: useStoreState(store4, (state2) => state2.baseElement?.id),
      ...props
    };
    return removeUndefinedValues(props);
  });
  var ComboboxLabel = memo4(forwardRef54(function ComboboxLabel2(props) {
    return createElement5(TagName12, useComboboxLabel(props));
  }));

  // node_modules/@ariakit/react-components/dist/combobox/combobox-list.js
  var import_react32 = __toESM(require_react(), 1);
  var import_jsx_runtime207 = __toESM(require_jsx_runtime(), 1);
  var TagName13 = "div";
  var useComboboxList = createHook(function useComboboxList2({ store: store4, alwaysVisible, ...props }) {
    const scopedContext = useComboboxScopedContext(true);
    const context = useComboboxContext();
    store4 = store4 || context;
    const scopedContextSameStore = !!store4 && store4 === scopedContext;
    invariant(store4, "ComboboxList must receive a `store` prop or be wrapped in a ComboboxProvider component.");
    const ref = (0, import_react32.useRef)(null);
    const id = useId5(props.id);
    const mounted = useStoreState(store4, "mounted");
    const hidden = isHidden(mounted, props.hidden, alwaysVisible);
    const style = hidden ? {
      ...props.style,
      display: "none"
    } : props.style;
    const multiSelectable = useStoreState(store4, (state2) => Array.isArray(state2.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_react32.useState)(false);
    const contentElement = useStoreState(store4, "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_runtime207.jsx)(ComboboxScopedContextProvider, {
      value: store4,
      children: /* @__PURE__ */ (0, import_jsx_runtime207.jsx)(ComboboxListRoleContext.Provider, {
        value: role,
        children: element
      })
    }), [store4, role]);
    const setContentElement = id && (!scopedContext || !scopedContextSameStore) ? store4.setContentElement : null;
    props = {
      hidden,
      ...props,
      id,
      ref: useMergeRefs2(setContentElement, ref, props.ref),
      style
    };
    return removeUndefinedValues(props);
  });
  var ComboboxList = forwardRef54(function ComboboxList2(props) {
    return createElement5(TagName13, useComboboxList(props));
  });

  // node_modules/@ariakit/react-components/dist/tag/tag-context.js
  var import_react33 = __toESM(require_react(), 1);
  var TagValueContext = (0, import_react33.createContext)(null);
  var TagRemoveIdContext = (0, import_react33.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 store4 = mergeStore(props.store, pick2(tag, ["value", "rtl"]));
    throwOnConflictingProps(props, store4);
    const tagState = tag?.getState();
    const syncState = store4?.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, store4);
    if (isTouchSafari) setup(combobox, () => sync2(combobox, ["virtualFocus"], () => {
      combobox.setState("virtualFocus", false);
    }));
    setup(combobox, () => {
      if (!tag) return;
      return chain(sync2(combobox, ["selectedValue"], (state2) => {
        if (!Array.isArray(state2.selectedValue)) return;
        tag.setValues(state2.selectedValue);
      }), sync2(tag, ["values"], (state2) => {
        combobox.setState("selectedValue", state2.values);
      }));
    });
    setup(combobox, () => sync2(combobox, ["resetValueOnHide", "mounted"], (state2) => {
      if (!state2.resetValueOnHide) return;
      if (state2.mounted) return;
      combobox.setState("value", value);
    }));
    setup(combobox, () => sync2(combobox, ["open"], (state2) => {
      if (state2.open) return;
      combobox.setState("activeId", activeId);
      combobox.setState("moves", 0);
    }));
    setup(combobox, () => sync2(combobox, ["moves", "activeId"], (state2, prevState) => {
      if (state2.moves === prevState.moves) combobox.setState("activeValue", void 0);
    }));
    setup(combobox, () => batch(combobox, ["moves", "renderedItems"], (state2, prev) => {
      if (state2.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(store4, update4, props) {
    useUpdateEffect(update4, [props.tag]);
    useStoreProps(store4, props, "value", "setValue");
    useStoreProps(store4, props, "selectedValue", "setSelectedValue");
    useStoreProps(store4, props, "resetValueOnHide");
    useStoreProps(store4, props, "resetValueOnSelect");
    return Object.assign(useCompositeStoreProps(usePopoverStoreProps(store4, update4, props), update4, props), { tag: props.tag });
  }
  function useComboboxStore(props = {}) {
    props = useComboboxStoreOptions(props);
    const [store4, update4] = useStore2(createComboboxStore, props);
    return useComboboxStoreProps(store4, update4, props);
  }

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

  // packages/dataviews/build-module/components/dataviews-filters/search-widget.mjs
  var import_remove_accents2 = __toESM(require_remove_accents(), 1);
  var import_compose14 = __toESM(require_compose(), 1);
  var import_i18n101 = __toESM(require_i18n(), 1);
  var import_element97 = __toESM(require_element(), 1);
  var import_components45 = __toESM(require_components(), 1);

  // packages/dataviews/build-module/components/dataviews-filters/utils.mjs
  var EMPTY_ARRAY7 = [];
  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_ARRAY7;
  };

  // packages/dataviews/build-module/hooks/use-elements.mjs
  var import_element96 = __toESM(require_element(), 1);
  var EMPTY_ARRAY8 = [];
  function useElements({
    elements: elements2,
    getElements
  }) {
    const staticElements = Array.isArray(elements2) && elements2.length > 0 ? elements2 : EMPTY_ARRAY8;
    const [records, setRecords] = (0, import_element96.useState)(staticElements);
    const [isLoading, setIsLoading] = (0, import_element96.useState)(false);
    (0, import_element96.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_runtime209 = __toESM(require_jsx_runtime(), 1);
  function normalizeSearchInput(input = "") {
    return (0, import_remove_accents2.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((v3) => v3 !== value) : [...currentFilter.value, value];
    }
    return [value];
  };
  function generateFilterElementCompositeItemId(prefix2, filterElementValue) {
    return `${prefix2}-${filterElementValue}`;
  }
  var MultiSelectionOption = ({ selected }) => {
    return /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
      "span",
      {
        className: clsx_default(
          "dataviews-filters__search-widget-listitem-multi-selection",
          { "is-selected": selected }
        ),
        children: selected && /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(import_components45.Icon, { icon: check_default })
      }
    );
  };
  var SingleSelectionOption = ({ selected }) => {
    return /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
      "span",
      {
        className: clsx_default(
          "dataviews-filters__search-widget-listitem-single-selection",
          { "is-selected": selected }
        )
      }
    );
  };
  function ListBox({ view, filter, onChangeView }) {
    const baseId = (0, import_compose14.useInstanceId)(ListBox, "dataviews-filter-list-box");
    const [activeCompositeId, setActiveCompositeId] = (0, import_element97.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(
      (f3) => f3.field === filter.field
    );
    const currentValue = getCurrentValue(filter, currentFilter);
    return /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
      import_components45.Composite,
      {
        virtualFocus: true,
        focusLoop: true,
        activeId: activeCompositeId,
        setActiveId: setActiveCompositeId,
        role: "listbox",
        className: "dataviews-filters__search-widget-listbox",
        "aria-label": (0, import_i18n101.sprintf)(
          /* translators: List of items for a filter. 1: Filter name. e.g.: "List of: Author". */
          (0, import_i18n101.__)("List of: %1$s"),
          filter.name
        ),
        onFocusVisible: () => {
          if (!activeCompositeId && filter.elements.length) {
            setActiveCompositeId(
              generateFilterElementCompositeItemId(
                baseId,
                filter.elements[0].value
              )
            );
          }
        },
        render: /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(import_components45.Composite.Typeahead, {}),
        children: filter.elements.map((element) => /* @__PURE__ */ (0, import_jsx_runtime209.jsxs)(
          import_components45.Composite.Hover,
          {
            render: /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
              import_components45.Composite.Item,
              {
                id: generateFilterElementCompositeItemId(
                  baseId,
                  element.value
                ),
                render: /* @__PURE__ */ (0, import_jsx_runtime209.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_runtime209.jsx)(
                SingleSelectionOption,
                {
                  selected: currentValue === element.value
                }
              ),
              !filter.singleSelection && /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
                MultiSelectionOption,
                {
                  selected: currentValue.includes(element.value)
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime209.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_element97.useState)("");
    const deferredSearchValue = (0, import_element97.useDeferredValue)(searchValue);
    const currentFilter = view.filters?.find(
      (_filter) => _filter.field === filter.field
    );
    const currentValue = getCurrentValue(filter, currentFilter);
    const matches = (0, import_element97.useMemo)(() => {
      const normalizedSearch = normalizeSearchInput(deferredSearchValue);
      return filter.elements.filter(
        (item) => normalizeSearchInput(item.label).includes(normalizedSearch)
      );
    }, [filter.elements, deferredSearchValue]);
    return /* @__PURE__ */ (0, import_jsx_runtime209.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_runtime209.jsxs)("div", { className: "dataviews-filters__search-widget-filter-combobox__wrapper", children: [
            /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(ComboboxLabel, {}), children: (0, import_i18n101.__)("Search items") }),
            /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
              Combobox,
              {
                autoSelect: "always",
                placeholder: (0, import_i18n101.__)("Search"),
                className: "dataviews-filters__search-widget-filter-combobox__input"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime209.jsx)("div", { className: "dataviews-filters__search-widget-filter-combobox__icon", children: /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(import_components45.Icon, { icon: search_default }) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime209.jsxs)(
            ComboboxList,
            {
              className: "dataviews-filters__search-widget-filter-combobox-list",
              alwaysVisible: true,
              children: [
                matches.map((element) => {
                  return /* @__PURE__ */ (0, import_jsx_runtime209.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_runtime209.jsx)(
                          SingleSelectionOption,
                          {
                            selected: currentValue === element.value
                          }
                        ),
                        !filter.singleSelection && /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
                          MultiSelectionOption,
                          {
                            selected: currentValue.includes(
                              element.value
                            )
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime209.jsxs)(
                          "span",
                          {
                            className: "dataviews-filters__search-widget-listitem-value",
                            title: element.label,
                            children: [
                              /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(
                                ComboboxItemValue,
                                {
                                  className: "dataviews-filters__search-widget-filter-combobox-item-value",
                                  value: element.label
                                }
                              ),
                              !!element.description && /* @__PURE__ */ (0, import_jsx_runtime209.jsx)("span", { className: "dataviews-filters__search-widget-listitem-description", children: element.description })
                            ]
                          }
                        )
                      ]
                    },
                    element.value
                  );
                }),
                !matches.length && /* @__PURE__ */ (0, import_jsx_runtime209.jsx)("p", { children: (0, import_i18n101.__)("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_runtime209.jsx)("div", { className: "dataviews-filters__search-widget-no-elements", children: /* @__PURE__ */ (0, import_jsx_runtime209.jsx)(import_components45.Spinner, {}) });
    }
    if (elements2.length === 0) {
      return /* @__PURE__ */ (0, import_jsx_runtime209.jsx)("div", { className: "dataviews-filters__search-widget-no-elements", children: (0, import_i18n101.__)("No elements found") });
    }
    const Widget = elements2.length > 10 ? ComboboxList22 : ListBox;
    return /* @__PURE__ */ (0, import_jsx_runtime209.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_compose15 = __toESM(require_compose(), 1);
  var import_element98 = __toESM(require_element(), 1);
  var import_components46 = __toESM(require_components(), 1);
  var import_jsx_runtime210 = __toESM(require_jsx_runtime(), 1);
  function InputWidget({
    filter,
    view,
    onChangeView,
    fields: fields2
  }) {
    const currentFilter = view.filters?.find(
      (f3) => f3.field === filter.field
    );
    const currentValue = getCurrentValue(filter, currentFilter);
    const field = (0, import_element98.useMemo)(() => {
      const currentField = fields2.find((f3) => f3.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_element98.useMemo)(() => {
      return (view.filters ?? []).reduce(
        (acc, activeFilter) => {
          acc[activeFilter.field] = activeFilter.value;
          return acc;
        },
        {}
      );
    }, [view.filters]);
    const handleChange = (0, import_compose15.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_runtime210.jsx)(
      import_components46.Flex,
      {
        className: "dataviews-filters__user-input-widget",
        gap: 2.5,
        direction: "column",
        children: /* @__PURE__ */ (0, import_jsx_runtime210.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 millisecondsInMinute = 6e4;
  var millisecondsInHour = 36e5;
  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 normalize2 = constructFrom.bind(
      null,
      context || dates.find((date) => typeof date === "object")
    );
    return dates.map(normalize2);
  }

  // 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/endOfMonth.js
  function endOfMonth(date, options) {
    const _date = toDate(date, options?.in);
    const month = _date.getMonth();
    _date.setFullYear(_date.getFullYear(), month + 1, 0);
    _date.setHours(23, 59, 59, 999);
    return _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/parseISO.js
  function parseISO(argument, options) {
    const invalidDate = () => constructFrom(options?.in, NaN);
    const additionalDigits = options?.additionalDigits ?? 2;
    const dateStrings = splitDateString(argument);
    let date;
    if (dateStrings.date) {
      const parseYearResult = parseYear(dateStrings.date, additionalDigits);
      date = parseDate(parseYearResult.restDateString, parseYearResult.year);
    }
    if (!date || isNaN(+date)) return invalidDate();
    const timestamp = +date;
    let time = 0;
    let offset4;
    if (dateStrings.time) {
      time = parseTime(dateStrings.time);
      if (isNaN(time)) return invalidDate();
    }
    if (dateStrings.timezone) {
      offset4 = parseTimezone(dateStrings.timezone);
      if (isNaN(offset4)) return invalidDate();
    } else {
      const tmpDate = new Date(timestamp + time);
      const result = toDate(0, options?.in);
      result.setFullYear(
        tmpDate.getUTCFullYear(),
        tmpDate.getUTCMonth(),
        tmpDate.getUTCDate()
      );
      result.setHours(
        tmpDate.getUTCHours(),
        tmpDate.getUTCMinutes(),
        tmpDate.getUTCSeconds(),
        tmpDate.getUTCMilliseconds()
      );
      return result;
    }
    return toDate(timestamp + time + offset4, options?.in);
  }
  var patterns = {
    dateTimeDelimiter: /[T ]/,
    timeZoneDelimiter: /[Z ]/i,
    timezone: /([Z+-].*)$/
  };
  var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
  var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
  var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
  function splitDateString(dateString) {
    const dateStrings = {};
    const array = dateString.split(patterns.dateTimeDelimiter);
    let timeString;
    if (array.length > 2) {
      return dateStrings;
    }
    if (/:/.test(array[0])) {
      timeString = array[0];
    } else {
      dateStrings.date = array[0];
      timeString = array[1];
      if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
        dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
        timeString = dateString.substr(
          dateStrings.date.length,
          dateString.length
        );
      }
    }
    if (timeString) {
      const token = patterns.timezone.exec(timeString);
      if (token) {
        dateStrings.time = timeString.replace(token[1], "");
        dateStrings.timezone = token[1];
      } else {
        dateStrings.time = timeString;
      }
    }
    return dateStrings;
  }
  function parseYear(dateString, additionalDigits) {
    const regex = new RegExp(
      "^(?:(\\d{4}|[+-]\\d{" + (4 + additionalDigits) + "})|(\\d{2}|[+-]\\d{" + (2 + additionalDigits) + "})$)"
    );
    const captures = dateString.match(regex);
    if (!captures) return { year: NaN, restDateString: "" };
    const year = captures[1] ? parseInt(captures[1]) : null;
    const century = captures[2] ? parseInt(captures[2]) : null;
    return {
      year: century === null ? year : century * 100,
      restDateString: dateString.slice((captures[1] || captures[2]).length)
    };
  }
  function parseDate(dateString, year) {
    if (year === null) return /* @__PURE__ */ new Date(NaN);
    const captures = dateString.match(dateRegex);
    if (!captures) return /* @__PURE__ */ new Date(NaN);
    const isWeekDate = !!captures[4];
    const dayOfYear = parseDateUnit(captures[1]);
    const month = parseDateUnit(captures[2]) - 1;
    const day = parseDateUnit(captures[3]);
    const week = parseDateUnit(captures[4]);
    const dayOfWeek = parseDateUnit(captures[5]) - 1;
    if (isWeekDate) {
      if (!validateWeekDate(year, week, dayOfWeek)) {
        return /* @__PURE__ */ new Date(NaN);
      }
      return dayOfISOWeekYear(year, week, dayOfWeek);
    } else {
      const date = /* @__PURE__ */ new Date(0);
      if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) {
        return /* @__PURE__ */ new Date(NaN);
      }
      date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
      return date;
    }
  }
  function parseDateUnit(value) {
    return value ? parseInt(value) : 1;
  }
  function parseTime(timeString) {
    const captures = timeString.match(timeRegex);
    if (!captures) return NaN;
    const hours = parseTimeUnit(captures[1]);
    const minutes = parseTimeUnit(captures[2]);
    const seconds = parseTimeUnit(captures[3]);
    if (!validateTime(hours, minutes, seconds)) {
      return NaN;
    }
    return hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * 1e3;
  }
  function parseTimeUnit(value) {
    return value && parseFloat(value.replace(",", ".")) || 0;
  }
  function parseTimezone(timezoneString) {
    if (timezoneString === "Z") return 0;
    const captures = timezoneString.match(timezoneRegex);
    if (!captures) return 0;
    const sign = captures[1] === "+" ? -1 : 1;
    const hours = parseInt(captures[2]);
    const minutes = captures[3] && parseInt(captures[3]) || 0;
    if (!validateTimezone(hours, minutes)) {
      return NaN;
    }
    return sign * (hours * millisecondsInHour + minutes * millisecondsInMinute);
  }
  function dayOfISOWeekYear(isoWeekYear, week, day) {
    const date = /* @__PURE__ */ new Date(0);
    date.setUTCFullYear(isoWeekYear, 0, 4);
    const fourthOfJanuaryDay = date.getUTCDay() || 7;
    const diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
    date.setUTCDate(date.getUTCDate() + diff);
    return date;
  }
  var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  function isLeapYearIndex(year) {
    return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
  }
  function validateDate(year, month, date) {
    return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28));
  }
  function validateDayOfYearDate(year, dayOfYear) {
    return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);
  }
  function validateWeekDate(_year, week, day) {
    return week >= 1 && week <= 53 && day >= 0 && day <= 6;
  }
  function validateTime(hours, minutes, seconds) {
    if (hours === 24) {
      return minutes === 0 && seconds === 0;
    }
    return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25;
  }
  function validateTimezone(_hours, minutes) {
    return minutes >= 0 && minutes <= 59;
  }

  // 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_i18n102 = __toESM(require_i18n(), 1);
  var import_element99 = __toESM(require_element(), 1);
  var import_date6 = __toESM(require_date(), 1);
  var import_jsx_runtime211 = __toESM(require_jsx_runtime(), 1);
  var filterTextWrappers = {
    Name: /* @__PURE__ */ (0, import_jsx_runtime211.jsx)("span", { className: "dataviews-filters__summary-filter-text-name" }),
    Value: /* @__PURE__ */ (0, import_jsx_runtime211.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_i18n102.__)("Is none of"),
    filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
      (0, import_i18n102.sprintf)(
        /* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is none of: Admin, Editor". */
        (0, import_i18n102.__)("<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_i18n102.__)("Includes"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is any: Admin, Editor". */
          (0, import_i18n102.__)("<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_NONE,
      ...isNoneOperatorDefinition
    },
    {
      name: OPERATOR_IS_ALL,
      /* translators: DataViews operator name */
      label: (0, import_i18n102.__)("Includes all"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author includes all: Admin, Editor". */
          (0, import_i18n102.__)("<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_i18n102.__)("Between (inc)"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.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_i18n102.__)(
            "<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_i18n102.__)("In the past"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "7 days"): "Date is in the past: 7 days". */
          (0, import_i18n102.__)(
            "<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_date6.getDate)(field.getValue({ item }));
        return fieldValue >= targetDate && fieldValue <= /* @__PURE__ */ new Date();
      },
      selection: "custom"
    },
    {
      name: OPERATOR_OVER,
      /* translators: DataViews operator name */
      label: (0, import_i18n102.__)("Over"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "7 days"): "Date is over: 7 days". */
          (0, import_i18n102.__)("<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_date6.getDate)(field.getValue({ item }));
        return fieldValue < targetDate;
      },
      selection: "custom"
    },
    {
      name: OPERATOR_IS,
      /* translators: DataViews operator name */
      label: (0, import_i18n102.__)("Is"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is: Admin". */
          (0, import_i18n102.__)("<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_i18n102.__)("Is not"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Author"). 2: Filter value (e.g. "Admin"): "Author is not: Admin". */
          (0, import_i18n102.__)("<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_i18n102.__)("Less than"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is less than: 10". */
          (0, import_i18n102.__)("<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_i18n102.__)("Greater than"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is greater than: 10". */
          (0, import_i18n102.__)(
            "<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_i18n102.__)("Less than or equal"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is less than or equal to: 10". */
          (0, import_i18n102.__)(
            "<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_i18n102.__)("Greater than or equal"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Count"). 2: Filter value (e.g. "10"): "Count is greater than or equal to: 10". */
          (0, import_i18n102.__)(
            "<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_BEFORE,
      /* translators: DataViews operator name */
      label: (0, import_i18n102.__)("Before"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is before: 2024-01-01". */
          (0, import_i18n102.__)("<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_date6.getDate)(filterValue);
        const fieldDate = (0, import_date6.getDate)(field.getValue({ item }));
        return fieldDate < filterDate;
      },
      selection: "single"
    },
    {
      name: OPERATOR_AFTER,
      /* translators: DataViews operator name */
      label: (0, import_i18n102.__)("After"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is after: 2024-01-01". */
          (0, import_i18n102.__)("<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_date6.getDate)(filterValue);
        const fieldDate = (0, import_date6.getDate)(field.getValue({ item }));
        return fieldDate > filterDate;
      },
      selection: "single"
    },
    {
      name: OPERATOR_BEFORE_INC,
      /* translators: DataViews operator name */
      label: (0, import_i18n102.__)("Before (inc)"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.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_i18n102.__)(
            "<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_date6.getDate)(filterValue);
        const fieldDate = (0, import_date6.getDate)(field.getValue({ item }));
        return fieldDate <= filterDate;
      },
      selection: "single"
    },
    {
      name: OPERATOR_AFTER_INC,
      /* translators: DataViews operator name */
      label: (0, import_i18n102.__)("After (inc)"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.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_i18n102.__)(
            "<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_date6.getDate)(filterValue);
        const fieldDate = (0, import_date6.getDate)(field.getValue({ item }));
        return fieldDate >= filterDate;
      },
      selection: "single"
    },
    {
      name: OPERATOR_CONTAINS,
      /* translators: DataViews operator name */
      label: (0, import_i18n102.__)("Contains"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title contains: Hello". */
          (0, import_i18n102.__)("<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_i18n102.__)("Doesn't contain"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title doesn't contain: Hello". */
          (0, import_i18n102.__)(
            "<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_i18n102.__)("Starts with"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Title"). 2: Filter value (e.g. "Hello"): "Title starts with: Hello". */
          (0, import_i18n102.__)("<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_i18n102.__)("On"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is: 2024-01-01". */
          (0, import_i18n102.__)("<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_date6.getDate)(filterValue);
        const fieldDate = (0, import_date6.getDate)(field.getValue({ item }));
        return filterDate.getTime() === fieldDate.getTime();
      },
      selection: "single"
    },
    {
      name: OPERATOR_NOT_ON,
      /* translators: DataViews operator name */
      label: (0, import_i18n102.__)("Not on"),
      filterText: (filter, activeElements) => (0, import_element99.createInterpolateElement)(
        (0, import_i18n102.sprintf)(
          /* translators: 1: Filter name (e.g. "Date"). 2: Filter value (e.g. "2024-01-01"): "Date is not: 2024-01-01". */
          (0, import_i18n102.__)("<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_date6.getDate)(filterValue);
        const fieldDate = (0, import_date6.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_runtime212 = __toESM(require_jsx_runtime(), 1);
  var ENTER = "Enter";
  var SPACE = " ";
  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_i18n103.sprintf)(
      /* translators: 1: Filter name e.g.: "Unknown status for Author". */
      (0, import_i18n103.__)("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_runtime212.jsxs)(
      Stack,
      {
        direction: "row",
        gap: "sm",
        justify: "flex-start",
        className: "dataviews-filters__summary-operators-container",
        align: "center",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(import_components47.FlexItem, { className: "dataviews-filters__summary-operators-filter-name", children: filter.name }),
          /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
            import_components47.SelectControl,
            {
              className: "dataviews-filters__summary-operators-filter-select",
              label: (0, import_i18n103.__)("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_element100.useRef)(null);
    const { filter, view, onChangeView } = commonProps;
    const filterInView = view.filters?.find(
      (f3) => f3.field === filter.field
    );
    let activeElements = [];
    const field = (0, import_element100.useMemo)(() => {
      const currentField = fields2.find((f3) => f3.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((v3) => {
        const formattedValue = field?.getValueFormatted({
          item: { [field.id]: v3 },
          field
        });
        return formattedValue || String(v3);
      });
      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_i18n103.__)("Reset") : (0, import_i18n103.__)("Remove");
    return /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
      import_components47.Dropdown,
      {
        defaultOpen: openedFilter === filter.field,
        contentClassName: "dataviews-filters__summary-popover",
        popoverProps: { placement: "bottom-start", role: "dialog" },
        onClose: () => {
          toggleRef.current?.focus();
        },
        renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)("div", { className: "dataviews-filters__summary-chip-container", children: [
          /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(tooltip_exports.Root, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
              tooltip_exports.Trigger,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime212.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 && [ENTER, SPACE].includes(
                        event.key
                      )) {
                        onToggle();
                        event.preventDefault();
                      }
                    },
                    "aria-disabled": isLocked,
                    "aria-pressed": isOpen2,
                    "aria-expanded": isOpen2,
                    ref: toggleRef,
                    children: /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
                      FilterText,
                      {
                        activeElements,
                        filterInView,
                        filter
                      }
                    )
                  }
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(tooltip_exports.Popup, { children: (0, import_i18n103.sprintf)(
              /* translators: 1: Filter name. */
              (0, import_i18n103.__)("Filter by: %1$s"),
              filter.name.toLowerCase()
            ) })
          ] }),
          canResetOrRemove && /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(tooltip_exports.Root, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
              tooltip_exports.Trigger,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime212.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_runtime212.jsx)(import_components47.Icon, { icon: close_small_default })
                  }
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(tooltip_exports.Popup, { children: resetOrRemoveLabel })
          ] })
        ] }),
        renderContent: () => {
          return /* @__PURE__ */ (0, import_jsx_runtime212.jsxs)(Stack, { direction: "column", justify: "flex-start", children: [
            /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(OperatorSelector, { ...commonProps }),
            commonProps.filter.hasElements ? /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(
              SearchWidget,
              {
                ...commonProps,
                filter: {
                  ...commonProps.filter,
                  elements: elements2
                }
              }
            ) : /* @__PURE__ */ (0, import_jsx_runtime212.jsx)(InputWidget, { ...commonProps, fields: fields2 })
          ] });
        }
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-filters/add-filter.mjs
  var import_components48 = __toESM(require_components(), 1);
  var import_i18n104 = __toESM(require_i18n(), 1);
  var import_element101 = __toESM(require_element(), 1);
  var import_jsx_runtime213 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu4 } = unlock5(import_components48.privateApis);
  function AddFilterMenu({
    filters,
    view,
    onChangeView,
    setOpenedFilter,
    triggerProps
  }) {
    const inactiveFilters = filters.filter((filter) => !filter.isVisible);
    return /* @__PURE__ */ (0, import_jsx_runtime213.jsxs)(Menu4, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime213.jsx)(Menu4.TriggerButton, { ...triggerProps }),
      /* @__PURE__ */ (0, import_jsx_runtime213.jsx)(Menu4.Popover, { children: inactiveFilters.map((filter) => {
        return /* @__PURE__ */ (0, import_jsx_runtime213.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_runtime213.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_runtime213.jsx)(
      AddFilterMenu,
      {
        triggerProps: {
          render: /* @__PURE__ */ (0, import_jsx_runtime213.jsx)(
            import_components48.Button,
            {
              accessibleWhenDisabled: true,
              size: "compact",
              className: "dataviews-filters-button",
              variant: "tertiary",
              disabled: !inactiveFilters.length,
              ref
            }
          ),
          children: (0, import_i18n104.__)("Add filter")
        },
        ...{ filters, view, onChangeView, setOpenedFilter }
      }
    );
  }
  var add_filter_default = (0, import_element101.forwardRef)(AddFilter);

  // packages/dataviews/build-module/components/dataviews-filters/reset-filters.mjs
  var import_components49 = __toESM(require_components(), 1);
  var import_i18n105 = __toESM(require_i18n(), 1);
  var import_jsx_runtime214 = __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_runtime214.jsx)(
      import_components49.Button,
      {
        disabled: isDisabled,
        accessibleWhenDisabled: true,
        size: "compact",
        variant: "tertiary",
        className: "dataviews-filters__reset-button",
        onClick: () => {
          onChangeView({
            ...view,
            page: 1,
            search: "",
            filters: view.filters?.filter((f3) => !!f3.isLocked) || []
          });
        },
        children: (0, import_i18n105.__)("Reset")
      }
    );
  }

  // packages/dataviews/build-module/components/dataviews-filters/use-filters.mjs
  var import_element102 = __toESM(require_element(), 1);
  function useFilters(fields2, view) {
    return (0, import_element102.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(
          (f3) => f3.field === field.id && !!f3.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(
            (f3) => f3.field === field.id && isRegisteredOperator(f3.operator)
          ),
          isPrimary,
          isLocked
        });
      });
      filters.sort((a3, b3) => {
        if (a3.isLocked && !b3.isLocked) {
          return -1;
        }
        if (!a3.isLocked && b3.isLocked) {
          return 1;
        }
        if (a3.isPrimary && !b3.isPrimary) {
          return -1;
        }
        if (!a3.isPrimary && b3.isPrimary) {
          return 1;
        }
        return a3.name.localeCompare(b3.name);
      });
      return filters;
    }, [fields2, view]);
  }
  var use_filters_default = useFilters;

  // packages/dataviews/build-module/components/dataviews-filters/filters.mjs
  var import_jsx_runtime215 = __toESM(require_jsx_runtime(), 1);
  function Filters({ className }) {
    const { fields: fields2, view, onChangeView, openedFilter, setOpenedFilter } = (0, import_element103.useContext)(dataviews_context_default);
    const addFilterRef = (0, import_element103.useRef)(null);
    const filters = use_filters_default(fields2, view);
    const addFilter10 = /* @__PURE__ */ (0, import_jsx_runtime215.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_runtime215.jsx)(
          Filter,
          {
            filter,
            view,
            fields: fields2,
            onChangeView,
            addFilterRef,
            openedFilter
          },
          filter.field
        );
      }),
      addFilter10
    ];
    filterComponents.push(
      /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(
        ResetFilter,
        {
          filters,
          view,
          onChangeView
        },
        "reset-filters"
      )
    );
    return /* @__PURE__ */ (0, import_jsx_runtime215.jsx)(
      Stack,
      {
        direction: "row",
        justify: "flex-start",
        gap: "sm",
        style: { width: "fit-content" },
        wrap: "wrap",
        className,
        children: filterComponents
      }
    );
  }
  var filters_default = (0, import_element103.memo)(Filters);

  // packages/dataviews/build-module/components/dataviews-filters/toggle.mjs
  var import_element104 = __toESM(require_element(), 1);
  var import_components50 = __toESM(require_components(), 1);
  var import_i18n106 = __toESM(require_i18n(), 1);
  var import_jsx_runtime216 = __toESM(require_jsx_runtime(), 1);
  function FiltersToggle() {
    const {
      filters,
      view,
      onChangeView,
      setOpenedFilter,
      isShowingFilter,
      setIsShowingFilter
    } = (0, import_element104.useContext)(dataviews_context_default);
    const buttonRef = (0, import_element104.useRef)(null);
    const onChangeViewWithFilterVisibility = (0, import_element104.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_i18n106.__)("Add filter"),
      "aria-expanded": false,
      isPressed: false
    };
    const toggleFiltersButtonProps = {
      label: (0, import_i18n106._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_runtime216.jsx)(
      import_components50.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_runtime216.jsx)("div", { className: "dataviews-filters__container-visibility-toggle", children: !hasVisibleFilters ? /* @__PURE__ */ (0, import_jsx_runtime216.jsx)(
      AddFilterMenu,
      {
        filters,
        view,
        onChangeView: onChangeViewWithFilterVisibility,
        setOpenedFilter,
        triggerProps: { render: buttonComponent }
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime216.jsx)(
      FilterVisibilityToggle,
      {
        buttonRef,
        filtersCount: view.filters?.length,
        children: buttonComponent
      }
    ) });
  }
  function FilterVisibilityToggle({
    buttonRef,
    filtersCount,
    children
  }) {
    (0, import_element104.useEffect)(
      () => () => {
        buttonRef.current?.focus();
      },
      [buttonRef]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime216.jsxs)(import_jsx_runtime216.Fragment, { children: [
      children,
      !!filtersCount && /* @__PURE__ */ (0, import_jsx_runtime216.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_element105 = __toESM(require_element(), 1);
  var import_jsx_runtime217 = __toESM(require_jsx_runtime(), 1);
  function FiltersToggled(props) {
    const { isShowingFilter } = (0, import_element105.useContext)(dataviews_context_default);
    if (!isShowingFilter) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime217.jsx)(filters_default, { ...props });
  }
  var filters_toggled_default = FiltersToggled;

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

  // packages/dataviews/build-module/components/dataviews-search/index.mjs
  var import_i18n108 = __toESM(require_i18n(), 1);
  var import_element107 = __toESM(require_element(), 1);
  var import_components52 = __toESM(require_components(), 1);
  var import_compose16 = __toESM(require_compose(), 1);
  var import_jsx_runtime219 = __toESM(require_jsx_runtime(), 1);
  var DataViewsSearch = (0, import_element107.memo)(function Search({ label }) {
    const { view, onChangeView } = (0, import_element107.useContext)(dataviews_context_default);
    const [search, setSearch, debouncedSearch] = (0, import_compose16.useDebouncedInput)(
      view.search
    );
    (0, import_element107.useEffect)(() => {
      if (view.search !== debouncedSearch) {
        setSearch(view.search ?? "");
      }
    }, [view.search, setSearch]);
    const onChangeViewRef = (0, import_element107.useRef)(onChangeView);
    const viewRef = (0, import_element107.useRef)(view);
    (0, import_element107.useEffect)(() => {
      onChangeViewRef.current = onChangeView;
      viewRef.current = view;
    }, [onChangeView, view]);
    (0, import_element107.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_i18n108.__)("Search");
    return /* @__PURE__ */ (0, import_jsx_runtime219.jsx)(
      import_components52.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_components53 = __toESM(require_components(), 1);
  var import_i18n109 = __toESM(require_i18n(), 1);
  var import_element108 = __toESM(require_element(), 1);
  var import_warning = __toESM(require_warning(), 1);
  var import_compose17 = __toESM(require_compose(), 1);
  var import_jsx_runtime220 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu5 } = unlock5(import_components53.privateApis);
  var DATAVIEWS_CONFIG_POPOVER_PROPS = {
    className: "dataviews-config__popover",
    placement: "bottom-end",
    offset: 9
  };
  function ViewTypeMenu() {
    const { view, onChangeView, defaultLayouts: defaultLayouts2 } = (0, import_element108.useContext)(dataviews_context_default);
    const availableLayouts = Object.keys(defaultLayouts2);
    if (availableLayouts.length <= 1) {
      return null;
    }
    const activeView = VIEW_LAYOUTS.find((v3) => view.type === v3.type);
    return /* @__PURE__ */ (0, import_jsx_runtime220.jsxs)(Menu5, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
        Menu5.TriggerButton,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
            import_components53.Button,
            {
              size: "compact",
              icon: activeView?.icon,
              label: (0, import_i18n109.__)("Layout")
            }
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(Menu5.Popover, { children: availableLayouts.map((layout) => {
        const config2 = VIEW_LAYOUTS.find(
          (v3) => v3.type === layout
        );
        if (!config2) {
          return null;
        }
        return /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
          Menu5.RadioItem,
          {
            value: layout,
            name: "view-actions-available-view",
            checked: layout === view.type,
            hideOnClick: true,
            onChange: (e3) => {
              switch (e3.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: e3.target.value,
                    ...defaultLayouts2[e3.target.value]
                  });
              }
              (0, import_warning.default)("Invalid dataview");
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(Menu5.ItemLabel, { children: config2.label })
          },
          layout
        );
      }) })
    ] });
  }
  function SortFieldControl() {
    const { view, fields: fields2, onChangeView } = (0, import_element108.useContext)(dataviews_context_default);
    const orderOptions = (0, import_element108.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_runtime220.jsx)(
      import_components53.SelectControl,
      {
        label: (0, import_i18n109.__)("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_element108.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_runtime220.jsx)(
      import_components53.__experimentalToggleGroupControl,
      {
        className: "dataviews-view-config__sort-direction",
        isBlock: true,
        label: (0, import_i18n109.__)("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_runtime220.jsx)(
            import_components53.__experimentalToggleGroupControlOptionIcon,
            {
              value: direction,
              icon: sortIcons[direction],
              label: sortLabels[direction]
            },
            direction
          );
        })
      }
    );
  }
  function ItemsPerPageControl() {
    const { view, config: config2, onChangeView } = (0, import_element108.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_runtime220.jsx)(
      import_components53.__experimentalToggleGroupControl,
      {
        isBlock: true,
        label: (0, import_i18n109.__)("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_runtime220.jsx)(
            import_components53.__experimentalToggleGroupControlOption,
            {
              value,
              label: value.toString()
            },
            value
          );
        })
      }
    );
  }
  function ResetViewButton() {
    const { onReset } = (0, import_element108.useContext)(dataviews_context_default);
    if (onReset === void 0) {
      return null;
    }
    const isDisabled = onReset === false;
    return /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
      import_components53.Button,
      {
        variant: "tertiary",
        size: "compact",
        disabled: isDisabled,
        accessibleWhenDisabled: true,
        className: "dataviews-view-config__reset-button",
        onClick: () => {
          if (typeof onReset === "function") {
            onReset();
          }
        },
        children: (0, import_i18n109.__)("Reset view")
      }
    );
  }
  function DataviewsViewConfigDropdown() {
    const { view, onReset } = (0, import_element108.useContext)(dataviews_context_default);
    const popoverId = (0, import_compose17.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_runtime220.jsx)(
      import_components53.Dropdown,
      {
        expandOnMobile: true,
        popoverProps: {
          ...DATAVIEWS_CONFIG_POPOVER_PROPS,
          id: popoverId
        },
        renderToggle: ({ onToggle, isOpen: isOpen2 }) => {
          return /* @__PURE__ */ (0, import_jsx_runtime220.jsxs)("div", { className: "dataviews-view-config__toggle-wrapper", children: [
            /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
              import_components53.Button,
              {
                size: "compact",
                icon: cog_default,
                label: (0, import_i18n109._x)(
                  "View options",
                  "View is used as a noun"
                ),
                onClick: onToggle,
                "aria-expanded": isOpen2 ? "true" : "false",
                "aria-controls": popoverId
              }
            ),
            isModified && /* @__PURE__ */ (0, import_jsx_runtime220.jsx)("span", { className: "dataviews-view-config__modified-indicator" })
          ] });
        },
        renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
          import_components53.__experimentalDropdownContentWrapper,
          {
            paddingSize: "medium",
            className: "dataviews-config__popover-content-wrapper",
            children: /* @__PURE__ */ (0, import_jsx_runtime220.jsxs)(
              Stack,
              {
                direction: "column",
                className: "dataviews-view-config",
                gap: "xl",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime220.jsxs)(
                    Stack,
                    {
                      direction: "row",
                      justify: "space-between",
                      align: "center",
                      className: "dataviews-view-config__header",
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(
                          import_components53.__experimentalHeading,
                          {
                            level: 2,
                            className: "dataviews-settings-section__title",
                            children: (0, import_i18n109.__)("Appearance")
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(ResetViewButton, {})
                      ]
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime220.jsxs)(Stack, { direction: "column", gap: "lg", children: [
                    /* @__PURE__ */ (0, import_jsx_runtime220.jsxs)(
                      Stack,
                      {
                        direction: "row",
                        gap: "sm",
                        className: "dataviews-view-config__sort-controls",
                        children: [
                          /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(SortFieldControl, {}),
                          /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(SortDirectionControl, {})
                        ]
                      }
                    ),
                    !!activeLayout?.viewConfigOptions && /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(activeLayout.viewConfigOptions, {}),
                    /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(ItemsPerPageControl, {}),
                    /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(PropertiesSection, {})
                  ] })
                ]
              }
            )
          }
        )
      }
    );
  }
  function _DataViewsViewConfig() {
    return /* @__PURE__ */ (0, import_jsx_runtime220.jsxs)(import_jsx_runtime220.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(ViewTypeMenu, {}),
      /* @__PURE__ */ (0, import_jsx_runtime220.jsx)(DataviewsViewConfigDropdown, {})
    ] });
  }
  var DataViewsViewConfig = (0, import_element108.memo)(_DataViewsViewConfig);
  var dataviews_view_config_default = DataViewsViewConfig;

  // packages/dataviews/build-module/components/dataform-controls/checkbox.mjs
  var import_components54 = __toESM(require_components(), 1);
  var import_element109 = __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_runtime221 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedCheckboxControl } = unlock5(import_components54.privateApis);
  function Checkbox({
    field,
    onChange,
    data,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { getValue: getValue3, setValue, label, description, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const onChangeControl = (0, import_element109.useCallback)(() => {
      onChange(
        setValue({ item: data, value: !getValue3({ item: data }) })
      );
    }, [data, getValue3, onChange, setValue]);
    return /* @__PURE__ */ (0, import_jsx_runtime221.jsx)(
      ValidatedCheckboxControl,
      {
        required: !!field.isValid?.required,
        markWhenOptional,
        customValidity: getCustomValidity(isValid2, validity),
        hidden: hideLabelFromVision,
        label,
        help: description,
        checked: getValue3({ item: data }),
        onChange: onChangeControl,
        disabled: disabled2
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/combobox.mjs
  var import_components55 = __toESM(require_components(), 1);
  var import_element110 = __toESM(require_element(), 1);
  var import_jsx_runtime222 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedComboboxControl } = unlock5(import_components55.privateApis);
  function Combobox3({
    data,
    field,
    onChange,
    hideLabelFromVision,
    validity
  }) {
    const { label, description, placeholder, getValue: getValue3, setValue, isValid: isValid2 } = field;
    const value = getValue3({ 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_runtime222.jsx)(import_components55.Spinner, {});
    }
    return /* @__PURE__ */ (0, import_jsx_runtime222.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_components57 = __toESM(require_components(), 1);
  var import_element113 = __toESM(require_element(), 1);
  var import_i18n111 = __toESM(require_i18n(), 1);
  var import_date8 = __toESM(require_date(), 1);

  // packages/dataviews/build-module/components/dataform-controls/utils/relative-date-control.mjs
  var import_components56 = __toESM(require_components(), 1);
  var import_element111 = __toESM(require_element(), 1);
  var import_i18n110 = __toESM(require_i18n(), 1);
  var import_jsx_runtime223 = __toESM(require_jsx_runtime(), 1);
  var TIME_UNITS_OPTIONS = {
    [OPERATOR_IN_THE_PAST]: [
      { value: "days", label: (0, import_i18n110.__)("Days") },
      { value: "weeks", label: (0, import_i18n110.__)("Weeks") },
      { value: "months", label: (0, import_i18n110.__)("Months") },
      { value: "years", label: (0, import_i18n110.__)("Years") }
    ],
    [OPERATOR_OVER]: [
      { value: "days", label: (0, import_i18n110.__)("Days ago") },
      { value: "weeks", label: (0, import_i18n110.__)("Weeks ago") },
      { value: "months", label: (0, import_i18n110.__)("Months ago") },
      { value: "years", label: (0, import_i18n110.__)("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: getValue3, setValue } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const fieldValue = getValue3({ item: data });
    const { value: relValue = "", unit = options[0].value } = fieldValue && typeof fieldValue === "object" ? fieldValue : {};
    const onChangeValue = (0, import_element111.useCallback)(
      (newValue) => onChange(
        setValue({
          item: data,
          value: { value: Number(newValue), unit }
        })
      ),
      [onChange, setValue, data, unit]
    );
    const onChangeUnit = (0, import_element111.useCallback)(
      (newUnit) => onChange(
        setValue({
          item: data,
          value: { value: relValue, unit: newUnit }
        })
      ),
      [onChange, setValue, data, relValue]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime223.jsx)(
      import_components56.BaseControl,
      {
        id,
        className: clsx_default(className, "dataviews-controls__relative-date"),
        label,
        hideLabelFromVision,
        help: description,
        children: /* @__PURE__ */ (0, import_jsx_runtime223.jsxs)(Stack, { direction: "row", gap: "sm", children: [
          /* @__PURE__ */ (0, import_jsx_runtime223.jsx)(
            import_components56.__experimentalNumberControl,
            {
              className: "dataviews-controls__relative-date-number",
              spinControls: "none",
              min: 1,
              step: 1,
              value: relValue,
              onChange: onChangeValue,
              disabled: disabled2
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime223.jsx)(
            import_components56.SelectControl,
            {
              className: "dataviews-controls__relative-date-unit",
              label: (0, import_i18n110.__)("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_element112 = __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_element112.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_date7 = __toESM(require_date(), 1);
  function parseDateTime(dateTimeString) {
    if (!dateTimeString) {
      return null;
    }
    const parsed = (0, import_date7.getDate)(dateTimeString);
    return parsed && isValid(parsed) ? parsed : null;
  }

  // packages/dataviews/build-module/components/dataform-controls/datetime.mjs
  var import_jsx_runtime224 = __toESM(require_jsx_runtime(), 1);
  var { DateCalendar, ValidatedInputControl } = unlock5(import_components57.privateApis);
  var formatDateTime = (value) => {
    if (!value) {
      return "";
    }
    return (0, import_date8.dateI18n)("Y-m-d\\TH:i", (0, import_date8.getDate)(value));
  };
  function CalendarDateTimeControl({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity,
    config: config2
  }) {
    const { compact } = config2 || {};
    const { id, label, description, setValue, getValue: getValue3, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const fieldValue = getValue3({ item: data });
    const value = typeof fieldValue === "string" ? fieldValue : void 0;
    const [calendarMonth, setCalendarMonth] = (0, import_element113.useState)(() => {
      const parsedDate = parseDateTime(value);
      return parsedDate || /* @__PURE__ */ new Date();
    });
    const inputControlRef = (0, import_element113.useRef)(null);
    const validationTimeoutRef = (0, import_element113.useRef)(void 0);
    const previousFocusRef = (0, import_element113.useRef)(null);
    const { minConstraint, maxConstraint, disabledMatchers } = useDisabledDateMatchers(isValid2, parseDateTime);
    const onChangeCallback = (0, import_element113.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    (0, import_element113.useEffect)(() => {
      return () => {
        if (validationTimeoutRef.current) {
          clearTimeout(validationTimeoutRef.current);
        }
      };
    }, []);
    const onSelectDate = (0, import_element113.useCallback)(
      (newDate) => {
        let dateTimeValue;
        if (newDate) {
          const wpDate = (0, import_date8.dateI18n)("Y-m-d", newDate);
          let wpTime;
          if (value) {
            wpTime = (0, import_date8.dateI18n)("H:i", (0, import_date8.getDate)(value));
          } else {
            wpTime = (0, import_date8.dateI18n)("H:i", newDate);
          }
          const finalDateTime = (0, import_date8.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_element113.useCallback)(
      (newValue) => {
        if (newValue) {
          const dateTime = (0, import_date8.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_date8.getSettings)().l10n.startOfWeek;
    const {
      timezone: { string: timezoneString }
    } = (0, import_date8.getSettings)();
    let displayLabel = label;
    if (isValid2?.required && !markWhenOptional && !hideLabelFromVision) {
      displayLabel = `${label} (${(0, import_i18n111.__)("Required")})`;
    } else if (!isValid2?.required && markWhenOptional && !hideLabelFromVision) {
      displayLabel = `${label} (${(0, import_i18n111.__)("Optional")})`;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime224.jsx)(
      import_components57.BaseControl,
      {
        id,
        label: displayLabel,
        help: description,
        hideLabelFromVision,
        children: /* @__PURE__ */ (0, import_jsx_runtime224.jsxs)(Stack, { direction: "column", gap: "lg", children: [
          /* @__PURE__ */ (0, import_jsx_runtime224.jsx)(
            ValidatedInputControl,
            {
              ref: inputControlRef,
              required: !!isValid2?.required,
              customValidity: getCustomValidity(isValid2, validity),
              type: "datetime-local",
              label: (0, import_i18n111.__)("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_runtime224.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_runtime224.jsx)(
        RelativeDateControl,
        {
          className: "dataviews-controls__datetime",
          data,
          field,
          onChange,
          hideLabelFromVision,
          operator
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime224.jsx)(
      CalendarDateTimeControl,
      {
        data,
        field,
        onChange,
        hideLabelFromVision,
        markWhenOptional,
        validity,
        config: config2
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/date.mjs
  var import_components58 = __toESM(require_components(), 1);
  var import_a11y3 = __toESM(require_a11y(), 1);
  var import_element114 = __toESM(require_element(), 1);
  var import_i18n112 = __toESM(require_i18n(), 1);
  var import_date9 = __toESM(require_date(), 1);
  var import_jsx_runtime225 = __toESM(require_jsx_runtime(), 1);
  var { DateCalendar: DateCalendar2, DateRangeCalendar } = unlock5(import_components58.privateApis);
  var DATE_PRESETS = [
    {
      id: "today",
      label: (0, import_i18n112.__)("Today"),
      getValue: () => (0, import_date9.getDate)(null)
    },
    {
      id: "yesterday",
      label: (0, import_i18n112.__)("Yesterday"),
      getValue: () => {
        const today = (0, import_date9.getDate)(null);
        return subDays(today, 1);
      }
    },
    {
      id: "past-week",
      label: (0, import_i18n112.__)("Past week"),
      getValue: () => {
        const today = (0, import_date9.getDate)(null);
        return subDays(today, 7);
      }
    },
    {
      id: "past-month",
      label: (0, import_i18n112.__)("Past month"),
      getValue: () => {
        const today = (0, import_date9.getDate)(null);
        return subMonths(today, 1);
      }
    }
  ];
  var DATE_RANGE_PRESETS = [
    {
      id: "last-7-days",
      label: (0, import_i18n112.__)("Last 7 days"),
      getValue: () => {
        const today = (0, import_date9.getDate)(null);
        return [subDays(today, 7), today];
      }
    },
    {
      id: "last-30-days",
      label: (0, import_i18n112.__)("Last 30 days"),
      getValue: () => {
        const today = (0, import_date9.getDate)(null);
        return [subDays(today, 30), today];
      }
    },
    {
      id: "month-to-date",
      label: (0, import_i18n112.__)("Month to date"),
      getValue: () => {
        const today = (0, import_date9.getDate)(null);
        return [startOfMonth(today), today];
      }
    },
    {
      id: "last-year",
      label: (0, import_i18n112.__)("Last year"),
      getValue: () => {
        const today = (0, import_date9.getDate)(null);
        return [subYears(today, 1), today];
      }
    },
    {
      id: "year-to-date",
      label: (0, import_i18n112.__)("Year to date"),
      getValue: () => {
        const today = (0, import_date9.getDate)(null);
        return [startOfYear(today), today];
      }
    }
  ];
  var parseDate2 = (dateString) => {
    if (!dateString) {
      return null;
    }
    const parsed = (0, import_date9.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_element114.useState)(void 0);
    const validateRefs = (0, import_element114.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_element114.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_element114.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_element114.useEffect)(() => {
      if (!isTouched) {
        return;
      }
      const result = validity ? getCustomValidity(isValid2, validity) : void 0;
      if (result) {
        setCustomValidity(result);
      } else {
        validateRefs();
      }
    }, [isTouched, isValid2, validity, validateRefs]);
    (0, import_element114.useEffect)(() => {
      if (isTouched && customValidity?.message) {
        (0, import_a11y3.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_runtime225.jsxs)("div", { onBlur, children: [
      children,
      customValidity && /* @__PURE__ */ (0, import_jsx_runtime225.jsxs)(
        "p",
        {
          className: clsx_default(
            "components-validated-control__indicator",
            customValidity.type === "invalid" ? "is-invalid" : void 0
          ),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
              import_components58.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: getValue3,
      isValid: isValid2,
      format: fieldFormat
    } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const [selectedPresetId, setSelectedPresetId] = (0, import_element114.useState)(
      null
    );
    const weekStartsOn = fieldFormat.weekStartsOn ?? (0, import_date9.getSettings)().l10n.startOfWeek;
    const fieldValue = getValue3({ item: data });
    const value = typeof fieldValue === "string" ? fieldValue : void 0;
    const [calendarMonth, setCalendarMonth] = (0, import_element114.useState)(() => {
      const parsedDate = parseDate2(value);
      return parsedDate || /* @__PURE__ */ new Date();
    });
    const [isTouched, setIsTouched] = (0, import_element114.useState)(false);
    const validityTargetRef = (0, import_element114.useRef)(null);
    const { minConstraint, maxConstraint, disabledMatchers } = useDisabledDateMatchers(isValid2, parseDate2);
    const onChangeCallback = (0, import_element114.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    const onSelectDate = (0, import_element114.useCallback)(
      (newDate) => {
        const dateValue = newDate ? format(newDate, "yyyy-MM-dd") : void 0;
        onChangeCallback(dateValue);
        setSelectedPresetId(null);
        setIsTouched(true);
      },
      [onChangeCallback]
    );
    const handlePresetClick = (0, import_element114.useCallback)(
      (preset) => {
        const presetDate = preset.getValue();
        const dateValue = formatDate(presetDate);
        setCalendarMonth(presetDate);
        onChangeCallback(dateValue);
        setSelectedPresetId(preset.id);
        setIsTouched(true);
      },
      [onChangeCallback]
    );
    const handleManualDateChange = (0, import_element114.useCallback)(
      (newValue) => {
        onChangeCallback(newValue);
        if (newValue) {
          const parsedDate = parseDate2(newValue);
          if (parsedDate) {
            setCalendarMonth(parsedDate);
          }
        }
        setSelectedPresetId(null);
        setIsTouched(true);
      },
      [onChangeCallback]
    );
    const {
      timezone: { string: timezoneString }
    } = (0, import_date9.getSettings)();
    let displayLabel = label;
    if (isValid2?.required && !markWhenOptional) {
      displayLabel = `${label} (${(0, import_i18n112.__)("Required")})`;
    } else if (!isValid2?.required && markWhenOptional) {
      displayLabel = `${label} (${(0, import_i18n112.__)("Optional")})`;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
      ValidatedDateControl,
      {
        field,
        validity,
        inputRefs: validityTargetRef,
        isTouched,
        setIsTouched,
        children: /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
          import_components58.BaseControl,
          {
            id,
            className: "dataviews-controls__date",
            label: displayLabel,
            help: description,
            hideLabelFromVision,
            children: /* @__PURE__ */ (0, import_jsx_runtime225.jsxs)(Stack, { direction: "column", gap: "lg", children: [
              /* @__PURE__ */ (0, import_jsx_runtime225.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_runtime225.jsx)(
                        import_components58.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_runtime225.jsx)(
                      import_components58.Button,
                      {
                        className: "dataviews-controls__date-preset",
                        variant: "tertiary",
                        isPressed: !selectedPresetId,
                        size: "small",
                        disabled: !!selectedPresetId || disabled2,
                        accessibleWhenDisabled: true,
                        children: (0, import_i18n112.__)("Custom")
                      }
                    )
                  ]
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
                import_components58.__experimentalInputControl,
                {
                  ref: validityTargetRef,
                  type: "date",
                  label: (0, import_i18n112.__)("Date"),
                  hideLabelFromVision: true,
                  value,
                  onChange: handleManualDateChange,
                  required: !!field.isValid?.required,
                  disabled: disabled2,
                  min: minConstraint,
                  max: maxConstraint
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
                DateCalendar2,
                {
                  style: { width: "100%" },
                  selected: value ? parseDate2(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: getValue3,
      setValue,
      isValid: isValid2,
      format: fieldFormat
    } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    let value;
    const fieldValue = getValue3({ item: data });
    if (Array.isArray(fieldValue) && fieldValue.length === 2 && fieldValue.every((date) => typeof date === "string")) {
      value = fieldValue;
    }
    const weekStartsOn = fieldFormat.weekStartsOn ?? (0, import_date9.getSettings)().l10n.startOfWeek;
    const { minConstraint, maxConstraint, disabledMatchers } = useDisabledDateMatchers(isValid2, parseDate2);
    const onChangeCallback = (0, import_element114.useCallback)(
      (newValue) => {
        onChange(
          setValue({
            item: data,
            value: newValue
          })
        );
      },
      [data, onChange, setValue]
    );
    const [selectedPresetId, setSelectedPresetId] = (0, import_element114.useState)(
      null
    );
    const selectedRange = (0, import_element114.useMemo)(() => {
      if (!value) {
        return { from: void 0, to: void 0 };
      }
      const [from, to2] = value;
      return {
        from: parseDate2(from) || void 0,
        to: parseDate2(to2) || void 0
      };
    }, [value]);
    const [calendarMonth, setCalendarMonth] = (0, import_element114.useState)(() => {
      return selectedRange.from || /* @__PURE__ */ new Date();
    });
    const [isTouched, setIsTouched] = (0, import_element114.useState)(false);
    const fromInputRef = (0, import_element114.useRef)(null);
    const toInputRef = (0, import_element114.useRef)(null);
    const updateDateRange = (0, import_element114.useCallback)(
      (fromDate, toDate2) => {
        if (fromDate && toDate2) {
          onChangeCallback([
            formatDate(fromDate),
            formatDate(toDate2)
          ]);
        } else if (!fromDate && !toDate2) {
          onChangeCallback(void 0);
        }
      },
      [onChangeCallback]
    );
    const onSelectCalendarRange = (0, import_element114.useCallback)(
      (newRange) => {
        updateDateRange(newRange?.from, newRange?.to);
        setSelectedPresetId(null);
        setIsTouched(true);
      },
      [updateDateRange]
    );
    const handlePresetClick = (0, import_element114.useCallback)(
      (preset) => {
        const [startDate2, endDate] = preset.getValue();
        setCalendarMonth(startDate2);
        updateDateRange(startDate2, endDate);
        setSelectedPresetId(preset.id);
        setIsTouched(true);
      },
      [updateDateRange]
    );
    const handleManualDateChange = (0, import_element114.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 = parseDate2(newValue);
          if (parsedDate) {
            setCalendarMonth(parsedDate);
          }
        }
        setSelectedPresetId(null);
        setIsTouched(true);
      },
      [value, updateDateRange]
    );
    const { timezone } = (0, import_date9.getSettings)();
    let displayLabel = label;
    if (field.isValid?.required && !markWhenOptional) {
      displayLabel = `${label} (${(0, import_i18n112.__)("Required")})`;
    } else if (!field.isValid?.required && markWhenOptional) {
      displayLabel = `${label} (${(0, import_i18n112.__)("Optional")})`;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
      ValidatedDateControl,
      {
        field,
        validity,
        inputRefs: [fromInputRef, toInputRef],
        isTouched,
        setIsTouched,
        children: /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
          import_components58.BaseControl,
          {
            id,
            className: "dataviews-controls__date",
            label: displayLabel,
            help: description,
            hideLabelFromVision,
            children: /* @__PURE__ */ (0, import_jsx_runtime225.jsxs)(Stack, { direction: "column", gap: "lg", children: [
              /* @__PURE__ */ (0, import_jsx_runtime225.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_runtime225.jsx)(
                        import_components58.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_runtime225.jsx)(
                      import_components58.Button,
                      {
                        className: "dataviews-controls__date-preset",
                        variant: "tertiary",
                        isPressed: !selectedPresetId,
                        size: "small",
                        accessibleWhenDisabled: true,
                        disabled: !!selectedPresetId || disabled2,
                        children: (0, import_i18n112.__)("Custom")
                      }
                    )
                  ]
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime225.jsxs)(
                Stack,
                {
                  direction: "row",
                  gap: "sm",
                  justify: "space-between",
                  className: "dataviews-controls__date-range-inputs",
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
                      import_components58.__experimentalInputControl,
                      {
                        ref: fromInputRef,
                        type: "date",
                        label: (0, import_i18n112.__)("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_runtime225.jsx)(
                      import_components58.__experimentalInputControl,
                      {
                        ref: toInputRef,
                        type: "date",
                        label: (0, import_i18n112.__)("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_runtime225.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_runtime225.jsx)(
        RelativeDateControl,
        {
          className: "dataviews-controls__date",
          data,
          field,
          onChange,
          hideLabelFromVision,
          operator
        }
      );
    }
    if (operator === OPERATOR_BETWEEN) {
      return /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
        CalendarDateRangeControl,
        {
          data,
          field,
          onChange,
          hideLabelFromVision,
          markWhenOptional,
          validity
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime225.jsx)(
      CalendarDateControl,
      {
        data,
        field,
        onChange,
        hideLabelFromVision,
        markWhenOptional,
        validity
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/select.mjs
  var import_components59 = __toESM(require_components(), 1);
  var import_element115 = __toESM(require_element(), 1);
  var import_jsx_runtime226 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedSelectControl } = unlock5(import_components59.privateApis);
  function Select({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { type, label, description, getValue: getValue3, setValue, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const isMultiple = type === "array";
    const value = getValue3({ item: data }) ?? (isMultiple ? [] : "");
    const onChangeControl = (0, import_element115.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_runtime226.jsx)(import_components59.Spinner, {});
    }
    return /* @__PURE__ */ (0, import_jsx_runtime226.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_runtime227 = __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_runtime227.jsx)(Combobox3, { ...props });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime227.jsx)(Select, { ...props });
  }

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

  // packages/dataviews/build-module/components/dataform-controls/utils/validated-input.mjs
  var import_components60 = __toESM(require_components(), 1);
  var import_element116 = __toESM(require_element(), 1);
  var import_jsx_runtime228 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedInputControl: ValidatedInputControl2 } = unlock5(import_components60.privateApis);
  function ValidatedText({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    type,
    prefix: prefix2,
    suffix,
    validity
  }) {
    const { label, placeholder, description, getValue: getValue3, setValue, isValid: isValid2 } = field;
    const value = getValue3({ item: data });
    const disabled2 = field.isDisabled({ item: data, field });
    const onChangeControl = (0, import_element116.useCallback)(
      (newValue) => onChange(
        setValue({
          item: data,
          value: newValue
        })
      ),
      [data, setValue, onChange]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime228.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_runtime229 = __toESM(require_jsx_runtime(), 1);
  function Email({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(
      ValidatedText,
      {
        ...{
          data,
          field,
          onChange,
          hideLabelFromVision,
          markWhenOptional,
          validity,
          type: "email",
          prefix: /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(import_components61.__experimentalInputControlPrefixWrapper, { variant: "icon", children: /* @__PURE__ */ (0, import_jsx_runtime229.jsx)(import_components61.Icon, { icon: envelope_default }) })
        }
      }
    );
  }

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

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

  // packages/dataviews/build-module/components/dataform-controls/utils/validated-number.mjs
  var import_components64 = __toESM(require_components(), 1);
  var import_element117 = __toESM(require_element(), 1);
  var import_i18n113 = __toESM(require_i18n(), 1);
  var import_jsx_runtime232 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedNumberControl } = unlock5(import_components64.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 [min3 = "", max3 = ""] = value;
    const onChangeMin = (0, import_element117.useCallback)(
      (newValue) => onChange([toNumberOrEmpty(newValue), max3]),
      [onChange, max3]
    );
    const onChangeMax = (0, import_element117.useCallback)(
      (newValue) => onChange([min3, toNumberOrEmpty(newValue)]),
      [onChange, min3]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime232.jsx)(
      import_components64.BaseControl,
      {
        help: (0, import_i18n113.__)("The max. value must be greater than the min. value."),
        children: /* @__PURE__ */ (0, import_jsx_runtime232.jsxs)(import_components64.Flex, { direction: "row", gap: 4, children: [
          /* @__PURE__ */ (0, import_jsx_runtime232.jsx)(
            import_components64.__experimentalNumberControl,
            {
              label: (0, import_i18n113.__)("Min."),
              value: min3,
              max: max3 ? Number(max3) - step : void 0,
              onChange: onChangeMin,
              hideLabelFromVision,
              step
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime232.jsx)(
            import_components64.__experimentalNumberControl,
            {
              label: (0, import_i18n113.__)("Max."),
              value: max3,
              min: min3 ? Number(min3) + 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: getValue3, setValue, isValid: isValid2 } = field;
    const value = getValue3({ item: data }) ?? "";
    const disabled2 = field.isDisabled({ item: data, field });
    const onChangeControl = (0, import_element117.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_element117.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_runtime232.jsx)(
        BetweenControls,
        {
          value: valueBetween,
          onChange: onChangeBetweenControls,
          hideLabelFromVision,
          step
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime232.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_runtime233 = __toESM(require_jsx_runtime(), 1);
  function Integer(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime233.jsx)(ValidatedNumber, { ...props });
  }

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

  // packages/dataviews/build-module/components/dataform-controls/radio.mjs
  var import_components65 = __toESM(require_components(), 1);
  var import_element118 = __toESM(require_element(), 1);
  var import_jsx_runtime235 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedRadioControl } = unlock5(import_components65.privateApis);
  function Radio({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { label, description, getValue: getValue3, setValue, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const { elements: elements2, isLoading } = useElements({
      elements: field.elements,
      getElements: field.getElements
    });
    const value = getValue3({ item: data });
    const onChangeControl = (0, import_element118.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime235.jsx)(import_components65.Spinner, {});
    }
    return /* @__PURE__ */ (0, import_jsx_runtime235.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_element119 = __toESM(require_element(), 1);
  var import_jsx_runtime236 = __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_runtime236.jsx)(
      ValidatedText,
      {
        ...{
          data,
          field,
          onChange,
          hideLabelFromVision,
          markWhenOptional,
          validity,
          prefix: prefix2 ? (0, import_element119.createElement)(prefix2) : void 0,
          suffix: suffix ? (0, import_element119.createElement)(suffix) : void 0
        }
      }
    );
  }

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

  // packages/dataviews/build-module/components/dataform-controls/textarea.mjs
  var import_components67 = __toESM(require_components(), 1);
  var import_element121 = __toESM(require_element(), 1);
  var import_jsx_runtime238 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedTextareaControl } = unlock5(import_components67.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_element121.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime238.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_element123 = __toESM(require_element(), 1);

  // packages/dataviews/build-module/components/dataform-controls/richtext/control.mjs
  var import_components68 = __toESM(require_components(), 1);
  var import_compose18 = __toESM(require_compose(), 1);
  var import_element122 = __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_ARRAY9 = [];
  function getAllowedFormats({
    allowedFormats,
    disableFormats
  }) {
    if (disableFormats) {
      return EMPTY_ARRAY9;
    }
    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_runtime239 = __toESM(require_jsx_runtime(), 1);
  var import_react34 = __toESM(require_react(), 1);
  var EMPTY_CONTEXT = {};
  function Edit({
    onChange,
    onFocus,
    value,
    forwardedRef,
    settings,
    isVisible: isVisible2
  }) {
    const { name: name2, edit: EditFunction } = settings;
    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_runtime239.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((settings) => /* @__PURE__ */ (0, import_react34.createElement)(Edit, { settings, ...props, key: settings.name }));
  }

  // packages/dataviews/build-module/components/dataform-controls/richtext/control.mjs
  var import_jsx_runtime240 = __toESM(require_jsx_runtime(), 1);
  var {
    ValidatedContentEditableControl: RichTextControlShell,
    withIgnoreIMEEvents
  } = unlock5(import_components68.privateApis);
  var {
    useRichText,
    KeyboardShortcutContext,
    InputEventContext,
    shortcutsListener,
    inputEventsListener
  } = unlock5(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_element122.useState)({
      start: void 0,
      end: void 0
    });
    const [isSelected2, setIsSelected] = (0, import_element122.useState)(false);
    const anchorRef = (0, import_element122.useRef)(void 0);
    const inputEvents = (0, import_element122.useRef)(/* @__PURE__ */ new Set());
    const keyboardShortcuts = (0, import_element122.useRef)(
      /* @__PURE__ */ new Set()
    );
    const focusOutside = (0, import_compose18.__experimentalUseFocusOutside)(() => setIsSelected(false));
    const adjustedAllowedFormats = getAllowedFormats({
      allowedFormats,
      disableFormats
    });
    const {
      value,
      onChange: onRichTextChange,
      ref: richTextRef,
      formatTypes,
      getValue: getValue3
    } = 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_element122.useMemo)(
        () => ({
          richTextIdentifier: id,
          blockClientId: clientId
        }),
        [id, clientId]
      )
    });
    function onFocus() {
      anchorRef.current?.focus();
    }
    const eventListenersPropsRef = (0, import_element122.useRef)({
      keyboardShortcuts,
      inputEvents
    });
    const inputRulePropsRef = (0, import_element122.useRef)({
      formatTypes,
      getValue: getValue3,
      onChange: onRichTextChange
    });
    (0, import_element122.useInsertionEffect)(() => {
      inputRulePropsRef.current = {
        formatTypes,
        getValue: getValue3,
        onChange: onRichTextChange
      };
    });
    const enterRef = (0, import_compose18.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_compose18.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_components68.__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_compose18.useRefEffect)(
      (element) => {
        if (focusOnMount && !disabled2) {
          element.focus();
        }
      },
      [focusOnMount, disabled2]
    );
    const editableRef = (0, import_compose18.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_runtime240.jsx)(
        "div",
        {
          ...focusOutside,
          onFocus: (event) => {
            setIsSelected(true);
            focusOutside.onFocus(event);
          },
          children: /* @__PURE__ */ (0, import_jsx_runtime240.jsxs)(import_components68.SlotFillProvider, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime240.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_runtime240.jsx)(
              KeyboardShortcutContext.Provider,
              {
                value: keyboardShortcuts,
                children: /* @__PURE__ */ (0, import_jsx_runtime240.jsx)(InputEventContext.Provider, { value: inputEvents, children: /* @__PURE__ */ (0, import_jsx_runtime240.jsx)(
                  FormatEdit,
                  {
                    value,
                    onChange: onRichTextChange,
                    onFocus,
                    formatTypes,
                    forwardedRef: anchorRef,
                    isVisible: true
                  }
                ) })
              }
            )
          ] })
        }
      )
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/richtext/index.mjs
  var import_jsx_runtime241 = __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_element123.useCallback)(
      (newValue) => onChange(setValue({ item: data, value: newValue })),
      [data, onChange, setValue]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime241.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_components69 = __toESM(require_components(), 1);
  var import_element124 = __toESM(require_element(), 1);
  var import_jsx_runtime242 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedToggleGroupControl } = unlock5(import_components69.privateApis);
  function ToggleGroup({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { getValue: getValue3, setValue, isValid: isValid2 } = field;
    const disabled2 = field.isDisabled({ item: data, field });
    const value = getValue3({ item: data });
    const onChangeControl = (0, import_element124.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_runtime242.jsx)(import_components69.Spinner, {});
    }
    if (elements2.length === 0) {
      return null;
    }
    const selectedOption = elements2.find((el) => el.value === value);
    return /* @__PURE__ */ (0, import_jsx_runtime242.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_runtime242.jsx)(
          import_components69.__experimentalToggleGroupControlOption,
          {
            label: el.label,
            value: el.value,
            disabled: disabled2
          },
          el.value
        ))
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/array.mjs
  var import_components70 = __toESM(require_components(), 1);
  var import_element125 = __toESM(require_element(), 1);
  var import_jsx_runtime243 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedFormTokenField } = unlock5(import_components70.privateApis);
  function ArrayControl({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { label, placeholder, description, getValue: getValue3, setValue, isValid: isValid2 } = field;
    const value = getValue3({ item: data });
    const disabled2 = field.isDisabled({ item: data, field });
    const { elements: elements2, isLoading } = useElements({
      elements: field.elements,
      getElements: field.getElements
    });
    const arrayValueAsElements = (0, import_element125.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_element125.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_runtime243.jsx)(import_components70.Spinner, {});
    }
    return /* @__PURE__ */ (0, import_jsx_runtime243.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_runtime243.jsx)("span", { children: element?.label || item });
          }
          return /* @__PURE__ */ (0, import_jsx_runtime243.jsx)("span", { children: item });
        }
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/color.mjs
  var import_components71 = __toESM(require_components(), 1);
  var import_element126 = __toESM(require_element(), 1);
  var import_i18n114 = __toESM(require_i18n(), 1);
  var import_jsx_runtime244 = __toESM(require_jsx_runtime(), 1);
  var { ValidatedInputControl: ValidatedInputControl3 } = unlock5(import_components71.privateApis);
  var ColorPickerDropdown = ({
    color,
    onColorChange,
    disabled: disabled2
  }) => {
    const validColor = color && w(color).isValid() ? color : "#ffffff";
    return /* @__PURE__ */ (0, import_jsx_runtime244.jsx)(
      import_components71.Dropdown,
      {
        className: "dataviews-controls__color-picker-dropdown",
        popoverProps: { resize: false },
        renderToggle: ({ onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime244.jsx)(
          import_components71.Button,
          {
            onClick: onToggle,
            "aria-label": (0, import_i18n114.__)("Open color picker"),
            size: "small",
            disabled: disabled2,
            accessibleWhenDisabled: true,
            icon: () => /* @__PURE__ */ (0, import_jsx_runtime244.jsx)(import_components71.ColorIndicator, { colorValue: validColor })
          }
        ),
        renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime244.jsx)(import_components71.__experimentalDropdownContentWrapper, { paddingSize: "none", children: /* @__PURE__ */ (0, import_jsx_runtime244.jsx)(
          import_components71.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_element126.useCallback)(
      (newColor) => {
        onChange(setValue({ item: data, value: newColor }));
      },
      [data, onChange, setValue]
    );
    const handleInputChange = (0, import_element126.useCallback)(
      (newValue) => {
        onChange(setValue({ item: data, value: newValue || "" }));
      },
      [data, onChange, setValue]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime244.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_runtime244.jsx)(import_components71.__experimentalInputControlPrefixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime244.jsx)(
          ColorPickerDropdown,
          {
            color: value,
            onColorChange: handleColorChange,
            disabled: disabled2
          }
        ) })
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-controls/password.mjs
  var import_components72 = __toESM(require_components(), 1);
  var import_element127 = __toESM(require_element(), 1);
  var import_i18n115 = __toESM(require_i18n(), 1);
  var import_jsx_runtime245 = __toESM(require_jsx_runtime(), 1);
  function Password({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const [isVisible2, setIsVisible] = (0, import_element127.useState)(false);
    const disabled2 = field.isDisabled({ item: data, field });
    const toggleVisibility = (0, import_element127.useCallback)(() => {
      setIsVisible((prev) => !prev);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime245.jsx)(
      ValidatedText,
      {
        ...{
          data,
          field,
          onChange,
          hideLabelFromVision,
          markWhenOptional,
          validity,
          type: isVisible2 ? "text" : "password",
          suffix: /* @__PURE__ */ (0, import_jsx_runtime245.jsx)(import_components72.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime245.jsx)(
            import_components72.Button,
            {
              icon: isVisible2 ? unseen_default : seen_default,
              onClick: toggleVisibility,
              size: "small",
              label: isVisible2 ? (0, import_i18n115.__)("Hide password") : (0, import_i18n115.__)("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_runtime246 = __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_runtime246.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 segment2 of path) {
      if (value.hasOwnProperty(segment2)) {
        value = value[segment2];
      } 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 segment2 of path.slice(0, -1)) {
      current[segment2] = {};
      current = current[segment2];
    }
    current[path.at(-1)] = value;
    return result;
  };
  var set_value_from_id_default = setValueFromId;

  // packages/dataviews/build-module/field-types/email.mjs
  var import_i18n116 = __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_runtime247 = __toESM(require_jsx_runtime(), 1);
  function render2({
    item,
    field
  }) {
    if (field.hasElements) {
      return /* @__PURE__ */ (0, import_jsx_runtime247.jsx)(RenderFromElements, { item, field });
    }
    return field.getValueFormatted({ item, field });
  }

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

  // 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((v3) => validValues.includes(v3));
  }

  // 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_i18n116.__)("Value must be a valid email address.");
    }
    return null;
  }
  var email_default = {
    type: "email",
    render: render2,
    Edit: "email",
    sort: sort_text_default,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE],
    validOperators: [
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_CONTAINS,
      OPERATOR_NOT_CONTAINS,
      OPERATOR_STARTS_WITH,
      // Multiple selection
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE,
      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_i18n117 = __toESM(require_i18n(), 1);

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

  // 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_i18n117.__)("Value must be an integer.");
    }
    return null;
  }
  var integer_default = {
    type: "integer",
    render: render2,
    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_NONE,
      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_i18n118 = __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_i18n118.__)("Value must be a number.");
    }
    return null;
  }
  var number_default = {
    type: "number",
    render: render2,
    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_NONE,
      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: render2,
    Edit: "text",
    sort: sort_text_default,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE],
    validOperators: [
      // Single selection
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_CONTAINS,
      OPERATOR_NOT_CONTAINS,
      OPERATOR_STARTS_WITH,
      // Multiple selection
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE,
      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_date12 = __toESM(require_date(), 1);

  // packages/dataviews/build-module/field-types/utils/is-valid-date-boundary.mjs
  var import_date11 = __toESM(require_date(), 1);
  function parseDateLike(value) {
    if (!value) {
      return null;
    }
    if (!isValid(new Date(value))) {
      return null;
    }
    const parsed = (0, import_date11.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_date12.getSettings)().formats.datetime,
    weekStartsOn: (0, import_date12.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_date12.dateI18n)(formatDatetime.datetime, (0, import_date12.getDate)(value));
  }
  var sort = (a3, b3, direction) => {
    const timeA = new Date(a3).getTime();
    const timeB = new Date(b3).getTime();
    return direction === "asc" ? timeA - timeB : timeB - timeA;
  };
  var datetime_default = {
    type: "datetime",
    render: render2,
    Edit: "datetime",
    sort,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [
      OPERATOR_ON,
      OPERATOR_NOT_ON,
      OPERATOR_BEFORE,
      OPERATOR_AFTER,
      OPERATOR_BEFORE_INC,
      OPERATOR_AFTER_INC,
      OPERATOR_IN_THE_PAST,
      OPERATOR_OVER
    ],
    validOperators: [
      OPERATOR_ON,
      OPERATOR_NOT_ON,
      OPERATOR_BEFORE,
      OPERATOR_AFTER,
      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_date13 = __toESM(require_date(), 1);
  var format5 = {
    date: (0, import_date13.getSettings)().formats.date,
    weekStartsOn: (0, import_date13.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_date13.dateI18n)(formatDate2.date, (0, import_date13.getDate)(value));
  }
  var sort2 = (a3, b3, direction) => {
    const timeA = new Date(a3).getTime();
    const timeB = new Date(b3).getTime();
    return direction === "asc" ? timeA - timeB : timeB - timeA;
  };
  var date_default2 = {
    type: "date",
    render: render2,
    Edit: "date",
    sort: sort2,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [
      OPERATOR_ON,
      OPERATOR_NOT_ON,
      OPERATOR_BEFORE,
      OPERATOR_AFTER,
      OPERATOR_BEFORE_INC,
      OPERATOR_AFTER_INC,
      OPERATOR_IN_THE_PAST,
      OPERATOR_OVER,
      OPERATOR_BETWEEN
    ],
    validOperators: [
      OPERATOR_ON,
      OPERATOR_NOT_ON,
      OPERATOR_BEFORE,
      OPERATOR_AFTER,
      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_i18n119 = __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_i18n119.__)("True");
    }
    if (value === false) {
      return (0, import_i18n119.__)("False");
    }
    return "";
  }
  function isValidCustom4(item, field) {
    const value = field.getValue({ item });
    if (![void 0, "", null].includes(value) && ![true, false].includes(value)) {
      return (0, import_i18n119.__)("Value must be true, false, or undefined");
    }
    return null;
  }
  var sort3 = (a3, b3, direction) => {
    const boolA = Boolean(a3);
    const boolB = Boolean(b3);
    if (boolA === boolB) {
      return 0;
    }
    if (direction === "asc") {
      return boolA ? 1 : -1;
    }
    return boolA ? -1 : 1;
  };
  var boolean_default = {
    type: "boolean",
    render: render2,
    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_default = {
    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_i18n120 = __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 render3({ 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_i18n120.__)("Value must be an array.");
    }
    if (!value.every((v3) => typeof v3 === "string")) {
      return (0, import_i18n120.__)("Every value must be a string.");
    }
    return null;
  }
  var sort4 = (a3, b3, direction) => {
    const arrA = Array.isArray(a3) ? a3 : [];
    const arrB = Array.isArray(b3) ? b3 : [];
    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: render3,
    Edit: "array",
    sort: sort4,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE],
    validOperators: [
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE,
      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_default2 = {
    type: "password",
    render: render2,
    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: render2,
    Edit: "telephone",
    sort: sort_text_default,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE],
    validOperators: [
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_CONTAINS,
      OPERATOR_NOT_CONTAINS,
      OPERATOR_STARTS_WITH,
      // Multiple selection
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE,
      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_i18n121 = __toESM(require_i18n(), 1);
  var import_jsx_runtime248 = __toESM(require_jsx_runtime(), 1);
  function render4({ item, field }) {
    if (field.hasElements) {
      return /* @__PURE__ */ (0, import_jsx_runtime248.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_runtime248.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: "8px" }, children: [
      /* @__PURE__ */ (0, import_jsx_runtime248.jsx)(
        "div",
        {
          style: {
            width: "16px",
            height: "16px",
            borderRadius: "50%",
            backgroundColor: value,
            border: "1px solid #ddd",
            flexShrink: 0
          }
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime248.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_i18n121.__)("Value must be a valid color.");
    }
    return null;
  }
  var sort5 = (a3, b3, direction) => {
    const colorA = w(a3);
    const colorB = w(b3);
    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_default2 = {
    type: "color",
    render: render4,
    Edit: "color",
    sort: sort5,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE],
    validOperators: [
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE
    ],
    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: render2,
    Edit: "url",
    sort: sort_text_default,
    enableSorting: true,
    enableGlobalSearch: false,
    defaultOperators: [OPERATOR_IS_ANY2, OPERATOR_IS_NONE],
    validOperators: [
      OPERATOR_IS,
      OPERATOR_IS_NOT,
      OPERATOR_CONTAINS,
      OPERATOR_NOT_CONTAINS,
      OPERATOR_STARTS_WITH,
      // Multiple selection
      OPERATOR_IS_ANY2,
      OPERATOR_IS_NONE,
      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 = (a3, b3, direction) => {
    if (typeof a3 === "number" && typeof b3 === "number") {
      return sort_number_default(a3, b3, direction);
    }
    return sort_text_default(a3, b3, direction);
  };
  var no_type_default = {
    // type: no type for this one
    render: render2,
    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 min3 = normalizeRangeRule(rules?.min, fieldType, "min");
    const max3 = 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: min3,
      max: max3,
      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_default2,
      boolean_default,
      media_default,
      array_default,
      password_default2,
      telephone_default,
      color_default2,
      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 getValue3 = field.getValue || get_value_from_id_default(field.id);
      const sort7 = function(a3, b3, direction) {
        const aValue = getValue3({ item: a3 });
        const bValue = getValue3({ item: b3 });
        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: getValue3,
        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_element128 = __toESM(require_element(), 1);
  function useData({
    view,
    data: shownData,
    getItemId: getItemId2,
    isLoading,
    paginationInfo,
    selection
  }) {
    const isInfiniteScrollEnabled = view.infiniteScrollEnabled;
    const [hasInitiallyLoaded, setHasInitiallyLoaded] = (0, import_element128.useState)(
      !isLoading
    );
    (0, import_element128.useEffect)(() => {
      if (!isLoading) {
        setHasInitiallyLoaded(true);
      }
    }, [isLoading]);
    const previousDataRef = (0, import_element128.useRef)(shownData);
    const previousPaginationInfoRef = (0, import_element128.useRef)(paginationInfo);
    (0, import_element128.useEffect)(() => {
      if (!isLoading) {
        previousDataRef.current = shownData;
        previousPaginationInfoRef.current = paginationInfo;
      }
    }, [shownData, isLoading, paginationInfo]);
    const [visibleEntries, setVisibleEntries] = (0, import_element128.useState)([]);
    const positionMapRef = (0, import_element128.useRef)(/* @__PURE__ */ new Map());
    const allLoadedRecordsRef = (0, import_element128.useRef)([]);
    const prevViewParamsRef = (0, import_element128.useRef)({
      search: void 0,
      filters: void 0,
      perPage: void 0
    });
    const scrollDirectionRef = (0, import_element128.useRef)(void 0);
    const prevStartPositionRef = (0, import_element128.useRef)(void 0);
    const hasInitializedRef = (0, import_element128.useRef)(false);
    const allLoadedRecords = (0, import_element128.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((a3, b3) => {
        const posA = a3.position;
        const posB = b3.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(
          (r4) => r4.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_element129 = __toESM(require_element(), 1);
  var import_compose19 = __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 distance2 = Math.abs(itemCenterY - centerY);
      const bestRect = best.getBoundingClientRect();
      const bestCenterY = bestRect.top + bestRect.height / 2;
      const bestDistance = Math.abs(bestCenterY - centerY);
      return distance2 < 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_element129.useRef)(null);
    const viewRef = (0, import_element129.useRef)(view);
    const isLoadingRef = (0, import_element129.useRef)(isLoading);
    const onChangeViewRef = (0, import_element129.useRef)(onChangeView);
    const totalItemsRef = (0, import_element129.useRef)(paginationInfo.totalItems);
    (0, import_element129.useLayoutEffect)(() => {
      viewRef.current = view;
      isLoadingRef.current = isLoading;
      onChangeViewRef.current = onChangeView;
      totalItemsRef.current = paginationInfo.totalItems;
    }, [view, isLoading, onChangeView, paginationInfo.totalItems]);
    const intersectionObserverCallback = (0, import_element129.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_element129.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_element129.useRef)(
      null
    );
    (0, import_element129.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_element129.useEffect)(() => {
      if (!view.infiniteScrollEnabled || !containerRef.current) {
        return;
      }
      let lastScrollTop = 0;
      const BOTTOM_THRESHOLD = 600;
      const TOP_THRESHOLD = 800;
      const handleScroll = (0, import_compose19.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-picker/index.mjs
  var import_element130 = __toESM(require_element(), 1);
  var import_compose20 = __toESM(require_compose(), 1);
  var import_jsx_runtime249 = __toESM(require_jsx_runtime(), 1);
  var isItemClickable = () => false;
  var dataViewsPickerLayouts = VIEW_LAYOUTS.filter(
    (viewLayout) => viewLayout.isPicker
  );
  var defaultGetItemId = (item) => item.id;
  var EMPTY_ARRAY10 = [];
  var DEFAULT_PICKER_LAYOUTS = {
    pickerGrid: true,
    pickerTable: true
  };
  function DefaultUI({
    search = true,
    searchLabel = void 0
  }) {
    const { view } = (0, import_element130.useContext)(dataviews_context_default);
    const isInfiniteScroll = view.infiniteScrollEnabled;
    return /* @__PURE__ */ (0, import_jsx_runtime249.jsxs)(import_jsx_runtime249.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime249.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_runtime249.jsxs)(
              Stack,
              {
                direction: "row",
                gap: "sm",
                justify: "start",
                className: "dataviews__search",
                children: [
                  search && /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(dataviews_search_default, { label: searchLabel }),
                  /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(toggle_default, {})
                ]
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(Stack, { direction: "row", gap: "xs", style: { flexShrink: 0 }, children: /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(dataviews_view_config_default, {}) })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(filters_toggled_default, { className: "dataviews-filters__container" }),
      /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(DataViewsLayout, {}),
      /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(DataViewsPickerFooter, {})
    ] });
  }
  function DataViewsPicker({
    view,
    onChangeView,
    fields: fields2,
    search = true,
    searchLabel = void 0,
    actions: actions2 = EMPTY_ARRAY10,
    data,
    getItemId: getItemId2 = defaultGetItemId,
    isLoading = false,
    paginationInfo,
    defaultLayouts: defaultLayoutsProperty = DEFAULT_PICKER_LAYOUTS,
    selection,
    onChangeSelection,
    children,
    config: config2 = { perPageSizes: [10, 20, 50, 100] },
    itemListLabel,
    empty,
    onReset
  }) {
    const { data: displayData, setVisibleEntries } = useData({
      view,
      data,
      getItemId: getItemId2,
      selection,
      paginationInfo
    });
    const containerRef = (0, import_element130.useRef)(null);
    const [containerWidth, setContainerWidth] = (0, import_element130.useState)(0);
    const resizeObserverRef = (0, import_compose20.useResizeObserver)(
      (resizeObserverEntries) => {
        setContainerWidth(
          resizeObserverEntries[0].borderBoxSize[0].inlineSize
        );
      },
      { box: "border-box" }
    );
    const [openedFilter, setOpenedFilter] = (0, import_element130.useState)(null);
    function setSelectionWithChange(value) {
      const newValue = typeof value === "function" ? value(selection) : value;
      if (onChangeSelection) {
        onChangeSelection(newValue);
      }
    }
    const _fields = (0, import_element130.useMemo)(() => normalizeFields(fields2), [fields2]);
    const filters = use_filters_default(_fields, view);
    const hasPrimaryOrLockedFilters = (0, import_element130.useMemo)(
      () => (filters || []).some(
        (filter) => filter.isPrimary || filter.isLocked
      ),
      [filters]
    );
    const [isShowingFilter, setIsShowingFilter] = (0, import_element130.useState)(
      hasPrimaryOrLockedFilters
    );
    const { intersectionObserver } = useInfiniteScroll({
      view,
      onChangeView,
      isLoading,
      paginationInfo,
      containerRef,
      setVisibleEntries
    });
    (0, import_element130.useEffect)(() => {
      if (hasPrimaryOrLockedFilters && !isShowingFilter) {
        setIsShowingFilter(true);
      }
    }, [hasPrimaryOrLockedFilters, isShowingFilter]);
    const defaultLayouts2 = (0, import_element130.useMemo)(
      () => Object.fromEntries(
        Object.entries(defaultLayoutsProperty).filter(([layoutType]) => {
          return dataViewsPickerLayouts.some(
            (viewLayout) => viewLayout.type === layoutType
          );
        }).map(([key, value]) => [
          key,
          value === true ? {} : value
        ])
      ),
      [defaultLayoutsProperty]
    );
    if (!defaultLayouts2[view.type]) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(
      dataviews_context_default.Provider,
      {
        value: {
          view,
          onChangeView,
          fields: _fields,
          actions: actions2,
          data: displayData,
          isLoading,
          paginationInfo,
          isItemClickable,
          selection,
          onChangeSelection: setSelectionWithChange,
          openedFilter,
          setOpenedFilter,
          getItemId: getItemId2,
          containerWidth,
          containerRef,
          resizeObserverRef,
          defaultLayouts: defaultLayouts2,
          filters,
          isShowingFilter,
          setIsShowingFilter,
          config: config2,
          itemListLabel,
          empty,
          onReset,
          hasInitiallyLoaded: true,
          intersectionObserver
        },
        children: /* @__PURE__ */ (0, import_jsx_runtime249.jsx)("div", { className: "dataviews-picker-wrapper", children: children ?? /* @__PURE__ */ (0, import_jsx_runtime249.jsx)(DefaultUI, { search, searchLabel }) })
      }
    );
  }
  var DataViewsPickerSubComponents = DataViewsPicker;
  DataViewsPickerSubComponents.BulkActionToolbar = DataViewsPickerBulkActionToolbar;
  DataViewsPickerSubComponents.Footer = DataViewsPickerFooter;
  DataViewsPickerSubComponents.Filters = filters_default;
  DataViewsPickerSubComponents.FiltersToggled = filters_toggled_default;
  DataViewsPickerSubComponents.FiltersToggle = toggle_default;
  DataViewsPickerSubComponents.Layout = DataViewsLayout;
  DataViewsPickerSubComponents.LayoutSwitcher = ViewTypeMenu;
  DataViewsPickerSubComponents.Pagination = DataViewsPagination;
  DataViewsPickerSubComponents.Search = dataviews_search_default;
  DataViewsPickerSubComponents.ViewConfig = DataviewsViewConfigDropdown;
  var dataviews_picker_default = DataViewsPickerSubComponents;

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

  // packages/dataviews/build-module/components/dataform-context/index.mjs
  var import_element131 = __toESM(require_element(), 1);
  var import_jsx_runtime250 = __toESM(require_jsx_runtime(), 1);
  var DataFormContext = (0, import_element131.createContext)({
    fields: []
  });
  DataFormContext.displayName = "DataFormContext";
  function DataFormProvider({
    fields: fields2,
    children
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime250.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_element141 = __toESM(require_element(), 1);

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

  // packages/dataviews/build-module/components/dataform-layouts/normalize-form.mjs
  var import_i18n122 = __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_i18n122.__)("Apply"),
          cancelLabel: openAs.cancelLabel?.trim() || (0, import_i18n122.__)("Cancel")
        };
      } else if (openAs === "modal") {
        normalizedOpenAs = {
          type: "modal",
          applyLabel: (0, import_i18n122.__)("Apply"),
          cancelLabel: (0, import_i18n122.__)("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(form) {
    const normalizedFormLayout = normalizeLayout(form?.layout);
    const normalizedFields = (form.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_runtime251 = __toESM(require_jsx_runtime(), 1);
  function Header3({ title }) {
    return /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
      Stack,
      {
        direction: "column",
        className: "dataforms-layouts-regular__header",
        gap: "lg",
        children: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(Stack, { direction: "row", align: "center", children: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(import_components73.__experimentalHeading, { level: 2, size: 13, children: title }) })
      }
    );
  }
  function FormRegularField({
    data,
    field,
    onChange,
    hideLabelFromVision,
    markWhenOptional,
    validity
  }) {
    const { fields: fields2 } = (0, import_element132.useContext)(dataform_context_default);
    const layout = field.layout;
    const form = (0, import_element132.useMemo)(
      () => ({
        layout: DEFAULT_LAYOUT,
        fields: !!field.children ? field.children : []
      }),
      [field]
    );
    if (!!field.children) {
      return /* @__PURE__ */ (0, import_jsx_runtime251.jsxs)(import_jsx_runtime251.Fragment, { children: [
        !hideLabelFromVision && field.label && /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(Header3, { title: field.label }),
        /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
          DataFormLayout,
          {
            data,
            form,
            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_runtime251.jsxs)(
        Stack,
        {
          direction: "row",
          className: "dataforms-layouts-regular__field",
          gap: "sm",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
              "div",
              {
                className: clsx_default(
                  "dataforms-layouts-regular__field-label",
                  `dataforms-layouts-regular__field-label--label-position-${labelPosition}`
                ),
                children: /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(import_components73.BaseControl.VisualLabel, { children: fieldDefinition.label })
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime251.jsx)("div", { className: "dataforms-layouts-regular__field-control", children: fieldDefinition.readOnly === true ? /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
              fieldDefinition.render,
              {
                item: data,
                field: fieldDefinition
              }
            ) : /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
              fieldDefinition.Edit,
              {
                data,
                field: fieldDefinition,
                onChange,
                hideLabelFromVision: true,
                markWhenOptional,
                validity
              },
              fieldDefinition.id
            ) })
          ]
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime251.jsx)("div", { className: "dataforms-layouts-regular__field", children: fieldDefinition.readOnly === true ? /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(import_jsx_runtime251.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime251.jsxs)(import_jsx_runtime251.Fragment, { children: [
      !hideLabelFromVision && labelPosition !== "none" && /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(import_components73.BaseControl.VisualLabel, { children: fieldDefinition.label }),
      /* @__PURE__ */ (0, import_jsx_runtime251.jsx)(
        fieldDefinition.render,
        {
          item: data,
          field: fieldDefinition
        }
      )
    ] }) }) : /* @__PURE__ */ (0, import_jsx_runtime251.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_components76 = __toESM(require_components(), 1);
  var import_element137 = __toESM(require_element(), 1);
  var import_compose22 = __toESM(require_compose(), 1);

  // packages/dataviews/build-module/components/dataform-layouts/panel/summary-button.mjs
  var import_components75 = __toESM(require_components(), 1);
  var import_i18n123 = __toESM(require_i18n(), 1);
  var import_compose21 = __toESM(require_compose(), 1);
  var import_element133 = __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_components74 = __toESM(require_components(), 1);
  var import_jsx_runtime252 = __toESM(require_jsx_runtime(), 1);
  function getLabelContent(showError, errorMessage, fieldLabel) {
    return showError ? /* @__PURE__ */ (0, import_jsx_runtime252.jsxs)(tooltip_exports.Root, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(
        tooltip_exports.Trigger,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime252.jsxs)("span", { className: "dataforms-layouts-panel__field-label-error-content", children: [
            /* @__PURE__ */ (0, import_jsx_runtime252.jsx)(import_components74.Icon, { icon: error_default, size: 16 }),
            /* @__PURE__ */ (0, import_jsx_runtime252.jsxs)(VisuallyHidden, { children: [
              errorMessage,
              ": "
            ] }),
            fieldLabel
          ] })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime252.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_runtime253 = __toESM(require_jsx_runtime(), 1);
  function SummaryButton({
    data,
    field,
    fieldLabel,
    summaryFields,
    validity,
    touched,
    disabled: disabled2,
    isOpen: isOpen2,
    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_compose21.useInstanceId)(
      SummaryButton,
      "dataforms-layouts-panel__field-control"
    );
    const ariaLabel = showError ? (0, import_i18n123.sprintf)(
      // translators: %s: Field name.
      (0, import_i18n123._x)("Edit %s (has errors)", "field"),
      fieldLabel || ""
    ) : (0, import_i18n123.sprintf)(
      // translators: %s: Field name.
      (0, import_i18n123._x)("Edit %s", "field"),
      fieldLabel || ""
    );
    const rowRef = (0, import_element133.useRef)(null);
    const editButtonRef = (0, import_element133.useRef)(null);
    const handleRowClick = (event) => {
      if (!isOpen2 && 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_runtime253.jsxs)(
      "div",
      {
        ref: rowRef,
        className,
        onClick: !disabled2 ? handleRowClick : void 0,
        onKeyDown: !disabled2 ? handleKeyDown : void 0,
        children: [
          labelPosition !== "none" && /* @__PURE__ */ (0, import_jsx_runtime253.jsx)("span", { className: labelClassName, children: labelContent }),
          labelPosition === "none" && showError && /* @__PURE__ */ (0, import_jsx_runtime253.jsxs)(tooltip_exports.Root, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
              tooltip_exports.Trigger,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
                  "span",
                  {
                    className: "dataforms-layouts-panel__field-label-error-content",
                    role: "img",
                    "aria-label": errorMessage,
                    children: /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(import_components75.Icon, { icon: error_default, size: 16 })
                  }
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(tooltip_exports.Popup, { children: errorMessage })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
            "span",
            {
              id: `${controlId}`,
              className: "dataforms-layouts-panel__field-control",
              children: summaryFields.length > 1 ? /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
                "span",
                {
                  style: {
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "flex-start",
                    width: "100%",
                    gap: "2px"
                  },
                  children: summaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
                    "span",
                    {
                      style: { width: "100%" },
                      children: /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
                        summaryField.render,
                        {
                          item: data,
                          field: summaryField
                        }
                      )
                    },
                    summaryField.id
                  ))
                }
              ) : summaryFields.map((summaryField) => /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
                summaryField.render,
                {
                  item: data,
                  field: summaryField
                },
                summaryField.id
              ))
            }
          ),
          !disabled2 && /* @__PURE__ */ (0, import_jsx_runtime253.jsx)(
            import_components75.Button,
            {
              ref: editButtonRef,
              className: "dataforms-layouts-panel__field-trigger-icon",
              label: ariaLabel,
              icon: pencil_default,
              size: "small",
              "aria-expanded": isOpen2,
              "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_element134 = __toESM(require_element(), 1);
  var import_i18n124 = __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(form, fields2) {
    const normalizedForm = normalize_form_default(form);
    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 i3 = 0; i3 < path.length - 1; i3++) {
      const segment2 = path[i3];
      if (!current[segment2]) {
        current[segment2] = {};
      }
      current[segment2] = { ...current[segment2] };
      current = current[segment2];
    }
    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 i3 = 0; i3 < path.length - 1; i3++) {
      const segment2 = path[i3];
      if (!current[segment2]) {
        return formValidity;
      }
      current[segment2] = { ...current[segment2] };
      current = current[segment2];
    }
    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_i18n124.__)("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_i18n124.__)(
                  "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_i18n124.__)(
          "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_i18n124.__)("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_i18n124.__)(
          "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_i18n124.__)("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_i18n124.__)("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_i18n124.__)("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_i18n124.__)("Value is too short.")
        }
      };
    }
    if (formField.field?.isValid.maxLength && !formField.field.isValid.maxLength.validate(item, formField.field)) {
      return {
        maxLength: {
          type: "invalid",
          message: (0, import_i18n124.__)("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_i18n124.__)("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_i18n124.__)("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_i18n124.__)("Validating\u2026")
      };
    }
    if (customError instanceof Promise) {
      handleCustomValidationAsync(customError, formField, promiseHandler);
      fieldValidity.custom = {
        type: "validating",
        message: (0, import_i18n124.__)("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, form) {
    const [formValidity, setFormValidity] = (0, import_element134.useState)();
    const customCounterRef = (0, import_element134.useRef)({});
    const elementsCounterRef = (0, import_element134.useRef)({});
    const previousValuesRef = (0, import_element134.useRef)({});
    const validate = (0, import_element134.useCallback)(() => {
      const promiseHandler = {
        customCounterRef,
        elementsCounterRef,
        setFormValidity,
        path: [],
        item
      };
      const formFieldsToValidate = getFormFieldsToValidate(form, 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, form]);
    (0, import_element134.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_element135 = __toESM(require_element(), 1);
  function useReportValidity(ref, shouldReport) {
    (0, import_element135.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_element136 = __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_element136.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_runtime254 = __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_element137.useContext)(dataform_context_default);
    const [changes, setChanges] = (0, import_element137.useState)({});
    const modalData = (0, import_element137.useMemo)(() => {
      return (0, import_deepmerge3.default)(data, changes, {
        arrayMerge: (target, source) => source
      });
    }, [data, changes]);
    const form = (0, import_element137.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((f3) => ({
      ...f3,
      Edit: f3.Edit === null ? void 0 : f3.Edit,
      isValid: {
        required: f3.isValid.required?.constraint,
        elements: f3.isValid.elements?.constraint,
        min: f3.isValid.min?.constraint,
        max: f3.isValid.max?.constraint,
        pattern: f3.isValid.pattern?.constraint,
        minLength: f3.isValid.minLength?.constraint,
        maxLength: f3.isValid.maxLength?.constraint
      }
    }));
    const { validity } = use_form_validity_default(modalData, fieldsAsFieldType, form);
    const onApply = () => {
      onChange(changes);
      onClose();
    };
    const handleOnChange = (newValue) => {
      setChanges(
        (prev) => (0, import_deepmerge3.default)(prev, newValue, {
          arrayMerge: (target, source) => source
        })
      );
    };
    const focusOnMountRef = (0, import_compose22.useFocusOnMount)("firstInputElement");
    const contentRef = (0, import_element137.useRef)(null);
    const mergedRef = (0, import_compose22.useMergeRefs)([focusOnMountRef, contentRef]);
    useReportValidity(contentRef, touched);
    return /* @__PURE__ */ (0, import_jsx_runtime254.jsxs)(
      import_components76.Modal,
      {
        className: "dataforms-layouts-panel__modal",
        onRequestClose: onClose,
        isFullScreen: false,
        title: fieldLabel,
        size: "medium",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime254.jsx)("div", { ref: mergedRef, children: /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
            DataFormLayout,
            {
              data: modalData,
              form,
              onChange: handleOnChange,
              validity,
              children: (FieldLayout, childField, childFieldValidity, markWhenOptional) => /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
                FieldLayout,
                {
                  data: modalData,
                  field: childField,
                  onChange: handleOnChange,
                  hideLabelFromVision: form.fields.length < 2,
                  markWhenOptional,
                  validity: childFieldValidity
                },
                childField.id
              )
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime254.jsxs)(
            Stack,
            {
              direction: "row",
              className: "dataforms-layouts-panel__modal-footer",
              gap: "md",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(import_components76.__experimentalSpacer, { style: { flex: 1 } }),
                /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
                  import_components76.Button,
                  {
                    variant: "tertiary",
                    onClick: onClose,
                    __next40pxDefaultSize: true,
                    children: cancelLabel
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
                  import_components76.Button,
                  {
                    variant: "primary",
                    onClick: onApply,
                    __next40pxDefaultSize: true,
                    children: applyLabel
                  }
                )
              ]
            }
          )
        ]
      }
    );
  }
  function PanelModal({
    data,
    field,
    onChange,
    validity
  }) {
    const [touched, setTouched] = (0, import_element137.useState)(false);
    const [isOpen2, setIsOpen] = (0, import_element137.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_runtime254.jsxs)(import_jsx_runtime254.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime254.jsx)(
        SummaryButton,
        {
          data,
          field,
          fieldLabel,
          summaryFields,
          validity,
          touched,
          disabled: fieldDefinition.readOnly === true,
          onClick: () => setIsOpen(true),
          isOpen: isOpen2
        }
      ),
      isOpen2 && /* @__PURE__ */ (0, import_jsx_runtime254.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_components77 = __toESM(require_components(), 1);
  var import_i18n125 = __toESM(require_i18n(), 1);
  var import_element138 = __toESM(require_element(), 1);
  var import_compose23 = __toESM(require_compose(), 1);
  var import_jsx_runtime255 = __toESM(require_jsx_runtime(), 1);
  function DropdownHeader({
    title,
    onClose
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
      Stack,
      {
        direction: "column",
        className: "dataforms-layouts-panel__dropdown-header",
        gap: "lg",
        children: /* @__PURE__ */ (0, import_jsx_runtime255.jsxs)(Stack, { direction: "row", gap: "sm", align: "center", children: [
          title && /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(import_components77.__experimentalHeading, { level: 2, size: 13, children: title }),
          /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(import_components77.__experimentalSpacer, { style: { flex: 1 } }),
          onClose && /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
            import_components77.Button,
            {
              label: (0, import_i18n125.__)("Close"),
              icon: close_small_default,
              onClick: onClose,
              size: "small"
            }
          )
        ] })
      }
    );
  }
  function DropdownContentWithValidation({
    touched,
    children
  }) {
    const ref = (0, import_element138.useRef)(null);
    useReportValidity(ref, touched);
    return /* @__PURE__ */ (0, import_jsx_runtime255.jsx)("div", { ref, children });
  }
  function PanelDropdown({
    data,
    field,
    onChange,
    validity
  }) {
    const [touched, setTouched] = (0, import_element138.useState)(false);
    const [popoverAnchor, setPopoverAnchor] = (0, import_element138.useState)(
      null
    );
    const popoverProps = (0, import_element138.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_compose23.__experimentalUseDialog)({
      focusOnMount: "firstInputElement"
    });
    const form = (0, import_element138.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_element138.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_runtime255.jsx)(
      "div",
      {
        ref: setPopoverAnchor,
        className: "dataforms-layouts-panel__field-dropdown-anchor",
        children: /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
          import_components77.Dropdown,
          {
            contentClassName: "dataforms-layouts-panel__field-dropdown",
            popoverProps,
            focusOnMount: false,
            onToggle: (willOpen) => {
              if (!willOpen) {
                setTouched(true);
              }
            },
            renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
              SummaryButton,
              {
                data,
                field,
                fieldLabel,
                summaryFields,
                validity,
                touched,
                disabled: fieldDefinition.readOnly === true,
                isOpen: isOpen2,
                onClick: onToggle
              }
            ),
            renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(DropdownContentWithValidation, { touched, children: /* @__PURE__ */ (0, import_jsx_runtime255.jsxs)("div", { ref: dialogRef, ...dialogProps, children: [
              /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
                DropdownHeader,
                {
                  title: fieldLabel,
                  onClose
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
                DataFormLayout,
                {
                  data,
                  form,
                  onChange,
                  validity: formValidity,
                  children: (FieldLayout, childField, childFieldValidity, markWhenOptional) => /* @__PURE__ */ (0, import_jsx_runtime255.jsx)(
                    FieldLayout,
                    {
                      data,
                      field: childField,
                      onChange,
                      hideLabelFromVision: (form?.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_runtime256 = __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_runtime256.jsx)(
        modal_default,
        {
          data,
          field,
          onChange,
          validity
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime256.jsx)(
      dropdown_default,
      {
        data,
        field,
        onChange,
        validity
      }
    );
  }

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

  // packages/dataviews/build-module/components/dataform-layouts/validation-badge.mjs
  var import_i18n126 = __toESM(require_i18n(), 1);
  var import_jsx_runtime257 = __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_runtime257.jsx)(Badge, { intent: "high", children: (0, import_i18n126.sprintf)(
      /* translators: %d: Number of fields that need attention */
      (0, import_i18n126._n)(
        "%d field needs attention",
        "%d fields need attention",
        invalidCount
      ),
      invalidCount
    ) });
  }

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

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

  // packages/dataviews/build-module/components/dataform-layouts/details/index.mjs
  var import_element140 = __toESM(require_element(), 1);
  var import_i18n127 = __toESM(require_i18n(), 1);
  var import_jsx_runtime260 = __toESM(require_jsx_runtime(), 1);
  function FormDetailsField({
    data,
    field,
    onChange,
    validity
  }) {
    const { fields: fields2 } = (0, import_element140.useContext)(dataform_context_default);
    const detailsRef = (0, import_element140.useRef)(null);
    const contentRef = (0, import_element140.useRef)(null);
    const [touched, setTouched] = (0, import_element140.useState)(false);
    const [isOpen2, setIsOpen] = (0, import_element140.useState)(false);
    const form = (0, import_element140.useMemo)(
      () => ({
        layout: DEFAULT_LAYOUT,
        fields: field.children ?? []
      }),
      [field]
    );
    (0, import_element140.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, isOpen2 && touched);
    const handleBlur = (0, import_element140.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_runtime260.jsx)(summaryField.render, { item: data, field: summaryField });
    } else {
      summaryContent = field.label || (0, import_i18n127.__)("More details");
    }
    return /* @__PURE__ */ (0, import_jsx_runtime260.jsxs)(
      "details",
      {
        ref: detailsRef,
        className: "dataforms-layouts-details__details",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime260.jsx)("summary", { className: "dataforms-layouts-details__summary", children: /* @__PURE__ */ (0, import_jsx_runtime260.jsxs)(
            Stack,
            {
              direction: "row",
              align: "center",
              gap: "md",
              className: "dataforms-layouts-details__summary-content",
              children: [
                summaryContent,
                touched && /* @__PURE__ */ (0, import_jsx_runtime260.jsx)(ValidationBadge, { validity })
              ]
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime260.jsx)(
            "div",
            {
              ref: contentRef,
              className: "dataforms-layouts-details__content",
              onBlur: handleBlur,
              children: /* @__PURE__ */ (0, import_jsx_runtime260.jsx)(
                DataFormLayout,
                {
                  data,
                  form,
                  onChange,
                  validity: validity?.children
                }
              )
            }
          )
        ]
      }
    );
  }

  // packages/dataviews/build-module/components/dataform-layouts/index.mjs
  var import_jsx_runtime261 = __toESM(require_jsx_runtime(), 1);
  var FORM_FIELD_LAYOUTS = [
    {
      type: "regular",
      component: FormRegularField,
      wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime261.jsx)(
        Stack,
        {
          direction: "column",
          className: "dataforms-layouts__wrapper",
          gap: "lg",
          children
        }
      )
    },
    {
      type: "panel",
      component: FormPanelField,
      wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime261.jsx)(
        Stack,
        {
          direction: "column",
          className: "dataforms-layouts__wrapper",
          gap: "md",
          children
        }
      )
    },
    {
      type: "card",
      component: FormCardField,
      wrapper: ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime261.jsx)(
        Stack,
        {
          direction: "column",
          className: "dataforms-layouts__wrapper",
          gap: "xl",
          children
        }
      )
    },
    {
      type: "row",
      component: FormRowField,
      wrapper: ({
        children,
        layout
      }) => /* @__PURE__ */ (0, import_jsx_runtime261.jsx)(
        Stack,
        {
          direction: "column",
          className: "dataforms-layouts__wrapper",
          gap: "lg",
          children: /* @__PURE__ */ (0, import_jsx_runtime261.jsx)("div", { className: "dataforms-layouts-row__field", children: /* @__PURE__ */ (0, import_jsx_runtime261.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_runtime262 = __toESM(require_jsx_runtime(), 1);
  var DEFAULT_WRAPPER = ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(Stack, { direction: "column", className: "dataforms-layouts__wrapper", gap: "lg", children });
  function DataFormLayout({
    data,
    form,
    onChange,
    validity,
    children,
    as
  }) {
    const { fields: fieldDefinitions } = (0, import_element141.useContext)(dataform_context_default);
    const markWhenOptional = (0, import_element141.useMemo)(() => {
      const requiredCount = fieldDefinitions.filter(
        (f3) => !!f3.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(form.layout.type)?.wrapper ?? DEFAULT_WRAPPER;
    return /* @__PURE__ */ (0, import_jsx_runtime262.jsx)(Wrapper, { layout: form.layout, children: form.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_runtime262.jsx)(
        FieldLayout,
        {
          data,
          field: formField,
          onChange,
          markWhenOptional,
          validity: validity?.[formField.id]
        },
        formField.id
      );
    }) });
  }

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

  // packages/dataviews/build-module/utils/filter-sort-and-paginate.mjs
  var import_remove_accents3 = __toESM(require_remove_accents(), 1);
  var import_deprecated3 = __toESM(require_deprecated(), 1);
  function normalizeSearchInput2(input = "") {
    return (0, import_remove_accents3.default)(input.trim().toLowerCase());
  }
  var EMPTY_ARRAY11 = [];
  function filterSortAndPaginate(data, view, fields2) {
    if (!data) {
      return {
        data: EMPTY_ARRAY11,
        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_deprecated3.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((a3, b3) => {
        if (groupByField) {
          const groupCompare = groupByField.sort(
            a3,
            b3,
            view.groupBy?.direction ?? "asc"
          );
          if (groupCompare !== 0) {
            return groupCompare;
          }
        }
        if (sortByField) {
          return sortByField.sort(a3, b3, 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/dataviews/build-module/private-apis.mjs
  var privateApis13 = {};
  lock5(privateApis13, {
    RichTextControl
  });

  // packages/media-editor/build-module/components/media-form/index.mjs
  var import_components79 = __toESM(require_components(), 1);
  var import_i18n128 = __toESM(require_i18n(), 1);
  var import_jsx_runtime264 = __toESM(require_jsx_runtime(), 1);
  function MediaForm({
    form: formOverrides,
    header
  }) {
    const { media, fields: fields2, onChange } = useMediaEditorContext();
    if (!media || !onChange) {
      return /* @__PURE__ */ (0, import_jsx_runtime264.jsx)("div", { className: "media-editor-form media-editor-form--loading", children: /* @__PURE__ */ (0, import_jsx_runtime264.jsx)(import_components79.Spinner, {}) });
    }
    const regularFieldIds = ["title", "alt_text", "caption", "description"];
    const sortedFields = [
      ...fields2.filter(
        (field) => regularFieldIds.includes(field.id)
      ),
      ...fields2.filter(
        (field) => !regularFieldIds.includes(field.id)
      )
    ];
    const defaultForm = {
      layout: {
        type: "panel"
      },
      fields: sortedFields.map((field) => {
        if (regularFieldIds.includes(field.id)) {
          return {
            id: field.id,
            layout: {
              type: "regular",
              labelPosition: "top"
            }
          };
        }
        return field.id;
      })
    };
    const form = formOverrides || defaultForm;
    return /* @__PURE__ */ (0, import_jsx_runtime264.jsx)("div", { className: "media-editor-form", children: /* @__PURE__ */ (0, import_jsx_runtime264.jsxs)(import_components79.__experimentalVStack, { spacing: 4, children: [
      /* @__PURE__ */ (0, import_jsx_runtime264.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime264.jsx)("h2", {}), children: (0, import_i18n128.__)("Media details") }),
      header,
      /* @__PURE__ */ (0, import_jsx_runtime264.jsx)(
        DataForm,
        {
          data: media,
          fields: fields2,
          form,
          onChange
        }
      )
    ] }) });
  }

  // packages/media-editor/build-module/lock-unlock.mjs
  var import_private_apis8 = __toESM(require_private_apis(), 1);
  var { lock: lock6, unlock: unlock6 } = (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/media-editor"
  );

  // packages/media-editor/build-module/store/index.mjs
  var import_data38 = __toESM(require_data(), 1);

  // packages/media-editor/build-module/store/reducer.mjs
  var DEFAULT_STATE = {
    isOpen: false,
    id: null,
    onUpdate: null,
    onClose: null
  };
  function reducer(state2 = DEFAULT_STATE, action) {
    switch (action.type) {
      case "OPEN_MEDIA_EDITOR_MODAL": {
        const { id, onUpdate, onClose } = action;
        return {
          isOpen: true,
          id,
          onUpdate,
          onClose
        };
      }
      case "CLOSE_MEDIA_EDITOR_MODAL":
        return DEFAULT_STATE;
    }
    return state2;
  }

  // packages/media-editor/build-module/store/actions.mjs
  var actions_exports = {};
  __export(actions_exports, {
    closeMediaEditorModal: () => closeMediaEditorModal,
    openMediaEditorModal: () => openMediaEditorModal
  });
  function openMediaEditorModal({
    id,
    onUpdate,
    onClose
  }) {
    return {
      type: "OPEN_MEDIA_EDITOR_MODAL",
      id,
      onUpdate: onUpdate ?? null,
      onClose: onClose ?? null
    };
  }
  function closeMediaEditorModal() {
    return { type: "CLOSE_MEDIA_EDITOR_MODAL" };
  }

  // packages/media-editor/build-module/store/selectors.mjs
  var selectors_exports2 = {};
  __export(selectors_exports2, {
    getId: () => getId,
    getOnClose: () => getOnClose,
    getOnUpdate: () => getOnUpdate,
    isOpen: () => isOpen
  });
  function isOpen(state2) {
    return state2.isOpen;
  }
  function getId(state2) {
    return state2.id;
  }
  function getOnUpdate(state2) {
    return state2.onUpdate;
  }
  function getOnClose(state2) {
    return state2.onClose;
  }

  // packages/media-editor/build-module/store/constants.mjs
  var STORE_NAME2 = "core/media-editor";

  // packages/media-editor/build-module/store/index.mjs
  var store2 = (0, import_data38.createReduxStore)(STORE_NAME2, {
    reducer,
    actions: actions_exports,
    selectors: selectors_exports2
  });
  (0, import_data38.register)(store2);

  // packages/media-editor/build-module/components/media-editor-modal/index.mjs
  var import_components92 = __toESM(require_components(), 1);
  var import_data46 = __toESM(require_data(), 1);
  var import_i18n142 = __toESM(require_i18n(), 1);
  var import_keyboard_shortcuts = __toESM(require_keyboard_shortcuts(), 1);
  var import_notices15 = __toESM(require_notices(), 1);

  // packages/media-editor/build-module/components/media-editor/index.mjs
  var import_components91 = __toESM(require_components(), 1);
  var import_compose26 = __toESM(require_compose(), 1);
  var import_data45 = __toESM(require_data(), 1);
  var import_core_data29 = __toESM(require_core_data(), 1);
  var import_element165 = __toESM(require_element(), 1);
  var import_i18n141 = __toESM(require_i18n(), 1);
  var import_keycodes4 = __toESM(require_keycodes(), 1);
  var import_notices14 = __toESM(require_notices(), 1);

  // packages/interface/build-module/index.mjs
  var build_module_exports = {};
  __export(build_module_exports, {
    ActionItem: () => action_item_default,
    ComplementaryArea: () => complementary_area_default,
    ComplementaryAreaMoreMenuItem: () => ComplementaryAreaMoreMenuItem,
    FullscreenMode: () => fullscreen_mode_default,
    InterfaceSkeleton: () => interface_skeleton_default,
    PinnedItems: () => pinned_items_default,
    store: () => store3
  });

  // packages/interface/build-module/components/complementary-area/index.mjs
  var import_components84 = __toESM(require_components(), 1);
  var import_data43 = __toESM(require_data(), 1);
  var import_i18n129 = __toESM(require_i18n(), 1);
  var import_element144 = __toESM(require_element(), 1);
  var import_viewport3 = __toESM(require_viewport(), 1);
  var import_preferences5 = __toESM(require_preferences(), 1);
  var import_compose24 = __toESM(require_compose(), 1);
  var import_plugins3 = __toESM(require_plugins(), 1);

  // packages/interface/build-module/components/complementary-area-toggle/index.mjs
  var import_components80 = __toESM(require_components(), 1);
  var import_data42 = __toESM(require_data(), 1);
  var import_plugins2 = __toESM(require_plugins(), 1);

  // packages/interface/build-module/store/index.mjs
  var import_data41 = __toESM(require_data(), 1);

  // packages/interface/build-module/store/actions.mjs
  var actions_exports2 = {};
  __export(actions_exports2, {
    closeModal: () => closeModal,
    disableComplementaryArea: () => disableComplementaryArea,
    enableComplementaryArea: () => enableComplementaryArea,
    openModal: () => openModal,
    pinItem: () => pinItem,
    setDefaultComplementaryArea: () => setDefaultComplementaryArea,
    setFeatureDefaults: () => setFeatureDefaults,
    setFeatureValue: () => setFeatureValue,
    toggleFeature: () => toggleFeature,
    unpinItem: () => unpinItem
  });
  var import_deprecated5 = __toESM(require_deprecated(), 1);
  var import_preferences3 = __toESM(require_preferences(), 1);

  // packages/interface/build-module/store/deprecated.mjs
  var import_deprecated4 = __toESM(require_deprecated(), 1);
  function normalizeComplementaryAreaScope(scope) {
    if (["core/edit-post", "core/edit-site"].includes(scope)) {
      (0, import_deprecated4.default)(`${scope} interface scope`, {
        alternative: "core interface scope",
        hint: "core/edit-post and core/edit-site are merging.",
        version: "6.6"
      });
      return "core";
    }
    return scope;
  }
  function normalizeComplementaryAreaName(scope, name2) {
    if (scope === "core" && name2 === "edit-site/template") {
      (0, import_deprecated4.default)(`edit-site/template sidebar`, {
        alternative: "edit-post/document",
        version: "6.6"
      });
      return "edit-post/document";
    }
    if (scope === "core" && name2 === "edit-site/block-inspector") {
      (0, import_deprecated4.default)(`edit-site/block-inspector sidebar`, {
        alternative: "edit-post/block",
        version: "6.6"
      });
      return "edit-post/block";
    }
    return name2;
  }

  // packages/interface/build-module/store/actions.mjs
  var setDefaultComplementaryArea = (scope, area) => {
    scope = normalizeComplementaryAreaScope(scope);
    area = normalizeComplementaryAreaName(scope, area);
    return {
      type: "SET_DEFAULT_COMPLEMENTARY_AREA",
      scope,
      area
    };
  };
  var enableComplementaryArea = (scope, area) => ({ registry, dispatch: dispatch8 }) => {
    if (!area) {
      return;
    }
    scope = normalizeComplementaryAreaScope(scope);
    area = normalizeComplementaryAreaName(scope, area);
    const isComplementaryAreaVisible = registry.select(import_preferences3.store).get(scope, "isComplementaryAreaVisible");
    if (!isComplementaryAreaVisible) {
      registry.dispatch(import_preferences3.store).set(scope, "isComplementaryAreaVisible", true);
    }
    dispatch8({
      type: "ENABLE_COMPLEMENTARY_AREA",
      scope,
      area
    });
  };
  var disableComplementaryArea = (scope) => ({ registry }) => {
    scope = normalizeComplementaryAreaScope(scope);
    const isComplementaryAreaVisible = registry.select(import_preferences3.store).get(scope, "isComplementaryAreaVisible");
    if (isComplementaryAreaVisible) {
      registry.dispatch(import_preferences3.store).set(scope, "isComplementaryAreaVisible", false);
    }
  };
  var pinItem = (scope, item) => ({ registry }) => {
    if (!item) {
      return;
    }
    scope = normalizeComplementaryAreaScope(scope);
    item = normalizeComplementaryAreaName(scope, item);
    const pinnedItems = registry.select(import_preferences3.store).get(scope, "pinnedItems");
    if (pinnedItems?.[item] === true) {
      return;
    }
    registry.dispatch(import_preferences3.store).set(scope, "pinnedItems", {
      ...pinnedItems,
      [item]: true
    });
  };
  var unpinItem = (scope, item) => ({ registry }) => {
    if (!item) {
      return;
    }
    scope = normalizeComplementaryAreaScope(scope);
    item = normalizeComplementaryAreaName(scope, item);
    const pinnedItems = registry.select(import_preferences3.store).get(scope, "pinnedItems");
    registry.dispatch(import_preferences3.store).set(scope, "pinnedItems", {
      ...pinnedItems,
      [item]: false
    });
  };
  function toggleFeature(scope, featureName) {
    return function({ registry }) {
      (0, import_deprecated5.default)(`dispatch( 'core/interface' ).toggleFeature`, {
        since: "6.0",
        alternative: `dispatch( 'core/preferences' ).toggle`
      });
      registry.dispatch(import_preferences3.store).toggle(scope, featureName);
    };
  }
  function setFeatureValue(scope, featureName, value) {
    return function({ registry }) {
      (0, import_deprecated5.default)(`dispatch( 'core/interface' ).setFeatureValue`, {
        since: "6.0",
        alternative: `dispatch( 'core/preferences' ).set`
      });
      registry.dispatch(import_preferences3.store).set(scope, featureName, !!value);
    };
  }
  function setFeatureDefaults(scope, defaults2) {
    return function({ registry }) {
      (0, import_deprecated5.default)(`dispatch( 'core/interface' ).setFeatureDefaults`, {
        since: "6.0",
        alternative: `dispatch( 'core/preferences' ).setDefaults`
      });
      registry.dispatch(import_preferences3.store).setDefaults(scope, defaults2);
    };
  }
  function openModal(name2) {
    return {
      type: "OPEN_MODAL",
      name: name2
    };
  }
  function closeModal() {
    return {
      type: "CLOSE_MODAL"
    };
  }

  // packages/interface/build-module/store/selectors.mjs
  var selectors_exports3 = {};
  __export(selectors_exports3, {
    getActiveComplementaryArea: () => getActiveComplementaryArea,
    isComplementaryAreaLoading: () => isComplementaryAreaLoading,
    isFeatureActive: () => isFeatureActive,
    isItemPinned: () => isItemPinned,
    isModalActive: () => isModalActive
  });
  var import_data39 = __toESM(require_data(), 1);
  var import_deprecated7 = __toESM(require_deprecated(), 1);
  var import_preferences4 = __toESM(require_preferences(), 1);
  var getActiveComplementaryArea = (0, import_data39.createRegistrySelector)(
    (select9) => (state2, scope) => {
      scope = normalizeComplementaryAreaScope(scope);
      const isComplementaryAreaVisible = select9(import_preferences4.store).get(
        scope,
        "isComplementaryAreaVisible"
      );
      if (isComplementaryAreaVisible === void 0) {
        return void 0;
      }
      if (isComplementaryAreaVisible === false) {
        return null;
      }
      return state2?.complementaryAreas?.[scope];
    }
  );
  var isComplementaryAreaLoading = (0, import_data39.createRegistrySelector)(
    (select9) => (state2, scope) => {
      scope = normalizeComplementaryAreaScope(scope);
      const isVisible2 = select9(import_preferences4.store).get(
        scope,
        "isComplementaryAreaVisible"
      );
      const identifier = state2?.complementaryAreas?.[scope];
      return isVisible2 && identifier === void 0;
    }
  );
  var isItemPinned = (0, import_data39.createRegistrySelector)(
    (select9) => (state2, scope, item) => {
      scope = normalizeComplementaryAreaScope(scope);
      item = normalizeComplementaryAreaName(scope, item);
      const pinnedItems = select9(import_preferences4.store).get(
        scope,
        "pinnedItems"
      );
      return pinnedItems?.[item] ?? true;
    }
  );
  var isFeatureActive = (0, import_data39.createRegistrySelector)(
    (select9) => (state2, scope, featureName) => {
      (0, import_deprecated7.default)(
        `select( 'core/interface' ).isFeatureActive( scope, featureName )`,
        {
          since: "6.0",
          alternative: `select( 'core/preferences' ).get( scope, featureName )`
        }
      );
      return !!select9(import_preferences4.store).get(scope, featureName);
    }
  );
  function isModalActive(state2, modalName3) {
    return state2.activeModal === modalName3;
  }

  // packages/interface/build-module/store/reducer.mjs
  var import_data40 = __toESM(require_data(), 1);
  function complementaryAreas(state2 = {}, action) {
    switch (action.type) {
      case "SET_DEFAULT_COMPLEMENTARY_AREA": {
        const { scope, area } = action;
        if (state2[scope]) {
          return state2;
        }
        return {
          ...state2,
          [scope]: area
        };
      }
      case "ENABLE_COMPLEMENTARY_AREA": {
        const { scope, area } = action;
        return {
          ...state2,
          [scope]: area
        };
      }
    }
    return state2;
  }
  function activeModal(state2 = null, action) {
    switch (action.type) {
      case "OPEN_MODAL":
        return action.name;
      case "CLOSE_MODAL":
        return null;
    }
    return state2;
  }
  var reducer_default3 = (0, import_data40.combineReducers)({
    complementaryAreas,
    activeModal
  });

  // packages/interface/build-module/store/constants.mjs
  var STORE_NAME3 = "core/interface";

  // packages/interface/build-module/store/index.mjs
  var store3 = (0, import_data41.createReduxStore)(STORE_NAME3, {
    reducer: reducer_default3,
    actions: actions_exports2,
    selectors: selectors_exports3
  });
  (0, import_data41.register)(store3);

  // packages/interface/build-module/components/complementary-area-toggle/index.mjs
  var import_jsx_runtime265 = __toESM(require_jsx_runtime(), 1);
  function roleSupportsCheckedState(role) {
    return [
      "checkbox",
      "option",
      "radio",
      "switch",
      "menuitemcheckbox",
      "menuitemradio",
      "treeitem"
    ].includes(role);
  }
  function ComplementaryAreaToggle({
    as = import_components80.Button,
    scope,
    identifier: identifierProp,
    icon: iconProp,
    selectedIcon,
    name: name2,
    shortcut,
    ...props
  }) {
    const ComponentToUse = as;
    const context = (0, import_plugins2.usePluginContext)();
    const icon = iconProp || context.icon;
    const identifier = identifierProp || `${context.name}/${name2}`;
    const isSelected2 = (0, import_data42.useSelect)(
      (select9) => select9(store3).getActiveComplementaryArea(scope) === identifier,
      [identifier, scope]
    );
    const { enableComplementaryArea: enableComplementaryArea2, disableComplementaryArea: disableComplementaryArea2 } = (0, import_data42.useDispatch)(store3);
    return /* @__PURE__ */ (0, import_jsx_runtime265.jsx)(
      ComponentToUse,
      {
        icon: selectedIcon && isSelected2 ? selectedIcon : icon,
        "aria-controls": identifier.replace("/", ":"),
        "aria-checked": roleSupportsCheckedState(props.role) ? isSelected2 : void 0,
        onClick: () => {
          if (isSelected2) {
            disableComplementaryArea2(scope);
          } else {
            enableComplementaryArea2(scope, identifier);
          }
        },
        shortcut,
        ...props
      }
    );
  }

  // packages/interface/build-module/components/complementary-area-header/index.mjs
  var import_jsx_runtime266 = __toESM(require_jsx_runtime(), 1);
  var ComplementaryAreaHeader = ({
    children,
    className,
    toggleButtonProps
  }) => {
    const toggleButton = /* @__PURE__ */ (0, import_jsx_runtime266.jsx)(ComplementaryAreaToggle, { icon: close_small_default, ...toggleButtonProps });
    return /* @__PURE__ */ (0, import_jsx_runtime266.jsxs)(
      "div",
      {
        className: clsx_default(
          "components-panel__header",
          "interface-complementary-area-header",
          className
        ),
        tabIndex: -1,
        children: [
          children,
          toggleButton
        ]
      }
    );
  };
  var complementary_area_header_default = ComplementaryAreaHeader;

  // packages/interface/build-module/components/complementary-area-more-menu-item/index.mjs
  var import_components82 = __toESM(require_components(), 1);

  // packages/interface/build-module/components/action-item/index.mjs
  var import_components81 = __toESM(require_components(), 1);
  var import_element143 = __toESM(require_element(), 1);
  var import_jsx_runtime267 = __toESM(require_jsx_runtime(), 1);
  var noop7 = () => {
  };
  function ActionItemSlot({
    name: name2,
    as: Component3 = import_components81.MenuGroup,
    fillProps = {},
    bubblesVirtually,
    ...props
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(
      import_components81.Slot,
      {
        name: name2,
        bubblesVirtually,
        fillProps,
        children: (fills) => {
          if (!import_element143.Children.toArray(fills).length) {
            return null;
          }
          const initializedByPlugins = [];
          import_element143.Children.forEach(
            fills,
            ({
              props: { __unstableExplicitMenuItem, __unstableTarget }
            }) => {
              if (__unstableTarget && __unstableExplicitMenuItem) {
                initializedByPlugins.push(__unstableTarget);
              }
            }
          );
          const children = import_element143.Children.map(fills, (child) => {
            if (!child.props.__unstableExplicitMenuItem && initializedByPlugins.includes(
              child.props.__unstableTarget
            )) {
              return null;
            }
            return child;
          });
          return /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(Component3, { ...props, children });
        }
      }
    );
  }
  function ActionItem({ name: name2, as: Component3 = import_components81.Button, onClick, ...props }) {
    return /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(import_components81.Fill, { name: name2, children: ({ onClick: fpOnClick }) => {
      return /* @__PURE__ */ (0, import_jsx_runtime267.jsx)(
        Component3,
        {
          onClick: onClick || fpOnClick ? (...args) => {
            (onClick || noop7)(...args);
            (fpOnClick || noop7)(...args);
          } : void 0,
          ...props
        }
      );
    } });
  }
  ActionItem.Slot = ActionItemSlot;
  var action_item_default = ActionItem;

  // packages/interface/build-module/components/complementary-area-more-menu-item/index.mjs
  var import_jsx_runtime268 = __toESM(require_jsx_runtime(), 1);
  var PluginsMenuItem = ({
    // Menu item is marked with unstable prop for backward compatibility.
    // They are removed so they don't leak to DOM elements.
    // @see https://github.com/WordPress/gutenberg/issues/14457
    __unstableExplicitMenuItem,
    __unstableTarget,
    ...restProps
  }) => /* @__PURE__ */ (0, import_jsx_runtime268.jsx)(import_components82.MenuItem, { ...restProps });
  function ComplementaryAreaMoreMenuItem({
    scope,
    target,
    __unstableExplicitMenuItem,
    ...props
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime268.jsx)(
      ComplementaryAreaToggle,
      {
        as: (toggleProps) => {
          return /* @__PURE__ */ (0, import_jsx_runtime268.jsx)(
            action_item_default,
            {
              __unstableExplicitMenuItem,
              __unstableTarget: `${scope}/${target}`,
              as: PluginsMenuItem,
              name: `${scope}/plugin-more-menu`,
              ...toggleProps
            }
          );
        },
        role: "menuitemcheckbox",
        selectedIcon: check_default,
        name: target,
        scope,
        ...props
      }
    );
  }

  // packages/interface/build-module/components/pinned-items/index.mjs
  var import_components83 = __toESM(require_components(), 1);
  var import_jsx_runtime269 = __toESM(require_jsx_runtime(), 1);
  function PinnedItems({ scope, ...props }) {
    return /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(import_components83.Fill, { name: `PinnedItems/${scope}`, ...props });
  }
  function PinnedItemsSlot({ scope, className, ...props }) {
    return /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(import_components83.Slot, { name: `PinnedItems/${scope}`, ...props, children: (fills) => fills?.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime269.jsx)(
      "div",
      {
        className: clsx_default(
          className,
          "interface-pinned-items"
        ),
        children: fills
      }
    ) });
  }
  PinnedItems.Slot = PinnedItemsSlot;
  var pinned_items_default = PinnedItems;

  // packages/interface/build-module/components/complementary-area/index.mjs
  var import_jsx_runtime270 = __toESM(require_jsx_runtime(), 1);
  var ANIMATION_DURATION = 0.3;
  function ComplementaryAreaSlot({ scope, ...props }) {
    return /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(import_components84.Slot, { name: `ComplementaryArea/${scope}`, ...props });
  }
  var SIDEBAR_WIDTH = 280;
  var variants = {
    open: { width: SIDEBAR_WIDTH },
    closed: { width: 0 },
    mobileOpen: { width: "100vw" }
  };
  function ComplementaryAreaFill({
    activeArea,
    isActive,
    scope,
    children,
    className,
    id
  }) {
    const disableMotion = (0, import_compose24.useReducedMotion)();
    const isMobileViewport = (0, import_compose24.useViewportMatch)("medium", "<");
    const previousActiveArea = (0, import_compose24.usePrevious)(activeArea);
    const previousIsActive = (0, import_compose24.usePrevious)(isActive);
    const [, setState] = (0, import_element144.useState)({});
    (0, import_element144.useEffect)(() => {
      setState({});
    }, [isActive]);
    const transition = {
      type: "tween",
      duration: disableMotion || isMobileViewport || !!previousActiveArea && !!activeArea && activeArea !== previousActiveArea ? 0 : ANIMATION_DURATION,
      ease: [0.6, 0, 0.4, 1]
    };
    return /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(import_components84.Fill, { name: `ComplementaryArea/${scope}`, children: /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(import_components84.__unstableAnimatePresence, { initial: false, children: (previousIsActive || isActive) && /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(
      import_components84.__unstableMotion.div,
      {
        variants,
        initial: "closed",
        animate: isMobileViewport ? "mobileOpen" : "open",
        exit: "closed",
        transition,
        className: "interface-complementary-area__fill",
        children: /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(
          "div",
          {
            id,
            className,
            style: {
              width: isMobileViewport ? "100vw" : SIDEBAR_WIDTH
            },
            children
          }
        )
      }
    ) }) });
  }
  function useAdjustComplementaryListener(scope, identifier, activeArea, isActive, isSmall) {
    const previousIsSmallRef = (0, import_element144.useRef)(false);
    const shouldOpenWhenNotSmallRef = (0, import_element144.useRef)(false);
    const { enableComplementaryArea: enableComplementaryArea2, disableComplementaryArea: disableComplementaryArea2 } = (0, import_data43.useDispatch)(store3);
    (0, import_element144.useEffect)(() => {
      if (isActive && isSmall && !previousIsSmallRef.current) {
        disableComplementaryArea2(scope);
        shouldOpenWhenNotSmallRef.current = true;
      } else if (
        // If there is a flag indicating the complementary area should be
        // enabled when we go from small to big window size and we are going
        // from a small to big window size.
        shouldOpenWhenNotSmallRef.current && !isSmall && previousIsSmallRef.current
      ) {
        shouldOpenWhenNotSmallRef.current = false;
        enableComplementaryArea2(scope, identifier);
      } else if (
        // If the flag is indicating the current complementary should be
        // reopened but another complementary area becomes active, remove
        // the flag.
        shouldOpenWhenNotSmallRef.current && activeArea && activeArea !== identifier
      ) {
        shouldOpenWhenNotSmallRef.current = false;
      }
      if (isSmall !== previousIsSmallRef.current) {
        previousIsSmallRef.current = isSmall;
      }
    }, [
      isActive,
      isSmall,
      scope,
      identifier,
      activeArea,
      disableComplementaryArea2,
      enableComplementaryArea2
    ]);
  }
  function ComplementaryArea({
    children,
    className,
    closeLabel = (0, import_i18n129.__)("Close plugin"),
    identifier: identifierProp,
    header,
    headerClassName,
    icon: iconProp,
    isPinnable = true,
    panelClassName,
    scope,
    name: name2,
    title,
    toggleShortcut,
    isActiveByDefault
  }) {
    const context = (0, import_plugins3.usePluginContext)();
    const icon = iconProp || context.icon;
    const identifier = identifierProp || `${context.name}/${name2}`;
    const [isReady2, setIsReady2] = (0, import_element144.useState)(false);
    const {
      isLoading,
      isActive,
      isPinned,
      activeArea,
      isSmall,
      isLarge,
      showIconLabels
    } = (0, import_data43.useSelect)(
      (select9) => {
        const {
          getActiveComplementaryArea: getActiveComplementaryArea2,
          isComplementaryAreaLoading: isComplementaryAreaLoading2,
          isItemPinned: isItemPinned2
        } = select9(store3);
        const { get } = select9(import_preferences5.store);
        const _activeArea = getActiveComplementaryArea2(scope);
        return {
          isLoading: isComplementaryAreaLoading2(scope),
          isActive: _activeArea === identifier,
          isPinned: isItemPinned2(scope, identifier),
          activeArea: _activeArea,
          isSmall: select9(import_viewport3.store).isViewportMatch("< medium"),
          isLarge: select9(import_viewport3.store).isViewportMatch("large"),
          showIconLabels: get("core", "showIconLabels")
        };
      },
      [identifier, scope]
    );
    const isMobileViewport = (0, import_compose24.useViewportMatch)("medium", "<");
    useAdjustComplementaryListener(
      scope,
      identifier,
      activeArea,
      isActive,
      isSmall
    );
    const {
      enableComplementaryArea: enableComplementaryArea2,
      disableComplementaryArea: disableComplementaryArea2,
      pinItem: pinItem2,
      unpinItem: unpinItem2
    } = (0, import_data43.useDispatch)(store3);
    (0, import_element144.useEffect)(() => {
      if (isActiveByDefault && activeArea === void 0 && !isSmall) {
        enableComplementaryArea2(scope, identifier);
      } else if (activeArea === void 0 && isSmall) {
        disableComplementaryArea2(scope, identifier);
      }
      setIsReady2(true);
    }, [
      activeArea,
      isActiveByDefault,
      scope,
      identifier,
      isSmall,
      enableComplementaryArea2,
      disableComplementaryArea2
    ]);
    if (!isReady2) {
      return;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime270.jsxs)(import_jsx_runtime270.Fragment, { children: [
      isPinnable && /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(pinned_items_default, { scope, children: isPinned && /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(
        ComplementaryAreaToggle,
        {
          scope,
          identifier,
          isPressed: isActive && (!showIconLabels || isLarge),
          "aria-expanded": isActive,
          "aria-disabled": isLoading,
          label: title,
          icon: showIconLabels ? check_default : icon,
          showTooltip: !showIconLabels,
          variant: showIconLabels ? "tertiary" : void 0,
          size: "compact",
          shortcut: toggleShortcut
        }
      ) }),
      name2 && isPinnable && /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(
        ComplementaryAreaMoreMenuItem,
        {
          target: name2,
          scope,
          icon,
          identifier,
          children: title
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime270.jsxs)(
        ComplementaryAreaFill,
        {
          activeArea,
          isActive,
          className: clsx_default("interface-complementary-area", className),
          scope,
          id: identifier.replace("/", ":"),
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(
              complementary_area_header_default,
              {
                className: headerClassName,
                closeLabel,
                onClose: () => disableComplementaryArea2(scope),
                toggleButtonProps: {
                  label: closeLabel,
                  size: "compact",
                  shortcut: toggleShortcut,
                  scope,
                  identifier
                },
                children: header || /* @__PURE__ */ (0, import_jsx_runtime270.jsxs)(import_jsx_runtime270.Fragment, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime270.jsx)("h2", { className: "interface-complementary-area-header__title", children: title }),
                  isPinnable && !isMobileViewport && /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(
                    import_components84.Button,
                    {
                      className: "interface-complementary-area__pin-unpin-item",
                      icon: isPinned ? star_filled_default : star_empty_default,
                      label: isPinned ? (0, import_i18n129.__)("Unpin from toolbar") : (0, import_i18n129.__)("Pin to toolbar"),
                      onClick: () => (isPinned ? unpinItem2 : pinItem2)(
                        scope,
                        identifier
                      ),
                      isPressed: isPinned,
                      "aria-expanded": isPinned,
                      size: "compact"
                    }
                  )
                ] })
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime270.jsx)(import_components84.Panel, { className: panelClassName, children })
          ]
        }
      )
    ] });
  }
  ComplementaryArea.Slot = ComplementaryAreaSlot;
  var complementary_area_default = ComplementaryArea;

  // packages/interface/build-module/components/fullscreen-mode/index.mjs
  var import_element145 = __toESM(require_element(), 1);
  var FullscreenMode = ({ isActive }) => {
    (0, import_element145.useEffect)(() => {
      let isSticky = false;
      if (document.body.classList.contains("sticky-menu")) {
        isSticky = true;
        document.body.classList.remove("sticky-menu");
      }
      return () => {
        if (isSticky) {
          document.body.classList.add("sticky-menu");
        }
      };
    }, []);
    (0, import_element145.useEffect)(() => {
      if (isActive) {
        document.body.classList.add("is-fullscreen-mode");
      } else {
        document.body.classList.remove("is-fullscreen-mode");
      }
      return () => {
        if (isActive) {
          document.body.classList.remove("is-fullscreen-mode");
        }
      };
    }, [isActive]);
    return null;
  };
  var fullscreen_mode_default = FullscreenMode;

  // packages/admin-ui/build-module/navigable-region/index.mjs
  var import_element146 = __toESM(require_element(), 1);
  var import_jsx_runtime271 = __toESM(require_jsx_runtime(), 1);
  var NavigableRegion = (0, import_element146.forwardRef)(
    ({ children, className, ariaLabel, as: Tag = "div", ...props }, ref) => {
      return /* @__PURE__ */ (0, import_jsx_runtime271.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/interface/build-module/components/interface-skeleton/index.mjs
  var import_element147 = __toESM(require_element(), 1);
  var import_components85 = __toESM(require_components(), 1);
  var import_i18n130 = __toESM(require_i18n(), 1);
  var import_compose25 = __toESM(require_compose(), 1);
  var import_jsx_runtime272 = __toESM(require_jsx_runtime(), 1);
  var ANIMATION_DURATION2 = 0.25;
  var commonTransition = {
    type: "tween",
    duration: ANIMATION_DURATION2,
    ease: [0.6, 0, 0.4, 1]
  };
  function useHTMLClass(className) {
    (0, import_element147.useEffect)(() => {
      const element = document && document.querySelector(`html:not(.${className})`);
      if (!element) {
        return;
      }
      element.classList.toggle(className);
      return () => {
        element.classList.toggle(className);
      };
    }, [className]);
  }
  var headerVariants = {
    hidden: { opacity: 1, marginTop: -60 },
    visible: { opacity: 1, marginTop: 0 },
    distractionFreeHover: {
      opacity: 1,
      marginTop: 0,
      transition: {
        ...commonTransition,
        delay: 0.2,
        delayChildren: 0.2
      }
    },
    distractionFreeHidden: {
      opacity: 0,
      marginTop: -60
    },
    distractionFreeDisabled: {
      opacity: 0,
      marginTop: 0,
      transition: {
        ...commonTransition,
        delay: 0.8,
        delayChildren: 0.8
      }
    }
  };
  function InterfaceSkeleton({
    isDistractionFree,
    footer,
    header,
    editorNotices,
    sidebar,
    secondarySidebar,
    content,
    actions: actions2,
    labels,
    className
  }, ref) {
    const [secondarySidebarResizeListener, secondarySidebarSize] = (0, import_compose25.useResizeObserver)();
    const isMobileViewport = (0, import_compose25.useViewportMatch)("medium", "<");
    const disableMotion = (0, import_compose25.useReducedMotion)();
    const defaultTransition = {
      type: "tween",
      duration: disableMotion ? 0 : ANIMATION_DURATION2,
      ease: [0.6, 0, 0.4, 1]
    };
    useHTMLClass("interface-interface-skeleton__html-container");
    const defaultLabels = {
      /* translators: accessibility text for the top bar landmark region. */
      header: (0, import_i18n130._x)("Header", "header landmark area"),
      /* translators: accessibility text for the content landmark region. */
      body: (0, import_i18n130.__)("Content"),
      /* translators: accessibility text for the secondary sidebar landmark region. */
      secondarySidebar: (0, import_i18n130.__)("Block Library"),
      /* translators: accessibility text for the settings landmark region. */
      sidebar: (0, import_i18n130._x)("Settings", "settings landmark area"),
      /* translators: accessibility text for the publish landmark region. */
      actions: (0, import_i18n130.__)("Publish"),
      /* translators: accessibility text for the footer landmark region. */
      footer: (0, import_i18n130.__)("Footer")
    };
    const mergedLabels = { ...defaultLabels, ...labels };
    return /* @__PURE__ */ (0, import_jsx_runtime272.jsxs)(
      "div",
      {
        ref,
        className: clsx_default(
          className,
          "interface-interface-skeleton",
          !!footer && "has-footer"
        ),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime272.jsxs)("div", { className: "interface-interface-skeleton__editor", children: [
            /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(import_components85.__unstableAnimatePresence, { initial: false, children: !!header && /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(
              navigable_region_default,
              {
                as: import_components85.__unstableMotion.div,
                className: "interface-interface-skeleton__header",
                ariaLabel: mergedLabels.header,
                initial: isDistractionFree && !isMobileViewport ? "distractionFreeHidden" : "hidden",
                whileHover: isDistractionFree && !isMobileViewport ? "distractionFreeHover" : "visible",
                animate: isDistractionFree && !isMobileViewport ? "distractionFreeDisabled" : "visible",
                exit: isDistractionFree && !isMobileViewport ? "distractionFreeHidden" : "hidden",
                variants: headerVariants,
                transition: defaultTransition,
                children: header
              }
            ) }),
            isDistractionFree && /* @__PURE__ */ (0, import_jsx_runtime272.jsx)("div", { className: "interface-interface-skeleton__header", children: editorNotices }),
            /* @__PURE__ */ (0, import_jsx_runtime272.jsxs)("div", { className: "interface-interface-skeleton__body", children: [
              /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(import_components85.__unstableAnimatePresence, { initial: false, children: !!secondarySidebar && /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(
                navigable_region_default,
                {
                  className: "interface-interface-skeleton__secondary-sidebar",
                  ariaLabel: mergedLabels.secondarySidebar,
                  as: import_components85.__unstableMotion.div,
                  initial: "closed",
                  animate: "open",
                  exit: "closed",
                  variants: {
                    open: { width: secondarySidebarSize.width },
                    closed: { width: 0 }
                  },
                  transition: defaultTransition,
                  children: /* @__PURE__ */ (0, import_jsx_runtime272.jsxs)(
                    import_components85.__unstableMotion.div,
                    {
                      style: {
                        position: "absolute",
                        width: isMobileViewport ? "100vw" : "fit-content",
                        height: "100%",
                        left: 0
                      },
                      variants: {
                        open: { x: 0 },
                        closed: { x: "-100%" }
                      },
                      transition: defaultTransition,
                      children: [
                        secondarySidebarResizeListener,
                        secondarySidebar
                      ]
                    }
                  )
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(
                navigable_region_default,
                {
                  className: "interface-interface-skeleton__content",
                  ariaLabel: mergedLabels.body,
                  children: content
                }
              ),
              !!sidebar && /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(
                navigable_region_default,
                {
                  className: "interface-interface-skeleton__sidebar",
                  ariaLabel: mergedLabels.sidebar,
                  children: sidebar
                }
              ),
              !!actions2 && /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(
                navigable_region_default,
                {
                  className: "interface-interface-skeleton__actions",
                  ariaLabel: mergedLabels.actions,
                  children: actions2
                }
              )
            ] })
          ] }),
          !!footer && /* @__PURE__ */ (0, import_jsx_runtime272.jsx)(
            navigable_region_default,
            {
              className: "interface-interface-skeleton__footer",
              ariaLabel: mergedLabels.footer,
              children: footer
            }
          )
        ]
      }
    );
  }
  var interface_skeleton_default = (0, import_element147.forwardRef)(InterfaceSkeleton);

  // packages/media-editor/build-module/components/media-editor-canvas/index.mjs
  var import_element158 = __toESM(require_element(), 1);
  var import_components87 = __toESM(require_components(), 1);
  var import_i18n135 = __toESM(require_i18n(), 1);

  // packages/media-editor/build-module/image-editor/core/constants.mjs
  var import_i18n131 = __toESM(require_i18n(), 1);
  var MIN_ZOOM = 1;
  var ABSOLUTE_MIN_ZOOM = 0.1;
  var MAX_ZOOM = 10;
  var MIN_CROP_PIXELS = 16;
  var MIN_CROP_SCREEN_PX = 44;
  var SETTLE_TARGET_CANVAS_FILL = 0.8;
  var MAX_VIEW_SCALE = 8;
  var PIXEL_SNAP_DISPLAY_SCALE = 1;
  var DEFAULT_WHEEL_ZOOM_SPEED = 25e-4;
  var DEFAULT_KEYBOARD_STEP = 0.01;
  var KEYBOARD_SHIFT_STEP_MULTIPLIER = 10;
  var MAX_ROTATION_OFFSET = 45;
  var DEFAULT_CROP_RECT = {
    x: 0,
    y: 0,
    width: 1,
    height: 1
  };
  var DEFAULT_FLIP = {
    horizontal: false,
    vertical: false
  };
  var DEFAULT_PAN = {
    x: 0,
    y: 0
  };
  var DEFAULT_STATE2 = {
    image: null,
    pan: { ...DEFAULT_PAN },
    zoom: MIN_ZOOM,
    rotation: 0,
    basePan: { ...DEFAULT_PAN },
    baseZoom: MIN_ZOOM,
    baseRotation: 0,
    flip: { ...DEFAULT_FLIP },
    cropRect: { ...DEFAULT_CROP_RECT }
  };
  var ORIGINAL_ASPECT_RATIO = -1;
  var DEFAULT_ASPECT_RATIOS = [
    { label: (0, import_i18n131.__)("Free"), value: 0 },
    { label: (0, import_i18n131.__)("Original"), value: ORIGINAL_ASPECT_RATIO },
    { label: (0, import_i18n131.__)("Square (1:1)"), value: 1 },
    { label: (0, import_i18n131.__)("Landscape (16:9)"), value: 16 / 9 },
    { label: (0, import_i18n131.__)("Portrait (9:16)"), value: 9 / 16 },
    { label: (0, import_i18n131.__)("Classic (4:3)"), value: 4 / 3 },
    { label: (0, import_i18n131.__)("Classic portrait (3:4)"), value: 3 / 4 },
    { label: (0, import_i18n131.__)("Photo (3:2)"), value: 3 / 2 },
    { label: (0, import_i18n131.__)("Photo portrait (2:3)"), value: 2 / 3 }
  ];

  // node_modules/gl-matrix/esm/common.js
  var EPSILON = 1e-6;
  var ARRAY_TYPE = typeof Float32Array !== "undefined" ? Float32Array : Array;
  var RANDOM = Math.random;
  function round2(a3) {
    if (a3 >= 0) return Math.round(a3);
    return a3 % 0.5 === 0 ? Math.floor(a3) : Math.round(a3);
  }
  var degree = Math.PI / 180;
  var radian = 180 / Math.PI;

  // node_modules/gl-matrix/esm/mat2d.js
  var mat2d_exports = {};
  __export(mat2d_exports, {
    add: () => add,
    clone: () => clone,
    copy: () => copy,
    create: () => create,
    determinant: () => determinant,
    equals: () => equals,
    exactEquals: () => exactEquals,
    frob: () => frob,
    fromRotation: () => fromRotation,
    fromScaling: () => fromScaling,
    fromTranslation: () => fromTranslation,
    fromValues: () => fromValues,
    identity: () => identity2,
    invert: () => invert,
    mul: () => mul,
    multiply: () => multiply,
    multiplyScalar: () => multiplyScalar,
    multiplyScalarAndAdd: () => multiplyScalarAndAdd,
    rotate: () => rotate,
    scale: () => scale,
    set: () => set3,
    str: () => str,
    sub: () => sub,
    subtract: () => subtract,
    translate: () => translate
  });
  function create() {
    var out = new ARRAY_TYPE(6);
    if (ARRAY_TYPE != Float32Array) {
      out[1] = 0;
      out[2] = 0;
      out[4] = 0;
      out[5] = 0;
    }
    out[0] = 1;
    out[3] = 1;
    return out;
  }
  function clone(a3) {
    var out = new ARRAY_TYPE(6);
    out[0] = a3[0];
    out[1] = a3[1];
    out[2] = a3[2];
    out[3] = a3[3];
    out[4] = a3[4];
    out[5] = a3[5];
    return out;
  }
  function copy(out, a3) {
    out[0] = a3[0];
    out[1] = a3[1];
    out[2] = a3[2];
    out[3] = a3[3];
    out[4] = a3[4];
    out[5] = a3[5];
    return out;
  }
  function identity2(out) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 1;
    out[4] = 0;
    out[5] = 0;
    return out;
  }
  function fromValues(a3, b3, c6, d3, tx, ty) {
    var out = new ARRAY_TYPE(6);
    out[0] = a3;
    out[1] = b3;
    out[2] = c6;
    out[3] = d3;
    out[4] = tx;
    out[5] = ty;
    return out;
  }
  function set3(out, a3, b3, c6, d3, tx, ty) {
    out[0] = a3;
    out[1] = b3;
    out[2] = c6;
    out[3] = d3;
    out[4] = tx;
    out[5] = ty;
    return out;
  }
  function invert(out, a3) {
    var aa = a3[0], ab = a3[1], ac = a3[2], ad = a3[3];
    var atx = a3[4], aty = a3[5];
    var det = aa * ad - ab * ac;
    if (!det) {
      return null;
    }
    det = 1 / det;
    out[0] = ad * det;
    out[1] = -ab * det;
    out[2] = -ac * det;
    out[3] = aa * det;
    out[4] = (ac * aty - ad * atx) * det;
    out[5] = (ab * atx - aa * aty) * det;
    return out;
  }
  function determinant(a3) {
    return a3[0] * a3[3] - a3[1] * a3[2];
  }
  function multiply(out, a3, b3) {
    var a0 = a3[0], a1 = a3[1], a22 = a3[2], a32 = a3[3], a4 = a3[4], a5 = a3[5];
    var b0 = b3[0], b1 = b3[1], b22 = b3[2], b32 = b3[3], b4 = b3[4], b5 = b3[5];
    out[0] = a0 * b0 + a22 * b1;
    out[1] = a1 * b0 + a32 * b1;
    out[2] = a0 * b22 + a22 * b32;
    out[3] = a1 * b22 + a32 * b32;
    out[4] = a0 * b4 + a22 * b5 + a4;
    out[5] = a1 * b4 + a32 * b5 + a5;
    return out;
  }
  function rotate(out, a3, rad) {
    var a0 = a3[0], a1 = a3[1], a22 = a3[2], a32 = a3[3], a4 = a3[4], a5 = a3[5];
    var s3 = Math.sin(rad);
    var c6 = Math.cos(rad);
    out[0] = a0 * c6 + a22 * s3;
    out[1] = a1 * c6 + a32 * s3;
    out[2] = a0 * -s3 + a22 * c6;
    out[3] = a1 * -s3 + a32 * c6;
    out[4] = a4;
    out[5] = a5;
    return out;
  }
  function scale(out, a3, v3) {
    var a0 = a3[0], a1 = a3[1], a22 = a3[2], a32 = a3[3], a4 = a3[4], a5 = a3[5];
    var v0 = v3[0], v1 = v3[1];
    out[0] = a0 * v0;
    out[1] = a1 * v0;
    out[2] = a22 * v1;
    out[3] = a32 * v1;
    out[4] = a4;
    out[5] = a5;
    return out;
  }
  function translate(out, a3, v3) {
    var a0 = a3[0], a1 = a3[1], a22 = a3[2], a32 = a3[3], a4 = a3[4], a5 = a3[5];
    var v0 = v3[0], v1 = v3[1];
    out[0] = a0;
    out[1] = a1;
    out[2] = a22;
    out[3] = a32;
    out[4] = a0 * v0 + a22 * v1 + a4;
    out[5] = a1 * v0 + a32 * v1 + a5;
    return out;
  }
  function fromRotation(out, rad) {
    var s3 = Math.sin(rad), c6 = Math.cos(rad);
    out[0] = c6;
    out[1] = s3;
    out[2] = -s3;
    out[3] = c6;
    out[4] = 0;
    out[5] = 0;
    return out;
  }
  function fromScaling(out, v3) {
    out[0] = v3[0];
    out[1] = 0;
    out[2] = 0;
    out[3] = v3[1];
    out[4] = 0;
    out[5] = 0;
    return out;
  }
  function fromTranslation(out, v3) {
    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 1;
    out[4] = v3[0];
    out[5] = v3[1];
    return out;
  }
  function str(a3) {
    return "mat2d(" + a3[0] + ", " + a3[1] + ", " + a3[2] + ", " + a3[3] + ", " + a3[4] + ", " + a3[5] + ")";
  }
  function frob(a3) {
    return Math.sqrt(a3[0] * a3[0] + a3[1] * a3[1] + a3[2] * a3[2] + a3[3] * a3[3] + a3[4] * a3[4] + a3[5] * a3[5] + 1);
  }
  function add(out, a3, b3) {
    out[0] = a3[0] + b3[0];
    out[1] = a3[1] + b3[1];
    out[2] = a3[2] + b3[2];
    out[3] = a3[3] + b3[3];
    out[4] = a3[4] + b3[4];
    out[5] = a3[5] + b3[5];
    return out;
  }
  function subtract(out, a3, b3) {
    out[0] = a3[0] - b3[0];
    out[1] = a3[1] - b3[1];
    out[2] = a3[2] - b3[2];
    out[3] = a3[3] - b3[3];
    out[4] = a3[4] - b3[4];
    out[5] = a3[5] - b3[5];
    return out;
  }
  function multiplyScalar(out, a3, b3) {
    out[0] = a3[0] * b3;
    out[1] = a3[1] * b3;
    out[2] = a3[2] * b3;
    out[3] = a3[3] * b3;
    out[4] = a3[4] * b3;
    out[5] = a3[5] * b3;
    return out;
  }
  function multiplyScalarAndAdd(out, a3, b3, scale3) {
    out[0] = a3[0] + b3[0] * scale3;
    out[1] = a3[1] + b3[1] * scale3;
    out[2] = a3[2] + b3[2] * scale3;
    out[3] = a3[3] + b3[3] * scale3;
    out[4] = a3[4] + b3[4] * scale3;
    out[5] = a3[5] + b3[5] * scale3;
    return out;
  }
  function exactEquals(a3, b3) {
    return a3[0] === b3[0] && a3[1] === b3[1] && a3[2] === b3[2] && a3[3] === b3[3] && a3[4] === b3[4] && a3[5] === b3[5];
  }
  function equals(a3, b3) {
    var a0 = a3[0], a1 = a3[1], a22 = a3[2], a32 = a3[3], a4 = a3[4], a5 = a3[5];
    var b0 = b3[0], b1 = b3[1], b22 = b3[2], b32 = b3[3], b4 = b3[4], b5 = b3[5];
    return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a22 - b22) <= EPSILON * Math.max(1, Math.abs(a22), Math.abs(b22)) && Math.abs(a32 - b32) <= EPSILON * Math.max(1, Math.abs(a32), Math.abs(b32)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5));
  }
  var mul = multiply;
  var sub = subtract;

  // node_modules/gl-matrix/esm/vec2.js
  var vec2_exports = {};
  __export(vec2_exports, {
    add: () => add2,
    angle: () => angle,
    ceil: () => ceil,
    clone: () => clone2,
    copy: () => copy2,
    create: () => create2,
    cross: () => cross,
    dist: () => dist,
    distance: () => distance,
    div: () => div,
    divide: () => divide,
    dot: () => dot,
    equals: () => equals2,
    exactEquals: () => exactEquals2,
    floor: () => floor2,
    forEach: () => forEach,
    fromValues: () => fromValues2,
    inverse: () => inverse,
    len: () => len,
    length: () => length,
    lerp: () => lerp,
    max: () => max2,
    min: () => min2,
    mul: () => mul2,
    multiply: () => multiply2,
    negate: () => negate,
    normalize: () => normalize,
    random: () => random,
    rotate: () => rotate2,
    round: () => round3,
    scale: () => scale2,
    scaleAndAdd: () => scaleAndAdd,
    set: () => set4,
    signedAngle: () => signedAngle,
    sqrDist: () => sqrDist,
    sqrLen: () => sqrLen,
    squaredDistance: () => squaredDistance,
    squaredLength: () => squaredLength,
    str: () => str2,
    sub: () => sub2,
    subtract: () => subtract2,
    transformMat2: () => transformMat2,
    transformMat2d: () => transformMat2d,
    transformMat3: () => transformMat3,
    transformMat4: () => transformMat4,
    zero: () => zero
  });
  function create2() {
    var out = new ARRAY_TYPE(2);
    if (ARRAY_TYPE != Float32Array) {
      out[0] = 0;
      out[1] = 0;
    }
    return out;
  }
  function clone2(a3) {
    var out = new ARRAY_TYPE(2);
    out[0] = a3[0];
    out[1] = a3[1];
    return out;
  }
  function fromValues2(x2, y3) {
    var out = new ARRAY_TYPE(2);
    out[0] = x2;
    out[1] = y3;
    return out;
  }
  function copy2(out, a3) {
    out[0] = a3[0];
    out[1] = a3[1];
    return out;
  }
  function set4(out, x2, y3) {
    out[0] = x2;
    out[1] = y3;
    return out;
  }
  function add2(out, a3, b3) {
    out[0] = a3[0] + b3[0];
    out[1] = a3[1] + b3[1];
    return out;
  }
  function subtract2(out, a3, b3) {
    out[0] = a3[0] - b3[0];
    out[1] = a3[1] - b3[1];
    return out;
  }
  function multiply2(out, a3, b3) {
    out[0] = a3[0] * b3[0];
    out[1] = a3[1] * b3[1];
    return out;
  }
  function divide(out, a3, b3) {
    out[0] = a3[0] / b3[0];
    out[1] = a3[1] / b3[1];
    return out;
  }
  function ceil(out, a3) {
    out[0] = Math.ceil(a3[0]);
    out[1] = Math.ceil(a3[1]);
    return out;
  }
  function floor2(out, a3) {
    out[0] = Math.floor(a3[0]);
    out[1] = Math.floor(a3[1]);
    return out;
  }
  function min2(out, a3, b3) {
    out[0] = Math.min(a3[0], b3[0]);
    out[1] = Math.min(a3[1], b3[1]);
    return out;
  }
  function max2(out, a3, b3) {
    out[0] = Math.max(a3[0], b3[0]);
    out[1] = Math.max(a3[1], b3[1]);
    return out;
  }
  function round3(out, a3) {
    out[0] = round2(a3[0]);
    out[1] = round2(a3[1]);
    return out;
  }
  function scale2(out, a3, b3) {
    out[0] = a3[0] * b3;
    out[1] = a3[1] * b3;
    return out;
  }
  function scaleAndAdd(out, a3, b3, scale3) {
    out[0] = a3[0] + b3[0] * scale3;
    out[1] = a3[1] + b3[1] * scale3;
    return out;
  }
  function distance(a3, b3) {
    var x2 = b3[0] - a3[0], y3 = b3[1] - a3[1];
    return Math.sqrt(x2 * x2 + y3 * y3);
  }
  function squaredDistance(a3, b3) {
    var x2 = b3[0] - a3[0], y3 = b3[1] - a3[1];
    return x2 * x2 + y3 * y3;
  }
  function length(a3) {
    var x2 = a3[0], y3 = a3[1];
    return Math.sqrt(x2 * x2 + y3 * y3);
  }
  function squaredLength(a3) {
    var x2 = a3[0], y3 = a3[1];
    return x2 * x2 + y3 * y3;
  }
  function negate(out, a3) {
    out[0] = -a3[0];
    out[1] = -a3[1];
    return out;
  }
  function inverse(out, a3) {
    out[0] = 1 / a3[0];
    out[1] = 1 / a3[1];
    return out;
  }
  function normalize(out, a3) {
    var x2 = a3[0], y3 = a3[1];
    var len2 = x2 * x2 + y3 * y3;
    if (len2 > 0) {
      len2 = 1 / Math.sqrt(len2);
    }
    out[0] = a3[0] * len2;
    out[1] = a3[1] * len2;
    return out;
  }
  function dot(a3, b3) {
    return a3[0] * b3[0] + a3[1] * b3[1];
  }
  function cross(out, a3, b3) {
    var z = a3[0] * b3[1] - a3[1] * b3[0];
    out[0] = out[1] = 0;
    out[2] = z;
    return out;
  }
  function lerp(out, a3, b3, t4) {
    var ax = a3[0], ay = a3[1];
    out[0] = ax + t4 * (b3[0] - ax);
    out[1] = ay + t4 * (b3[1] - ay);
    return out;
  }
  function random(out, scale3) {
    scale3 = scale3 === void 0 ? 1 : scale3;
    var r4 = RANDOM() * 2 * Math.PI;
    out[0] = Math.cos(r4) * scale3;
    out[1] = Math.sin(r4) * scale3;
    return out;
  }
  function transformMat2(out, a3, m2) {
    var x2 = a3[0], y3 = a3[1];
    out[0] = m2[0] * x2 + m2[2] * y3;
    out[1] = m2[1] * x2 + m2[3] * y3;
    return out;
  }
  function transformMat2d(out, a3, m2) {
    var x2 = a3[0], y3 = a3[1];
    out[0] = m2[0] * x2 + m2[2] * y3 + m2[4];
    out[1] = m2[1] * x2 + m2[3] * y3 + m2[5];
    return out;
  }
  function transformMat3(out, a3, m2) {
    var x2 = a3[0], y3 = a3[1];
    out[0] = m2[0] * x2 + m2[3] * y3 + m2[6];
    out[1] = m2[1] * x2 + m2[4] * y3 + m2[7];
    return out;
  }
  function transformMat4(out, a3, m2) {
    var x2 = a3[0];
    var y3 = a3[1];
    out[0] = m2[0] * x2 + m2[4] * y3 + m2[12];
    out[1] = m2[1] * x2 + m2[5] * y3 + m2[13];
    return out;
  }
  function rotate2(out, a3, b3, rad) {
    var p0 = a3[0] - b3[0], p1 = a3[1] - b3[1], sinC = Math.sin(rad), cosC = Math.cos(rad);
    out[0] = p0 * cosC - p1 * sinC + b3[0];
    out[1] = p0 * sinC + p1 * cosC + b3[1];
    return out;
  }
  function angle(a3, b3) {
    var ax = a3[0], ay = a3[1], bx = b3[0], by = b3[1];
    return Math.abs(Math.atan2(ay * bx - ax * by, ax * bx + ay * by));
  }
  function signedAngle(a3, b3) {
    var ax = a3[0], ay = a3[1], bx = b3[0], by = b3[1];
    return Math.atan2(ax * by - ay * bx, ax * bx + ay * by);
  }
  function zero(out) {
    out[0] = 0;
    out[1] = 0;
    return out;
  }
  function str2(a3) {
    return "vec2(" + a3[0] + ", " + a3[1] + ")";
  }
  function exactEquals2(a3, b3) {
    return a3[0] === b3[0] && a3[1] === b3[1];
  }
  function equals2(a3, b3) {
    var a0 = a3[0], a1 = a3[1];
    var b0 = b3[0], b1 = b3[1];
    return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1));
  }
  var len = length;
  var sub2 = subtract2;
  var mul2 = multiply2;
  var div = divide;
  var dist = distance;
  var sqrDist = squaredDistance;
  var sqrLen = squaredLength;
  var forEach = (function() {
    var vec = create2();
    return function(a3, stride, offset4, count, fn, arg) {
      var i3, l3;
      if (!stride) {
        stride = 2;
      }
      if (!offset4) {
        offset4 = 0;
      }
      if (count) {
        l3 = Math.min(count * stride + offset4, a3.length);
      } else {
        l3 = a3.length;
      }
      for (i3 = offset4; i3 < l3; i3 += stride) {
        vec[0] = a3[i3];
        vec[1] = a3[i3 + 1];
        fn(vec, vec, arg);
        a3[i3] = vec[0];
        a3[i3 + 1] = vec[1];
      }
      return a3;
    };
  })();

  // packages/media-editor/build-module/image-editor/core/math/rotation.mjs
  function normalizeRotation(degrees) {
    if (degrees >= 0) {
      return degrees % 360;
    }
    return (360 + degrees % 360) % 360;
  }
  function degreesToRadians(degrees) {
    return degrees * Math.PI / 180;
  }

  // packages/media-editor/build-module/image-editor/core/math/sanitize.mjs
  var MAX_SAFE_MAGNITUDE = 1e6;
  function safeBoundedNumber(value, fallback) {
    if (!Number.isFinite(value)) {
      return fallback;
    }
    if (Math.abs(value) > MAX_SAFE_MAGNITUDE) {
      return fallback;
    }
    return value;
  }
  function isSafeNumber(value) {
    return Number.isFinite(value) && Math.abs(value) <= MAX_SAFE_MAGNITUDE;
  }
  function isValidSize(size4) {
    return Number.isFinite(size4.width) && Number.isFinite(size4.height) && size4.width >= Number.EPSILON && size4.height >= Number.EPSILON && size4.width <= MAX_SAFE_MAGNITUDE && size4.height <= MAX_SAFE_MAGNITUDE;
  }
  function sanitizeRect(rect) {
    const x2 = safeBoundedNumber(rect.x, 0);
    const y3 = safeBoundedNumber(rect.y, 0);
    const width = safeBoundedNumber(rect.width, 0);
    const height = safeBoundedNumber(rect.height, 0);
    if (x2 === rect.x && y3 === rect.y && width === rect.width && height === rect.height) {
      return rect;
    }
    return { x: x2, y: y3, width, height };
  }
  function sanitizeCropperState(state2) {
    const panX = safeBoundedNumber(state2.pan.x, 0);
    const panY = safeBoundedNumber(state2.pan.y, 0);
    const basePanX = safeBoundedNumber(state2.basePan.x, 0);
    const basePanY = safeBoundedNumber(state2.basePan.y, 0);
    const rotation = safeBoundedNumber(state2.rotation, 0);
    const baseRotation = safeBoundedNumber(state2.baseRotation, 0);
    const rawZoom = safeBoundedNumber(state2.zoom, 1);
    const zoom = rawZoom >= Number.EPSILON ? rawZoom : 1;
    const rawBaseZoom = safeBoundedNumber(state2.baseZoom, 1);
    const baseZoom = rawBaseZoom >= Number.EPSILON ? rawBaseZoom : 1;
    const cropRect = sanitizeRect(state2.cropRect);
    const panUnchanged = panX === state2.pan.x && panY === state2.pan.y;
    const basePanUnchanged = basePanX === state2.basePan.x && basePanY === state2.basePan.y;
    if (panUnchanged && basePanUnchanged && zoom === state2.zoom && baseZoom === state2.baseZoom && rotation === state2.rotation && baseRotation === state2.baseRotation && cropRect === state2.cropRect) {
      return state2;
    }
    return {
      ...state2,
      pan: panUnchanged ? state2.pan : { x: panX, y: panY },
      zoom,
      rotation,
      basePan: basePanUnchanged ? state2.basePan : { x: basePanX, y: basePanY },
      baseZoom,
      baseRotation,
      cropRect
    };
  }

  // packages/media-editor/build-module/image-editor/core/camera.mjs
  var _scratchMat = mat2d_exports.create();
  var _scratchVec = vec2_exports.create();
  function getRotatedBBox(width, height, rotation) {
    if (!isSafeNumber(width) || !isSafeNumber(height) || !isSafeNumber(rotation) || width <= 0 || height <= 0) {
      return { width: 0, height: 0 };
    }
    const rad = degreesToRadians(rotation);
    const cosR = Math.abs(Math.cos(rad));
    const sinR = Math.abs(Math.sin(rad));
    return {
      width: cosR * width + sinR * height,
      height: sinR * width + cosR * height
    };
  }
  function getImageFit(containerSize, imageSize, rotation) {
    if (!isValidSize(containerSize) || !isValidSize(imageSize)) {
      return {
        elementSize: { width: 0, height: 0 },
        visualSize: { width: 0, height: 0 }
      };
    }
    const safeRotation = safeBoundedNumber(rotation, 0);
    const snapRotation = Math.round(safeRotation / 90) * 90;
    const naturalBBox = getRotatedBBox(
      imageSize.width,
      imageSize.height,
      snapRotation
    );
    if (naturalBBox.width === 0 || naturalBBox.height === 0) {
      return {
        elementSize: { width: 0, height: 0 },
        visualSize: { width: 0, height: 0 }
      };
    }
    const fitScale = Math.min(
      containerSize.width / naturalBBox.width,
      containerSize.height / naturalBBox.height
    );
    const renderedW = imageSize.width * fitScale;
    const renderedH = imageSize.height * fitScale;
    const visualSize = getRotatedBBox(renderedW, renderedH, snapRotation);
    return {
      elementSize: { width: renderedW, height: renderedH },
      visualSize
    };
  }
  function getViewScale(cropRect, canvasSize, visualSize, targetFill, maxScale) {
    const cropScreenW = cropRect.width * visualSize.width;
    const cropScreenH = cropRect.height * visualSize.height;
    if (!isValidSize(canvasSize) || !isValidSize(visualSize) || !(cropScreenW > 0) || !(cropScreenH > 0) || !Number.isFinite(targetFill) || !Number.isFinite(maxScale) || !(targetFill > 0) || !(maxScale >= 1)) {
      return 1;
    }
    const kW = targetFill * canvasSize.width / cropScreenW;
    const kH = targetFill * canvasSize.height / cropScreenH;
    const k2 = Math.min(kW, kH);
    return Math.min(maxScale, Math.max(1, k2));
  }
  function createCamera(state2, containerSize, imageSize) {
    const m2 = mat2d_exports.create();
    if (!isValidSize(containerSize) || !isValidSize(imageSize)) {
      return m2;
    }
    const safeState = sanitizeCropperState(state2);
    const snapRotation = Math.round(safeState.rotation / 90) * 90;
    const naturalBBox = getRotatedBBox(
      imageSize.width,
      imageSize.height,
      snapRotation
    );
    if (naturalBBox.width === 0 || naturalBBox.height === 0) {
      return m2;
    }
    const fitScale = Math.min(
      containerSize.width / naturalBBox.width,
      containerSize.height / naturalBBox.height
    );
    const renderedW = imageSize.width * fitScale;
    const renderedH = imageSize.height * fitScale;
    const { width: visualW, height: visualH } = getRotatedBBox(
      renderedW,
      renderedH,
      snapRotation
    );
    mat2d_exports.translate(m2, m2, [
      containerSize.width / 2,
      containerSize.height / 2
    ]);
    mat2d_exports.translate(m2, m2, [
      safeState.pan.x * visualW,
      safeState.pan.y * visualH
    ]);
    mat2d_exports.scale(m2, m2, [
      safeState.flip.horizontal ? -1 : 1,
      safeState.flip.vertical ? -1 : 1
    ]);
    mat2d_exports.rotate(m2, m2, degreesToRadians(safeState.rotation));
    mat2d_exports.scale(m2, m2, [safeState.zoom, safeState.zoom]);
    mat2d_exports.translate(m2, m2, [-renderedW / 2, -renderedH / 2]);
    mat2d_exports.scale(m2, m2, [renderedW, renderedH]);
    return m2;
  }
  function aabb(camera, corners) {
    const screenCorners = corners.map((c6) => {
      const out = vec2_exports.create();
      vec2_exports.transformMat2d(out, c6, camera);
      return out;
    });
    let minX = screenCorners[0][0];
    let maxX = screenCorners[0][0];
    let minY = screenCorners[0][1];
    let maxY = screenCorners[0][1];
    for (let i3 = 1; i3 < screenCorners.length; i3++) {
      const s3 = screenCorners[i3];
      if (s3[0] < minX) {
        minX = s3[0];
      }
      if (s3[0] > maxX) {
        maxX = s3[0];
      }
      if (s3[1] < minY) {
        minY = s3[1];
      }
      if (s3[1] > maxY) {
        maxY = s3[1];
      }
    }
    return { left: minX, top: minY, width: maxX - minX, height: maxY - minY };
  }
  function getVisibleBounds(camera) {
    return aabb(camera, [
      [0, 0],
      [1, 0],
      [1, 1],
      [0, 1]
    ]);
  }
  function createExportCamera(state2, imageSize, outputSize) {
    const m2 = mat2d_exports.create();
    if (!isValidSize(imageSize) || !isValidSize(outputSize)) {
      return m2;
    }
    const { rotation, flip: flip4, cropRect, zoom, pan } = sanitizeCropperState(state2);
    const snapRotation = Math.round(rotation / 90) * 90;
    const { width: rotW, height: rotH } = getRotatedBBox(
      imageSize.width,
      imageSize.height,
      snapRotation
    );
    const naturalCropW = cropRect.width * rotW;
    const naturalCropH = cropRect.height * rotH;
    const outputScaleX = naturalCropW > 0 ? outputSize.width / naturalCropW : 1;
    const outputScaleY = naturalCropH > 0 ? outputSize.height / naturalCropH : 1;
    const cropOffsetX = cropRect.x * rotW + outputSize.width / 2 / outputScaleX;
    const cropOffsetY = cropRect.y * rotH + outputSize.height / 2 / outputScaleY;
    const visualCenterX = rotW / 2 + pan.x * rotW;
    const visualCenterY = rotH / 2 + pan.y * rotH;
    mat2d_exports.scale(m2, m2, [outputScaleX, outputScaleY]);
    mat2d_exports.translate(m2, m2, [
      visualCenterX - cropOffsetX + outputSize.width / 2 / outputScaleX,
      visualCenterY - cropOffsetY + outputSize.height / 2 / outputScaleY
    ]);
    mat2d_exports.scale(m2, m2, [flip4.horizontal ? -1 : 1, flip4.vertical ? -1 : 1]);
    mat2d_exports.rotate(m2, m2, degreesToRadians(rotation));
    mat2d_exports.scale(m2, m2, [zoom, zoom]);
    mat2d_exports.translate(m2, m2, [-imageSize.width / 2, -imageSize.height / 2]);
    return m2;
  }

  // packages/media-editor/build-module/image-editor/core/export/canvas-renderer.mjs
  var DEFAULT_QUALITY = 0.92;
  function loadImage(src) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      image.addEventListener("load", () => resolve(image));
      image.addEventListener("error", (error2) => reject(error2));
      image.crossOrigin = "anonymous";
      image.src = src;
    });
  }
  function renderToCanvas(image, state2) {
    const { naturalWidth, naturalHeight } = image;
    const { rotation, cropRect } = state2;
    const imageSize = { width: naturalWidth, height: naturalHeight };
    const snapRotation = Math.round(rotation / 90) * 90;
    const rotBBox = getRotatedBBox(naturalWidth, naturalHeight, snapRotation);
    const outW = Math.round(cropRect.width * rotBBox.width);
    const outH = Math.round(cropRect.height * rotBBox.height);
    const canvas = document.createElement("canvas");
    canvas.width = outW;
    canvas.height = outH;
    const ctx9 = canvas.getContext("2d");
    if (!ctx9) {
      throw new Error(
        "Could not obtain a 2D context for the export canvas."
      );
    }
    const camera = createExportCamera(state2, imageSize, {
      width: outW,
      height: outH
    });
    ctx9.setTransform(
      camera[0],
      camera[1],
      camera[2],
      camera[3],
      camera[4],
      camera[5]
    );
    ctx9.drawImage(image, 0, 0);
    return canvas;
  }
  function canvasToBlob(canvas, mimeType = "image/png", quality = DEFAULT_QUALITY) {
    return new Promise((resolve, reject) => {
      canvas.toBlob(
        (blob) => {
          if (blob) {
            resolve(blob);
          } else {
            reject(new Error("Canvas toBlob returned null."));
          }
        },
        mimeType,
        quality
      );
    });
  }
  async function exportCroppedImage(src, state2, mimeType = "image/png", quality = DEFAULT_QUALITY) {
    const image = await loadImage(src);
    const canvas = renderToCanvas(image, state2);
    return canvasToBlob(canvas, mimeType, quality);
  }

  // packages/media-editor/build-module/image-editor/core/containment.mjs
  var EPSILON2 = 1e-9;
  function getVisualDimensions(rotation, imageAspectRatio) {
    const rad = degreesToRadians(rotation);
    const absC = Math.abs(Math.cos(rad));
    const absS = Math.abs(Math.sin(rad));
    const bbox = getRotatedBBox(imageAspectRatio, 1, rotation);
    return {
      visualW: bbox.width,
      visualH: bbox.height,
      absC,
      absS
    };
  }
  function getMinZoomForCover(rotation, imageAspectRatio, cropRect) {
    const aspectRatio = Math.max(imageAspectRatio, Number.EPSILON);
    const snapRotation = Math.round(rotation / 90) * 90;
    const { visualW: snapVisualW, visualH: snapVisualH } = getVisualDimensions(
      snapRotation,
      aspectRatio
    );
    const { absC, absS } = getVisualDimensions(rotation, aspectRatio);
    const cropHalfW = cropRect.width * snapVisualW / 2;
    const cropHalfH = cropRect.height * snapVisualH / 2;
    const spanAlpha = cropHalfW * absC + cropHalfH * absS;
    const spanBeta = cropHalfW * absS + cropHalfH * absC;
    const zoomFromAlpha = 2 * spanAlpha / aspectRatio;
    const zoomFromBeta = 2 * spanBeta;
    return Math.max(zoomFromAlpha, zoomFromBeta);
  }
  function getMinZoom(state2) {
    if (!state2.image) {
      return MIN_ZOOM;
    }
    const imageSize = {
      width: state2.image.naturalWidth,
      height: state2.image.naturalHeight
    };
    if (!isValidSize(imageSize)) {
      return MIN_ZOOM;
    }
    const safeState = sanitizeCropperState(state2);
    const aspectRatio = imageSize.width / imageSize.height;
    return Math.max(
      ABSOLUTE_MIN_ZOOM,
      getMinZoomForCover(
        safeState.rotation,
        aspectRatio,
        safeState.cropRect
      )
    );
  }
  function getImageCropBounds(state2, elementSize, visualSize) {
    if (!isValidSize(elementSize) || !isValidSize(visualSize)) {
      return { minX: 0, minY: 0, maxX: 1, maxY: 1 };
    }
    const safeState = sanitizeCropperState(state2);
    const tx = safeState.pan.x * visualSize.width;
    const ty = safeState.pan.y * visualSize.height;
    const rad = degreesToRadians(safeState.rotation);
    const cos = Math.cos(rad);
    const sin = Math.sin(rad);
    const sx = safeState.flip.horizontal ? -1 : 1;
    const sy = safeState.flip.vertical ? -1 : 1;
    const z = safeState.zoom;
    const ma = sx * cos * z;
    const mb = sy * sin * z;
    const mc = -sx * sin * z;
    const md = sy * cos * z;
    const hw = elementSize.width / 2;
    const hh = elementSize.height / 2;
    const corners = [
      [-hw, -hh],
      [hw, -hh],
      [hw, hh],
      [-hw, hh]
    ];
    let imgMinX = Infinity;
    let imgMaxX = -Infinity;
    let imgMinY = Infinity;
    let imgMaxY = -Infinity;
    for (const [cx, cy] of corners) {
      const screenX = ma * cx + mc * cy + tx;
      const screenY = mb * cx + md * cy + ty;
      const nx = screenX / visualSize.width + 0.5;
      const ny = screenY / visualSize.height + 0.5;
      imgMinX = Math.min(imgMinX, nx);
      imgMaxX = Math.max(imgMaxX, nx);
      imgMinY = Math.min(imgMinY, ny);
      imgMaxY = Math.max(imgMaxY, ny);
    }
    return {
      minX: imgMinX,
      minY: imgMinY,
      maxX: imgMaxX,
      maxY: imgMaxY
    };
  }
  function restrictCropRect(cropRect, zoom, rotation, imageAspectRatio) {
    const safeRect = sanitizeRect(cropRect);
    const zoomCandidate = safeBoundedNumber(zoom, 1);
    const safeZoom = zoomCandidate >= Number.EPSILON ? zoomCandidate : 1;
    const safeRotation = safeBoundedNumber(rotation, 0);
    const safeAspect = safeBoundedNumber(imageAspectRatio, 1);
    const aspectRatio = Math.max(safeAspect, Number.EPSILON);
    const snapRotation = Math.round(safeRotation / 90) * 90;
    const { visualW, visualH } = getVisualDimensions(
      snapRotation,
      aspectRatio
    );
    const { absC, absS } = getVisualDimensions(safeRotation, aspectRatio);
    const W = safeRect.width;
    const H2 = safeRect.height;
    const cropWPx = W * visualW;
    const cropHPx = H2 * visualH;
    const spanAlpha = cropWPx * absC + cropHPx * absS;
    const spanBeta = cropWPx * absS + cropHPx * absC;
    const limitAlpha = aspectRatio * safeZoom;
    const limitBeta = safeZoom;
    let t4 = 1;
    if (spanAlpha > 0) {
      t4 = Math.min(t4, limitAlpha / spanAlpha);
    }
    if (spanBeta > 0) {
      t4 = Math.min(t4, limitBeta / spanBeta);
    }
    if (t4 >= 1 - EPSILON2) {
      return safeRect;
    }
    const newW = W * t4;
    const newH = H2 * t4;
    const centerX = safeRect.x + W / 2;
    const centerY = safeRect.y + H2 / 2;
    let newX = centerX - newW / 2;
    let newY = centerY - newH / 2;
    newX = Math.max(0, Math.min(newX, 1 - newW));
    newY = Math.max(0, Math.min(newY, 1 - newH));
    return { x: newX, y: newY, width: newW, height: newH };
  }
  var CANONICAL_CONTAINER = { width: 1e3, height: 1e3 };
  var _scratchMat2 = mat2d_exports.create();
  var _scratchVec2 = vec2_exports.create();
  function restrictPanZoom(state2, imageSize, cropRect) {
    const safeState = sanitizeCropperState(state2);
    const safeCropRect = sanitizeRect(cropRect);
    const aspectRatio = isValidSize(imageSize) ? imageSize.width / imageSize.height : 1;
    const minZoom = Math.max(
      ABSOLUTE_MIN_ZOOM,
      getMinZoomForCover(safeState.rotation, aspectRatio, safeCropRect)
    );
    const zoom = Math.min(MAX_ZOOM, Math.max(safeState.zoom, minZoom));
    const candidateState = { ...safeState, zoom };
    const camera = createCamera(
      candidateState,
      CANONICAL_CONTAINER,
      imageSize
    );
    const snapRotation = Math.round(safeState.rotation / 90) * 90;
    const baseCamera = createCamera(
      {
        ...candidateState,
        pan: { x: 0, y: 0 },
        zoom: 1,
        rotation: snapRotation
      },
      CANONICAL_CONTAINER,
      imageSize
    );
    const visibleBounds = getVisibleBounds(baseCamera);
    const stencilCorners = [
      [
        visibleBounds.left + safeCropRect.x * visibleBounds.width,
        visibleBounds.top + safeCropRect.y * visibleBounds.height
      ],
      [
        visibleBounds.left + (safeCropRect.x + safeCropRect.width) * visibleBounds.width,
        visibleBounds.top + safeCropRect.y * visibleBounds.height
      ],
      [
        visibleBounds.left + (safeCropRect.x + safeCropRect.width) * visibleBounds.width,
        visibleBounds.top + (safeCropRect.y + safeCropRect.height) * visibleBounds.height
      ],
      [
        visibleBounds.left + safeCropRect.x * visibleBounds.width,
        visibleBounds.top + (safeCropRect.y + safeCropRect.height) * visibleBounds.height
      ]
    ];
    mat2d_exports.invert(_scratchMat2, camera);
    let minWx = Infinity;
    let maxWx = -Infinity;
    let minWy = Infinity;
    let maxWy = -Infinity;
    for (const corner of stencilCorners) {
      vec2_exports.transformMat2d(_scratchVec2, corner, _scratchMat2);
      const w3 = _scratchVec2;
      if (w3[0] < minWx) {
        minWx = w3[0];
      }
      if (w3[0] > maxWx) {
        maxWx = w3[0];
      }
      if (w3[1] < minWy) {
        minWy = w3[1];
      }
      if (w3[1] > maxWy) {
        maxWy = w3[1];
      }
    }
    if (minWx >= -EPSILON2 && maxWx <= 1 + EPSILON2 && minWy >= -EPSILON2 && maxWy <= 1 + EPSILON2) {
      return { pan: safeState.pan, zoom };
    }
    let dwx = 0;
    let dwy = 0;
    if (minWx < 0 && maxWx <= 1 + EPSILON2) {
      dwx = -minWx;
    } else if (maxWx > 1 && minWx >= -EPSILON2) {
      dwx = 1 - maxWx;
    } else if (minWx < 0 && maxWx > 1) {
      dwx = (1 - maxWx - minWx) / 2;
    }
    if (minWy < 0 && maxWy <= 1 + EPSILON2) {
      dwy = -minWy;
    } else if (maxWy > 1 && minWy >= -EPSILON2) {
      dwy = 1 - maxWy;
    } else if (minWy < 0 && maxWy > 1) {
      dwy = (1 - maxWy - minWy) / 2;
    }
    const dsx = camera[0] * dwx + camera[2] * dwy;
    const dsy = camera[1] * dwx + camera[3] * dwy;
    const newPanX = safeState.pan.x - (visibleBounds.width > 0 ? dsx / visibleBounds.width : 0);
    const newPanY = safeState.pan.y - (visibleBounds.height > 0 ? dsy / visibleBounds.height : 0);
    return {
      pan: { x: newPanX, y: newPanY },
      zoom
    };
  }

  // packages/media-editor/build-module/image-editor/core/state.mjs
  var STATE_EPSILON = 1e-6;
  function nearlyEqual(a3, b3) {
    return Math.abs(a3 - b3) < STATE_EPSILON;
  }
  function areCropperStatesEqual(a3, b3) {
    const aImage = a3.image;
    const bImage = b3.image;
    return aImage?.src === bImage?.src && aImage?.naturalWidth === bImage?.naturalWidth && aImage?.naturalHeight === bImage?.naturalHeight && nearlyEqual(a3.pan.x, b3.pan.x) && nearlyEqual(a3.pan.y, b3.pan.y) && nearlyEqual(a3.zoom, b3.zoom) && nearlyEqual(a3.rotation, b3.rotation) && a3.flip.horizontal === b3.flip.horizontal && a3.flip.vertical === b3.flip.vertical && nearlyEqual(a3.cropRect.x, b3.cropRect.x) && nearlyEqual(a3.cropRect.y, b3.cropRect.y) && nearlyEqual(a3.cropRect.width, b3.cropRect.width) && nearlyEqual(a3.cropRect.height, b3.cropRect.height);
  }
  function clampRequestedZoom(state2, zoom) {
    if (state2.image) {
      return Math.min(MAX_ZOOM, Math.max(ABSOLUTE_MIN_ZOOM, zoom));
    }
    return Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, zoom));
  }
  function operationToAction(state2, op) {
    switch (op.type) {
      case "crop":
        return { type: "SET_CROP_RECT", payload: { ...op.rect } };
      case "rotate": {
        const singleFlip = state2.flip.horizontal !== state2.flip.vertical;
        const fieldDelta = singleFlip ? -op.degrees : op.degrees;
        return {
          type: "SET_ROTATION",
          payload: normalizeRotation(state2.rotation + fieldDelta)
        };
      }
      case "flip":
        return {
          type: "SET_FLIP",
          payload: {
            ...state2.flip,
            [op.direction]: !state2.flip[op.direction]
          }
        };
      case "zoom":
        return { type: "SET_ZOOM", payload: op.factor };
    }
  }
  function enforceContainment(state2) {
    if (!state2.image) {
      return state2;
    }
    const imageSize = {
      width: state2.image.naturalWidth,
      height: state2.image.naturalHeight
    };
    const imageAspectRatio = imageSize.width / imageSize.height;
    const { pan: panAfterZoom, zoom } = restrictPanZoom(
      state2,
      imageSize,
      state2.cropRect
    );
    const cropRect = restrictCropRect(
      state2.cropRect,
      zoom,
      state2.rotation,
      imageAspectRatio
    );
    let pan = panAfterZoom;
    if (cropRect !== state2.cropRect) {
      ({ pan } = restrictPanZoom(
        { ...state2, zoom, cropRect },
        imageSize,
        cropRect
      ));
    }
    if (pan.x === state2.pan.x && pan.y === state2.pan.y && zoom === state2.zoom && cropRect === state2.cropRect) {
      return state2;
    }
    return { ...state2, pan, zoom, cropRect };
  }
  function commitBase(next) {
    if (next.basePan.x === next.pan.x && next.basePan.y === next.pan.y && next.baseZoom === next.zoom && next.baseRotation === next.rotation) {
      return next;
    }
    return {
      ...next,
      basePan: { x: next.pan.x, y: next.pan.y },
      baseZoom: next.zoom,
      baseRotation: next.rotation
    };
  }
  function cropperReducer(state2, action) {
    switch (action.type) {
      case "SET_IMAGE":
        return commitBase(
          enforceContainment({
            ...state2,
            image: action.payload
          })
        );
      case "SET_PAN":
        return commitBase(
          enforceContainment({
            ...state2,
            pan: action.payload
          })
        );
      case "SET_ZOOM": {
        const z = clampRequestedZoom(state2, action.payload);
        return commitBase(
          enforceContainment({
            ...state2,
            zoom: z
          })
        );
      }
      case "SET_ZOOM_AT_POINT": {
        const z = clampRequestedZoom(state2, action.payload.zoom);
        return commitBase(
          enforceContainment({
            ...state2,
            zoom: z,
            pan: action.payload.pan
          })
        );
      }
      case "SET_ROTATION": {
        const newRotation = normalizeRotation(action.payload);
        const singleFlip = state2.flip.horizontal !== state2.flip.vertical;
        const deltaRad = degreesToRadians(
          newRotation - state2.baseRotation
        );
        const cos = Math.cos(deltaRad);
        const sin = Math.sin(deltaRad) * (singleFlip ? -1 : 1);
        const cropCx = state2.cropRect.x + state2.cropRect.width / 2;
        const cropCy = state2.cropRect.y + state2.cropRect.height / 2;
        const ox = cropCx - 0.5;
        const oy = cropCy - 0.5;
        const dx = state2.basePan.x - ox;
        const dy = state2.basePan.y - oy;
        return enforceContainment({
          ...state2,
          rotation: newRotation,
          zoom: state2.baseZoom,
          pan: {
            x: ox + cos * dx - sin * dy,
            y: oy + sin * dx + cos * dy
          }
        });
      }
      case "SNAP_ROTATE_90": {
        const rawDir = action.payload.direction;
        const singleFlip = state2.flip.horizontal !== state2.flip.vertical;
        const fieldDir = singleFlip ? -rawDir : rawDir;
        const rot90 = normalizeRotation(state2.rotation + fieldDir * 90);
        const rect = state2.cropRect;
        const cx = rect.x + rect.width / 2;
        const cy = rect.y + rect.height / 2;
        const newPanX = rawDir === 1 ? -state2.pan.y : state2.pan.y;
        const newPanY = rawDir === 1 ? state2.pan.x : -state2.pan.x;
        return commitBase(
          enforceContainment({
            ...state2,
            rotation: rot90,
            zoom: state2.baseZoom,
            pan: { x: newPanX, y: newPanY },
            cropRect: {
              x: cx - rect.height / 2,
              y: cy - rect.width / 2,
              width: rect.height,
              height: rect.width
            }
          })
        );
      }
      case "SET_FLIP": {
        const oldFlip = state2.flip;
        const newFlip = action.payload;
        const flippedH = oldFlip.horizontal !== newFlip.horizontal;
        const flippedV = oldFlip.vertical !== newFlip.vertical;
        const rect = state2.cropRect;
        return commitBase(
          enforceContainment({
            ...state2,
            flip: newFlip,
            pan: {
              x: flippedH ? -state2.pan.x : state2.pan.x,
              y: flippedV ? -state2.pan.y : state2.pan.y
            },
            cropRect: {
              x: flippedH ? 1 - rect.x - rect.width : rect.x,
              y: flippedV ? 1 - rect.y - rect.height : rect.y,
              width: rect.width,
              height: rect.height
            }
          })
        );
      }
      case "SET_CROP_RECT":
        return commitBase(
          enforceContainment({
            ...state2,
            cropRect: action.payload
          })
        );
      case "SETTLE_CROP": {
        const rect = state2.cropRect;
        if (rect.width === 0 || rect.height === 0 || !state2.image) {
          return state2;
        }
        const fitScale = 1 / Math.max(rect.width, rect.height);
        const zoomCap = state2.zoom > 0 ? MAX_ZOOM / state2.zoom : fitScale;
        const s3 = Math.min(fitScale, zoomCap);
        const newW = rect.width * s3;
        const newH = rect.height * s3;
        const oldCx = rect.x + rect.width / 2;
        const oldCy = rect.y + rect.height / 2;
        return commitBase(
          enforceContainment({
            ...state2,
            zoom: state2.zoom * s3,
            pan: {
              x: (state2.pan.x - oldCx + 0.5) * s3,
              y: (state2.pan.y - oldCy + 0.5) * s3
            },
            cropRect: {
              x: (1 - newW) / 2,
              y: (1 - newH) / 2,
              width: newW,
              height: newH
            }
          })
        );
      }
      case "APPLY_OPERATION":
        return cropperReducer(
          state2,
          operationToAction(state2, action.payload)
        );
      case "RESET":
        return commitBase(
          enforceContainment({
            ...DEFAULT_STATE2,
            image: state2.image,
            ...action.payload
          })
        );
    }
  }

  // packages/media-editor/build-module/image-editor/core/setter-helpers.mjs
  function buildFocalPointZoomAction(state2, requestedZoom) {
    const clampedZoom = Math.min(
      MAX_ZOOM,
      Math.max(getMinZoom(state2), requestedZoom)
    );
    if (clampedZoom === state2.zoom) {
      return null;
    }
    const { cropRect } = state2;
    const focalNormX = cropRect.x + cropRect.width / 2 - 0.5;
    const focalNormY = cropRect.y + cropRect.height / 2 - 0.5;
    const zoomRatio = 1 - clampedZoom / state2.zoom;
    const newPanX = state2.pan.x + (focalNormX - state2.pan.x) * zoomRatio;
    const newPanY = state2.pan.y + (focalNormY - state2.pan.y) * zoomRatio;
    const imageSize = state2.image ? {
      width: state2.image.naturalWidth,
      height: state2.image.naturalHeight
    } : { width: 1, height: 1 };
    const { pan: clampedPan } = restrictPanZoom(
      {
        ...state2,
        zoom: clampedZoom,
        pan: { x: newPanX, y: newPanY }
      },
      imageSize,
      state2.cropRect
    );
    return {
      type: "SET_ZOOM_AT_POINT",
      payload: { zoom: clampedZoom, pan: clampedPan }
    };
  }

  // packages/media-editor/build-module/image-editor/react/hooks/build-cropper-setters.mjs
  function buildCropperSetters(dispatchCropperAction, getCropperState) {
    return {
      setPan: (pan) => dispatchCropperAction({ type: "SET_PAN", payload: pan }),
      setZoom: (zoom) => {
        const action = buildFocalPointZoomAction(getCropperState(), zoom);
        if (action) {
          dispatchCropperAction(action);
        }
      },
      setZoomAtPoint: (zoom, pan) => dispatchCropperAction({
        type: "SET_ZOOM_AT_POINT",
        payload: { zoom, pan }
      }),
      setRotation: (rotation) => dispatchCropperAction({
        type: "SET_ROTATION",
        payload: rotation
      }),
      setFlip: (flip4) => dispatchCropperAction({ type: "SET_FLIP", payload: flip4 }),
      toggleFlip: (direction) => {
        const { flip: flip4 } = getCropperState();
        dispatchCropperAction({
          type: "SET_FLIP",
          payload: { ...flip4, [direction]: !flip4[direction] }
        });
      },
      snapRotate90: (direction) => dispatchCropperAction({
        type: "SNAP_ROTATE_90",
        payload: { direction }
      }),
      setCropRect: (rect) => dispatchCropperAction({
        type: "SET_CROP_RECT",
        payload: rect
      }),
      settleCrop: () => dispatchCropperAction({ type: "SETTLE_CROP" }),
      applyOperation: (op) => dispatchCropperAction({
        type: "APPLY_OPERATION",
        payload: op
      })
    };
  }

  // packages/media-editor/build-module/image-editor/react/components/cropper.mjs
  var import_element155 = __toESM(require_element(), 1);
  var import_i18n134 = __toESM(require_i18n(), 1);

  // packages/media-editor/build-module/image-editor/core/crop-rect.mjs
  function computeInscribedRect(aspectRatio, visualSize) {
    let w3 = 1;
    let h3 = 1;
    if (aspectRatio && aspectRatio > 0 && visualSize.width > 0) {
      const normalizedRatio = aspectRatio * visualSize.height / visualSize.width;
      if (normalizedRatio <= 1) {
        w3 = normalizedRatio;
      } else {
        h3 = 1 / normalizedRatio;
      }
    }
    return {
      x: (1 - w3) / 2,
      y: (1 - h3) / 2,
      width: w3,
      height: h3
    };
  }

  // packages/media-editor/build-module/image-editor/core/stencil-math.mjs
  function getMinCropPixels(displayScale) {
    if (displayScale <= 0) {
      return MIN_CROP_PIXELS;
    }
    return Math.max(MIN_CROP_PIXELS, MIN_CROP_SCREEN_PX / displayScale);
  }
  var DEFAULT_MIN_CROP_SIZE = { width: 0.05, height: 0.05 };
  function computeFreeResizeRect(drag2, clientX, clientY, imageSize, bounds, minCropSize = DEFAULT_MIN_CROP_SIZE) {
    const dx = imageSize.width > 0 ? (clientX - drag2.startX) / imageSize.width : 0;
    const dy = imageSize.height > 0 ? (clientY - drag2.startY) / imageSize.height : 0;
    const s3 = drag2.startRect;
    const handle = drag2.handle;
    let edgeTop = s3.y;
    let edgeBottom = s3.y + s3.height;
    let edgeLeft = s3.x;
    let edgeRight = s3.x + s3.width;
    if (handle === "n" || handle === "nw" || handle === "ne") {
      edgeTop = Math.max(
        bounds.minY,
        Math.min(s3.y + dy, edgeBottom - minCropSize.height)
      );
    }
    if (handle === "s" || handle === "sw" || handle === "se") {
      edgeBottom = Math.max(
        edgeTop + minCropSize.height,
        Math.min(s3.y + s3.height + dy, bounds.maxY)
      );
    }
    if (handle === "w" || handle === "nw" || handle === "sw") {
      edgeLeft = Math.max(
        bounds.minX,
        Math.min(s3.x + dx, edgeRight - minCropSize.width)
      );
    }
    if (handle === "e" || handle === "ne" || handle === "se") {
      edgeRight = Math.max(
        edgeLeft + minCropSize.width,
        Math.min(s3.x + s3.width + dx, bounds.maxX)
      );
    }
    return {
      x: edgeLeft,
      y: edgeTop,
      width: edgeRight - edgeLeft,
      height: edgeBottom - edgeTop
    };
  }
  function computeLockedResizeRect(drag2, clientX, clientY, imageSize, bounds, normalizedRatio, minCropSize = DEFAULT_MIN_CROP_SIZE, driverAxis) {
    if (normalizedRatio <= 0 || imageSize.width <= 0 || imageSize.height <= 0) {
      return { ...drag2.startRect };
    }
    const dx = (clientX - drag2.startX) / imageSize.width;
    const dy = (clientY - drag2.startY) / imageSize.height;
    const s3 = drag2.startRect;
    const handle = drag2.handle;
    const anchorX = handle === "nw" || handle === "sw" ? s3.x + s3.width : s3.x;
    const anchorY = handle === "nw" || handle === "ne" ? s3.y + s3.height : s3.y;
    const dirX = handle === "nw" || handle === "sw" ? -1 : 1;
    const dirY = handle === "nw" || handle === "ne" ? -1 : 1;
    const draggedX = (handle === "nw" || handle === "sw" ? s3.x : s3.x + s3.width) + dx;
    const draggedY = (handle === "nw" || handle === "ne" ? s3.y : s3.y + s3.height) + dy;
    let distW = (draggedX - anchorX) * dirX;
    let distH = (draggedY - anchorY) * dirY;
    const minDistW = Math.max(
      minCropSize.width,
      minCropSize.height * normalizedRatio
    );
    const minDistH = minDistW / normalizedRatio;
    distW = Math.max(distW, minDistW);
    distH = Math.max(distH, minDistH);
    const pixelRatio = normalizedRatio * imageSize.width / imageSize.height;
    const isWidthDriver = driverAxis === "width" || !driverAxis && distW * imageSize.width / (distH * imageSize.height) > pixelRatio;
    if (isWidthDriver) {
      distH = distW / normalizedRatio;
    } else {
      distW = distH * normalizedRatio;
    }
    const maxW = dirX > 0 ? bounds.maxX - anchorX : anchorX - bounds.minX;
    const maxH = dirY > 0 ? bounds.maxY - anchorY : anchorY - bounds.minY;
    if (distW > maxW) {
      distW = maxW;
      distH = distW / normalizedRatio;
    }
    if (distH > maxH) {
      distH = maxH;
      distW = distH * normalizedRatio;
    }
    distW = Math.max(distW, minDistW);
    distH = Math.max(distH, minDistH);
    const newX = dirX > 0 ? anchorX : anchorX - distW;
    const newY = dirY > 0 ? anchorY : anchorY - distH;
    return { x: newX, y: newY, width: distW, height: distH };
  }
  function computeShiftLockedResizeRect(drag2, clientX, clientY, imageSize, bounds, minCropSize = DEFAULT_MIN_CROP_SIZE) {
    const s3 = drag2.startRect;
    const pixelW = s3.width * imageSize.width;
    const pixelH = s3.height * imageSize.height;
    if (pixelH <= 0 || pixelW <= 0) {
      return computeFreeResizeRect(
        drag2,
        clientX,
        clientY,
        imageSize,
        bounds,
        minCropSize
      );
    }
    const normalizedRatio = s3.width / s3.height;
    const handle = drag2.handle;
    if (handle === "nw" || handle === "ne" || handle === "sw" || handle === "se") {
      return computeLockedResizeRect(
        drag2,
        clientX,
        clientY,
        imageSize,
        bounds,
        normalizedRatio,
        minCropSize
      );
    }
    const free = computeFreeResizeRect(
      drag2,
      clientX,
      clientY,
      imageSize,
      bounds,
      minCropSize
    );
    if (handle === "n" || handle === "s") {
      let newHeight2 = free.height;
      let newWidth2 = newHeight2 * normalizedRatio;
      const centerX = s3.x + s3.width / 2;
      const maxWidth = Math.min(centerX - bounds.minX, bounds.maxX - centerX) * 2;
      if (newWidth2 > maxWidth) {
        newWidth2 = maxWidth;
        newHeight2 = newWidth2 / normalizedRatio;
      }
      const minHeight = Math.max(
        minCropSize.height,
        minCropSize.width / normalizedRatio
      );
      if (newHeight2 < minHeight) {
        newHeight2 = minHeight;
        newWidth2 = newHeight2 * normalizedRatio;
      }
      const newY = handle === "n" ? s3.y + s3.height - newHeight2 : s3.y;
      return {
        x: centerX - newWidth2 / 2,
        y: newY,
        width: newWidth2,
        height: newHeight2
      };
    }
    let newWidth = free.width;
    let newHeight = newWidth / normalizedRatio;
    const centerY = s3.y + s3.height / 2;
    const maxHeight = Math.min(centerY - bounds.minY, bounds.maxY - centerY) * 2;
    if (newHeight > maxHeight) {
      newHeight = maxHeight;
      newWidth = newHeight * normalizedRatio;
    }
    const minWidth = Math.max(
      minCropSize.width,
      minCropSize.height * normalizedRatio
    );
    if (newWidth < minWidth) {
      newWidth = minWidth;
      newHeight = newWidth / normalizedRatio;
    }
    const newX = handle === "w" ? s3.x + s3.width - newWidth : s3.x;
    return {
      x: newX,
      y: centerY - newHeight / 2,
      width: newWidth,
      height: newHeight
    };
  }

  // packages/media-editor/build-module/image-editor/react/hooks/use-interaction.mjs
  var import_element148 = __toESM(require_element(), 1);

  // packages/media-editor/build-module/image-editor/core/interaction-controller.mjs
  var DOUBLE_TAP_TIME = 300;
  var DOUBLE_TAP_DISTANCE = 30;
  var ZOOM_ANIMATION_DURATION = 200;
  function getImageSizeFromState(state2) {
    return state2.image ? { width: state2.image.naturalWidth, height: state2.image.naturalHeight } : { width: 1, height: 1 };
  }
  function getTouchDistance(t1, t22) {
    const dx = t1.clientX - t22.clientX;
    const dy = t1.clientY - t22.clientY;
    return Math.sqrt(dx * dx + dy * dy);
  }
  var InteractionController = class {
    options;
    /** Current drag/zoom status. */
    isDragging = false;
    isZooming = false;
    /** Active drag state during pointer interactions. */
    drag = null;
    /** Active touch state during touch interactions. */
    touch = null;
    /** Cleanup function for active touch listeners on document. */
    touchCleanup = null;
    /**
     * Cleanup function for active pointer-drag listeners on the
     * captured element. Set while a pointer drag is in progress so
     * `destroy()` can tear the drag down cleanly if the consumer
     * unmounts mid-drag. Cleared on pointerup/lostpointercapture.
     */
    pointerCleanup = null;
    /** Last tap info for double-tap detection. */
    lastTap = null;
    /** Timer for the zoom animation state (double-tap). */
    zoomTimer;
    /** Timer for wheel gesture debounce. */
    wheelGestureTimer;
    /** Whether a wheel gesture is currently active. */
    wheelGestureActive = false;
    /** Current requestAnimationFrame ID. */
    rafId = 0;
    constructor(options) {
      this.options = options;
    }
    /** Read minZoom lazily so option changes take effect immediately. */
    get minZoom() {
      return this.options.minZoom ?? MIN_ZOOM;
    }
    /** Read maxZoom lazily so option changes take effect immediately. */
    get maxZoom() {
      return this.options.maxZoom ?? MAX_ZOOM;
    }
    /** Read zoomSpeed lazily so option changes take effect immediately. */
    get zoomSpeed() {
      return this.options.zoomSpeed ?? DEFAULT_WHEEL_ZOOM_SPEED;
    }
    /** Read keyboardStep lazily so option changes take effect immediately. */
    get keyboardStep() {
      return this.options.keyboardStep ?? DEFAULT_KEYBOARD_STEP;
    }
    /**
     * Get the keyboard pan step, including modifier-based coarse movement.
     *
     * @param event The native KeyboardEvent.
     * @return The normalized pan step.
     */
    getKeyboardStep(event) {
      return event.shiftKey ? this.keyboardStep * KEYBOARD_SHIFT_STEP_MULTIPLIER : this.keyboardStep;
    }
    /** Read doubleTapZoom lazily so option changes take effect immediately. */
    get doubleTapZoom() {
      return this.options.doubleTapZoom ?? 2;
    }
    /**
     * Update the drag/zoom status and notify via callback if changed.
     *
     * @param update Partial status with isDragging and/or isZooming.
     */
    setStatus(update4) {
      let changed = false;
      if (update4.isDragging !== void 0 && update4.isDragging !== this.isDragging) {
        this.isDragging = update4.isDragging;
        changed = true;
      }
      if (update4.isZooming !== void 0 && update4.isZooming !== this.isZooming) {
        this.isZooming = update4.isZooming;
        changed = true;
      }
      if (changed) {
        this.options.onStatusChange?.({
          isDragging: this.isDragging,
          isZooming: this.isZooming
        });
      }
    }
    /**
     * Handle a pointer-down event on the container element.
     *
     * Initiates a drag (pan) interaction. Captures the pointer on the
     * provided element and registers pointermove/pointerup/lostpointercapture
     * listeners for the duration of the drag.
     *
     * @param e  The native PointerEvent.
     * @param el The DOM element to capture the pointer on.
     */
    handlePointerDown(e3, el) {
      if (e3.button !== 0) {
        return;
      }
      if (e3.pointerType === "touch") {
        return;
      }
      e3.preventDefault();
      const ownerDoc = el.ownerDocument;
      if (ownerDoc?.activeElement instanceof HTMLElement && ownerDoc.activeElement !== el) {
        ownerDoc.activeElement.blur();
      }
      el.focus();
      el.setPointerCapture(e3.pointerId);
      this.setStatus({ isDragging: true });
      this.options.onGestureStart?.();
      const currentState = this.options.getState();
      this.drag = {
        startX: e3.clientX,
        startY: e3.clientY,
        startPanX: currentState.pan.x,
        startPanY: currentState.pan.y
      };
      const onPointerMove = (moveEvent) => {
        const drag2 = this.drag;
        if (!drag2) {
          return;
        }
        const pe = moveEvent;
        cancelAnimationFrame(this.rafId);
        this.rafId = requestAnimationFrame(() => {
          const s3 = this.options.getState();
          const imgSize = this.options.getImageSize();
          const containerSize = this.options.getContainerSize();
          const panSize = imgSize ?? containerSize;
          const deltaX = panSize.width > 0 ? (pe.clientX - drag2.startX) / panSize.width : 0;
          const deltaY = panSize.height > 0 ? (pe.clientY - drag2.startY) / panSize.height : 0;
          const { pan: newCrop } = restrictPanZoom(
            {
              ...s3,
              pan: {
                x: drag2.startPanX + deltaX,
                y: drag2.startPanY + deltaY
              }
            },
            getImageSizeFromState(s3),
            s3.cropRect
          );
          this.options.actions.setPan(newCrop);
        });
      };
      const removeListeners = () => {
        el.removeEventListener("pointermove", onPointerMove);
        el.removeEventListener("pointerup", onPointerUp);
        el.removeEventListener("lostpointercapture", onPointerUp);
      };
      const onPointerUp = () => {
        this.setStatus({ isDragging: false });
        this.options.onGestureEnd?.();
        this.drag = null;
        cancelAnimationFrame(this.rafId);
        removeListeners();
        this.pointerCleanup = null;
      };
      el.addEventListener("pointermove", onPointerMove);
      el.addEventListener("pointerup", onPointerUp);
      el.addEventListener("lostpointercapture", onPointerUp);
      this.pointerCleanup = removeListeners;
    }
    /**
     * Handle a wheel event on the container element.
     *
     * Implements focal-point zoom: the point under the cursor stays
     * stationary on screen while the zoom level changes.
     *
     * Must be registered with `{ passive: false }` to allow preventDefault.
     *
     * @param e The native WheelEvent.
     */
    handleWheel(e3) {
      e3.preventDefault();
      if (this.drag) {
        return;
      }
      if (!this.wheelGestureActive) {
        this.wheelGestureActive = true;
        this.options.onGestureStart?.();
      }
      clearTimeout(this.wheelGestureTimer);
      this.wheelGestureTimer = setTimeout(() => {
        this.wheelGestureActive = false;
        this.options.onGestureEnd?.();
      }, DOUBLE_TAP_TIME);
      const s3 = this.options.getState();
      const delta = -e3.deltaY * this.zoomSpeed;
      const newZoom = Math.min(
        this.maxZoom,
        Math.max(this.minZoom, s3.zoom + delta)
      );
      if (newZoom === s3.zoom) {
        return;
      }
      const containerSize = this.options.getContainerSize();
      const imgSize = this.options.getImageSize();
      const visSize = imgSize ?? containerSize;
      const target = e3.currentTarget;
      const rect = target instanceof Element ? target.getBoundingClientRect() : void 0;
      if (visSize.width > 0 && visSize.height > 0 && rect) {
        const fx = e3.clientX - rect.left - containerSize.width / 2;
        const fy = e3.clientY - rect.top - containerSize.height / 2;
        const zoomRatio = 1 - newZoom / s3.zoom;
        const focalNormX = fx / visSize.width;
        const focalNormY = fy / visSize.height;
        const newCropX = s3.pan.x + (focalNormX - s3.pan.x) * zoomRatio;
        const newCropY = s3.pan.y + (focalNormY - s3.pan.y) * zoomRatio;
        const { pan: clampedCrop } = restrictPanZoom(
          { ...s3, zoom: newZoom, pan: { x: newCropX, y: newCropY } },
          getImageSizeFromState(s3),
          s3.cropRect
        );
        this.options.actions.setZoomAtPoint(newZoom, clampedCrop);
      } else {
        this.options.actions.setZoom(newZoom);
      }
    }
    /**
     * Handle a touch-start event on the container element.
     *
     * Supports single-finger pan, two-finger pinch zoom, and
     * double-tap to toggle between fit and 2x zoom. Registers
     * touchmove/touchend/touchcancel on the provided document for the
     * duration of the gesture.
     *
     * @param e             The native TouchEvent.
     * @param containerRect The bounding rect of the container element.
     * @param doc           The document to register move/end listeners on.
     *                      Defaults to globalThis.document. Pass the iframe's
     *                      contentDocument when running inside an iframe.
     */
    handleTouchStart(e3, containerRect, doc = document) {
      if (this.touch && e3.touches.length === 2) {
        const s3 = this.options.getState();
        const distance2 = getTouchDistance(e3.touches[0], e3.touches[1]);
        const midX = (e3.touches[0].clientX + e3.touches[1].clientX) / 2;
        const midY = (e3.touches[0].clientY + e3.touches[1].clientY) / 2;
        this.touch.didPinch = true;
        this.touch.startDistance = distance2;
        this.touch.startZoom = s3.zoom;
        this.touch.startPanX = s3.pan.x;
        this.touch.startPanY = s3.pan.y;
        this.touch.startMidX = midX;
        this.touch.startMidY = midY;
        this.touch.containerRect = containerRect;
        this.setStatus({ isDragging: false });
        return;
      }
      if (e3.touches.length === 1) {
        const tapX = e3.touches[0].clientX;
        const tapY = e3.touches[0].clientY;
        if (this.tryDoubleTap(e3, tapX, tapY, containerRect)) {
          return;
        }
        const currentState = this.options.getState();
        this.touch = {
          startDistance: 0,
          startZoom: currentState.zoom,
          lastTouchX: e3.touches[0].clientX,
          lastTouchY: e3.touches[0].clientY,
          startPanX: currentState.pan.x,
          startPanY: currentState.pan.y,
          containerRect,
          startMidX: 0,
          startMidY: 0,
          didPinch: false,
          moved: false
        };
        this.options.onGestureStart?.();
      } else if (e3.touches.length === 2) {
        const currentState = this.options.getState();
        const distance2 = getTouchDistance(e3.touches[0], e3.touches[1]);
        const midX = (e3.touches[0].clientX + e3.touches[1].clientX) / 2;
        const midY = (e3.touches[0].clientY + e3.touches[1].clientY) / 2;
        this.touch = {
          startDistance: distance2,
          startZoom: currentState.zoom,
          lastTouchX: 0,
          lastTouchY: 0,
          startPanX: currentState.pan.x,
          startPanY: currentState.pan.y,
          containerRect,
          startMidX: midX,
          startMidY: midY,
          didPinch: true,
          moved: false
        };
        this.options.onGestureStart?.();
      }
      const onTouchEnd = () => {
        this.touch = null;
        this.touchCleanup = null;
        cancelAnimationFrame(this.rafId);
        doc.removeEventListener("touchmove", this.handleTouchMove);
        doc.removeEventListener("touchend", onTouchEnd);
        doc.removeEventListener("touchcancel", onTouchEnd);
        this.setStatus({ isDragging: false });
        this.options.onGestureEnd?.();
      };
      this.touchCleanup?.();
      doc.addEventListener("touchmove", this.handleTouchMove, {
        passive: false
      });
      doc.addEventListener("touchend", onTouchEnd);
      doc.addEventListener("touchcancel", onTouchEnd);
      this.touchCleanup = onTouchEnd;
    }
    // Handle a touchmove event during an active touch gesture. Decides pinch
    // vs. pan based on current `moveEvent.touches.length`, so the gesture
    // can transition between modes without timing sensitivity (e.g. fingers
    // landing 0ms vs 200ms apart). Arrow-property binding so `this` stays
    // attached when used as an event listener.
    handleTouchMove = (moveEvent) => {
      const touch = this.touch;
      if (!touch) {
        return;
      }
      moveEvent.preventDefault();
      cancelAnimationFrame(this.rafId);
      this.rafId = requestAnimationFrame(() => {
        const s3 = this.options.getState();
        if (moveEvent.touches.length === 2) {
          if (!touch.didPinch) {
            touch.didPinch = true;
            touch.startDistance = getTouchDistance(
              moveEvent.touches[0],
              moveEvent.touches[1]
            );
            touch.startZoom = s3.zoom;
            touch.startPanX = s3.pan.x;
            touch.startPanY = s3.pan.y;
            touch.startMidX = (moveEvent.touches[0].clientX + moveEvent.touches[1].clientX) / 2;
            touch.startMidY = (moveEvent.touches[0].clientY + moveEvent.touches[1].clientY) / 2;
            this.setStatus({ isDragging: false });
            return;
          }
          const latestContainerSize = this.options.getContainerSize();
          const latestImageSize = this.options.getImageSize();
          const t0 = moveEvent.touches[0];
          const t1 = moveEvent.touches[1];
          const currentDistance = getTouchDistance(t0, t1);
          const ratio = currentDistance / touch.startDistance;
          const newZoom = Math.min(
            this.maxZoom,
            Math.max(this.minZoom, touch.startZoom * ratio)
          );
          const visSize = latestImageSize ?? latestContainerSize;
          const rect = touch.containerRect;
          if (visSize.width > 0 && visSize.height > 0 && rect) {
            const mx = (t0.clientX + t1.clientX) / 2 - rect.left - latestContainerSize.width / 2;
            const my = (t0.clientY + t1.clientY) / 2 - rect.top - latestContainerSize.height / 2;
            const startMx = touch.startMidX - rect.left - latestContainerSize.width / 2;
            const startMy = touch.startMidY - rect.top - latestContainerSize.height / 2;
            const panDx = visSize.width > 0 ? (mx - startMx) / visSize.width : 0;
            const panDy = visSize.height > 0 ? (my - startMy) / visSize.height : 0;
            const zoomRatio = touch.startZoom !== 0 ? 1 - newZoom / touch.startZoom : 0;
            const startFocalNormX = startMx / visSize.width;
            const startFocalNormY = startMy / visSize.height;
            const newCropX = touch.startPanX + panDx + (startFocalNormX - touch.startPanX) * zoomRatio;
            const newCropY = touch.startPanY + panDy + (startFocalNormY - touch.startPanY) * zoomRatio;
            const { pan: clampedCrop } = restrictPanZoom(
              {
                ...s3,
                zoom: newZoom,
                pan: { x: newCropX, y: newCropY }
              },
              getImageSizeFromState(s3),
              s3.cropRect
            );
            this.options.actions.setZoomAtPoint(newZoom, clampedCrop);
          } else if (newZoom !== s3.zoom) {
            this.options.actions.setZoom(newZoom);
          }
        } else if (moveEvent.touches.length === 1 && !touch.didPinch) {
          if (!touch.moved) {
            touch.moved = true;
            this.setStatus({ isDragging: true });
          }
          const panImageSize = this.options.getImageSize();
          const panContainerSize = this.options.getContainerSize();
          const panSize = panImageSize ?? panContainerSize;
          const deltaX = panSize.width > 0 ? (moveEvent.touches[0].clientX - touch.lastTouchX) / panSize.width : 0;
          const deltaY = panSize.height > 0 ? (moveEvent.touches[0].clientY - touch.lastTouchY) / panSize.height : 0;
          const { pan: newCrop } = restrictPanZoom(
            {
              ...s3,
              pan: {
                x: touch.startPanX + deltaX,
                y: touch.startPanY + deltaY
              }
            },
            getImageSizeFromState(s3),
            s3.cropRect
          );
          this.options.actions.setPan(newCrop);
        }
      });
    };
    // Handle double-tap-to-toggle-zoom. On a second tap within the configured
    // time/distance threshold, toggles zoom between `minZoom` and
    // `doubleTapZoom` around the tap point and dispatches. Returns `true` if
    // the tap was handled as a double-tap (caller should early-return),
    // `false` otherwise (caller proceeds with normal single-tap handling).
    // Either way, records the tap for next time.
    tryDoubleTap(e3, tapX, tapY, containerRect) {
      const now = Date.now();
      const lastTap = this.lastTap;
      if (!lastTap) {
        this.lastTap = { time: now, x: tapX, y: tapY };
        return false;
      }
      const timeDelta = now - lastTap.time;
      const distDelta = Math.sqrt(
        (tapX - lastTap.x) ** 2 + (tapY - lastTap.y) ** 2
      );
      const isDoubleTap = timeDelta < DOUBLE_TAP_TIME && distDelta < DOUBLE_TAP_DISTANCE;
      if (!isDoubleTap) {
        this.lastTap = { time: now, x: tapX, y: tapY };
        return false;
      }
      e3.preventDefault();
      this.lastTap = null;
      const currentState = this.options.getState();
      const containerSize = this.options.getContainerSize();
      const imgSize = this.options.getImageSize();
      const targetZoom = currentState.zoom > (this.minZoom + this.doubleTapZoom) / 2 ? this.minZoom : this.doubleTapZoom;
      const visSize = imgSize ?? containerSize;
      this.setStatus({ isZooming: true });
      clearTimeout(this.zoomTimer);
      this.zoomTimer = setTimeout(() => {
        this.setStatus({ isZooming: false });
      }, ZOOM_ANIMATION_DURATION);
      this.options.onGestureStart?.();
      if (visSize.width > 0 && visSize.height > 0) {
        const fx = tapX - containerRect.left - containerSize.width / 2;
        const fy = tapY - containerRect.top - containerSize.height / 2;
        const zoomRatio = 1 - targetZoom / currentState.zoom;
        const focalNormX = fx / visSize.width;
        const focalNormY = fy / visSize.height;
        const newCropX = currentState.pan.x + (focalNormX - currentState.pan.x) * zoomRatio;
        const newCropY = currentState.pan.y + (focalNormY - currentState.pan.y) * zoomRatio;
        const { pan: clampedCrop } = restrictPanZoom(
          {
            ...currentState,
            zoom: targetZoom,
            pan: { x: newCropX, y: newCropY }
          },
          getImageSizeFromState(currentState),
          currentState.cropRect
        );
        this.options.actions.setZoomAtPoint(targetZoom, clampedCrop);
      } else {
        this.options.actions.setZoom(targetZoom);
      }
      this.options.onGestureEnd?.();
      return true;
    }
    /**
     * Handle a keydown event on the container element.
     *
     * Supports arrow keys for panning, +/- for zoom, and r/R for rotation.
     *
     * @param e The native KeyboardEvent.
     */
    handleKeyDown(e3) {
      const currentState = this.options.getState();
      switch (e3.key) {
        case "ArrowUp": {
          e3.preventDefault();
          const keyboardStep = this.getKeyboardStep(e3);
          const { pan: newCrop } = restrictPanZoom(
            {
              ...currentState,
              pan: {
                x: currentState.pan.x,
                y: currentState.pan.y + keyboardStep
              }
            },
            getImageSizeFromState(currentState),
            currentState.cropRect
          );
          this.options.actions.setPan(newCrop);
          break;
        }
        case "ArrowDown": {
          e3.preventDefault();
          const keyboardStep = this.getKeyboardStep(e3);
          const { pan: newCrop } = restrictPanZoom(
            {
              ...currentState,
              pan: {
                x: currentState.pan.x,
                y: currentState.pan.y - keyboardStep
              }
            },
            getImageSizeFromState(currentState),
            currentState.cropRect
          );
          this.options.actions.setPan(newCrop);
          break;
        }
        case "ArrowLeft": {
          e3.preventDefault();
          const keyboardStep = this.getKeyboardStep(e3);
          const { pan: newCrop } = restrictPanZoom(
            {
              ...currentState,
              pan: {
                x: currentState.pan.x + keyboardStep,
                y: currentState.pan.y
              }
            },
            getImageSizeFromState(currentState),
            currentState.cropRect
          );
          this.options.actions.setPan(newCrop);
          break;
        }
        case "ArrowRight": {
          e3.preventDefault();
          const keyboardStep = this.getKeyboardStep(e3);
          const { pan: newCrop } = restrictPanZoom(
            {
              ...currentState,
              pan: {
                x: currentState.pan.x - keyboardStep,
                y: currentState.pan.y
              }
            },
            getImageSizeFromState(currentState),
            currentState.cropRect
          );
          this.options.actions.setPan(newCrop);
          break;
        }
        case "+":
        case "=": {
          e3.preventDefault();
          const newZoom = Math.min(
            this.maxZoom,
            Math.max(this.minZoom, currentState.zoom + 0.5)
          );
          this.options.actions.setZoom(newZoom);
          break;
        }
        case "-":
        case "_": {
          e3.preventDefault();
          const newZoom = Math.min(
            this.maxZoom,
            Math.max(this.minZoom, currentState.zoom - 0.5)
          );
          this.options.actions.setZoom(newZoom);
          break;
        }
        case "r":
        case "R": {
          if (e3.metaKey || e3.ctrlKey || e3.altKey) {
            break;
          }
          e3.preventDefault();
          this.options.actions.snapRotate90(e3.shiftKey ? -1 : 1);
          break;
        }
        case "h":
        case "H": {
          if (e3.metaKey || e3.ctrlKey || e3.altKey || e3.shiftKey) {
            break;
          }
          e3.preventDefault();
          this.options.actions.toggleFlip?.("horizontal");
          break;
        }
        case "v":
        case "V": {
          if (e3.metaKey || e3.ctrlKey || e3.altKey || e3.shiftKey) {
            break;
          }
          e3.preventDefault();
          this.options.actions.toggleFlip?.("vertical");
          break;
        }
      }
    }
    /**
     * Clean up all timers, animation frames, and active touch listeners.
     *
     * Must be called when the controller is no longer needed (e.g., on
     * component unmount or element removal).
     */
    destroy() {
      cancelAnimationFrame(this.rafId);
      clearTimeout(this.zoomTimer);
      clearTimeout(this.wheelGestureTimer);
      this.touchCleanup?.();
      this.touchCleanup = null;
      this.pointerCleanup?.();
      this.pointerCleanup = null;
      this.drag = null;
      this.touch = null;
      this.lastTap = null;
    }
  };

  // packages/media-editor/build-module/image-editor/react/hooks/use-interaction.mjs
  var KEYBOARD_INTERACTION_IDLE_MS = 300;
  function isHandledKeyboardPan(event) {
    switch (event.key) {
      case "ArrowUp":
      case "ArrowDown":
      case "ArrowLeft":
      case "ArrowRight":
        return true;
      default:
        return false;
    }
  }
  function isHandledKeyboardZoom(event) {
    switch (event.key) {
      case "+":
      case "=":
      case "-":
      case "_":
        return true;
      default:
        return false;
    }
  }
  function useInteraction(state2, actions2, containerSize, imageSize, options) {
    const [isDragging, setIsDragging] = (0, import_element148.useState)(false);
    const [isZooming, setIsZooming] = (0, import_element148.useState)(false);
    const [isGestureActive, setIsGestureActive] = (0, import_element148.useState)(false);
    const [isKeyboardPanning, setIsKeyboardPanning] = (0, import_element148.useState)(false);
    const keyboardInteractionTimerRef = (0, import_element148.useRef)();
    const isKeyboardGestureActiveRef = (0, import_element148.useRef)(false);
    const stateRef = (0, import_element148.useRef)(state2);
    stateRef.current = state2;
    const containerSizeRef = (0, import_element148.useRef)(containerSize);
    containerSizeRef.current = containerSize;
    const imageSizeRef = (0, import_element148.useRef)(imageSize);
    imageSizeRef.current = imageSize;
    const optionsRef = (0, import_element148.useRef)(options);
    optionsRef.current = options;
    const actionsRef = (0, import_element148.useRef)(actions2);
    actionsRef.current = actions2;
    const controllerRef = (0, import_element148.useRef)(null);
    const startPlacementGesture = (0, import_element148.useCallback)(() => {
      setIsGestureActive(true);
    }, []);
    const stopPlacementGesture = (0, import_element148.useCallback)(() => {
      setIsGestureActive(false);
    }, []);
    const signalKeyboardGesture = (0, import_element148.useCallback)(() => {
      if (!isKeyboardGestureActiveRef.current) {
        isKeyboardGestureActiveRef.current = true;
        optionsRef.current?.onGestureStart?.();
      }
      clearTimeout(keyboardInteractionTimerRef.current);
      keyboardInteractionTimerRef.current = setTimeout(() => {
        isKeyboardGestureActiveRef.current = false;
        setIsKeyboardPanning(false);
        optionsRef.current?.onGestureEnd?.();
      }, KEYBOARD_INTERACTION_IDLE_MS);
    }, []);
    (0, import_element148.useEffect)(() => {
      return () => {
        clearTimeout(keyboardInteractionTimerRef.current);
      };
    }, []);
    (0, import_element148.useEffect)(() => {
      const controller = new InteractionController({
        getState: () => stateRef.current,
        actions: {
          setPan: (pan) => actionsRef.current.setPan(pan),
          setZoom: (zoom) => actionsRef.current.setZoom(zoom),
          setZoomAtPoint: (zoom, pan) => actionsRef.current.setZoomAtPoint(zoom, pan),
          snapRotate90: (direction) => actionsRef.current.snapRotate90(direction),
          toggleFlip: (direction) => actionsRef.current.toggleFlip?.(direction)
        },
        getContainerSize: () => containerSizeRef.current,
        getImageSize: () => imageSizeRef.current,
        get minZoom() {
          return optionsRef.current?.minZoom;
        },
        get maxZoom() {
          return optionsRef.current?.maxZoom;
        },
        get zoomSpeed() {
          return optionsRef.current?.zoomSpeed;
        },
        get keyboardStep() {
          return optionsRef.current?.keyboardStep;
        },
        get doubleTapZoom() {
          return optionsRef.current?.doubleTapZoom;
        },
        onGestureStart: () => {
          startPlacementGesture();
          optionsRef.current?.onGestureStart?.();
        },
        onGestureEnd: () => {
          stopPlacementGesture();
          optionsRef.current?.onGestureEnd?.();
        },
        onStatusChange: (status) => {
          setIsDragging(status.isDragging);
          setIsZooming(status.isZooming);
        }
      });
      controllerRef.current = controller;
      return () => {
        controller.destroy();
        controllerRef.current = null;
      };
    }, [startPlacementGesture, stopPlacementGesture]);
    const onPointerDown = (0, import_element148.useCallback)((e3) => {
      const el = e3.currentTarget;
      controllerRef.current?.handlePointerDown(e3.nativeEvent, el);
    }, []);
    const onTouchStart = (0, import_element148.useCallback)((e3) => {
      const el = e3.currentTarget;
      const rect = el.getBoundingClientRect();
      controllerRef.current?.handleTouchStart(
        e3.nativeEvent,
        rect,
        el.ownerDocument
      );
    }, []);
    const onKeyDown = (0, import_element148.useCallback)(
      (e3) => {
        if (isHandledKeyboardPan(e3.nativeEvent)) {
          setIsKeyboardPanning(true);
          signalKeyboardGesture();
        } else if (isHandledKeyboardZoom(e3.nativeEvent)) {
          signalKeyboardGesture();
        }
        controllerRef.current?.handleKeyDown(e3.nativeEvent);
      },
      [signalKeyboardGesture]
    );
    const onWheelNative = (0, import_element148.useCallback)((e3) => {
      controllerRef.current?.handleWheel(e3);
    }, []);
    return {
      handlers: {
        onPointerDown,
        onTouchStart,
        onKeyDown
      },
      onWheelNative,
      isDragging,
      isZooming,
      isPlacementActive: isGestureActive || isKeyboardPanning || isZooming
    };
  }

  // packages/media-editor/build-module/image-editor/react/hooks/use-transform-style.mjs
  var import_element149 = __toESM(require_element(), 1);

  // packages/media-editor/build-module/image-editor/core/transform-style.mjs
  var IDENTITY_MATRIX_STYLE = "matrix(1, 0, 0, 1, 0, 0)";
  function computeTransformStyle(state2, imageSize) {
    if (!isValidSize(imageSize)) {
      return IDENTITY_MATRIX_STYLE;
    }
    const safeState = sanitizeCropperState(state2);
    const translateX = safeState.pan.x * imageSize.width;
    const translateY = safeState.pan.y * imageSize.height;
    const rad = degreesToRadians(safeState.rotation);
    const cos = Math.cos(rad);
    const sin = Math.sin(rad);
    const sx = safeState.flip.horizontal ? -1 : 1;
    const sy = safeState.flip.vertical ? -1 : 1;
    const z = safeState.zoom;
    const a3 = sx * cos * z;
    const b3 = sy * sin * z;
    const c6 = -sx * sin * z;
    const d3 = sy * cos * z;
    return `matrix(${a3}, ${b3}, ${c6}, ${d3}, ${translateX}, ${translateY})`;
  }

  // packages/media-editor/build-module/image-editor/react/hooks/use-transform-style.mjs
  function useTransformStyle(state2, imageSize) {
    return (0, import_element149.useMemo)(
      () => computeTransformStyle(state2, imageSize),
      [state2, imageSize]
    );
  }

  // packages/media-editor/build-module/image-editor/react/hooks/use-aria-announcer.mjs
  var import_a11y4 = __toESM(require_a11y(), 1);
  var import_element150 = __toESM(require_element(), 1);
  var import_i18n132 = __toESM(require_i18n(), 1);

  // packages/media-editor/build-module/image-editor/core/source-region.mjs
  function getSourceRegion(state2, imageSize) {
    const safeState = sanitizeCropperState(state2);
    if (!isValidSize(imageSize)) {
      return {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        rotation: safeState.rotation,
        flip: { ...safeState.flip },
        zoom: safeState.zoom
      };
    }
    const syntheticContainer = { width: 1e3, height: 1e3 };
    const camera = createCamera(safeState, syntheticContainer, imageSize);
    const inv = mat2d_exports.create();
    mat2d_exports.invert(inv, camera);
    const baseCamera = createCamera(
      { ...safeState, pan: { x: 0, y: 0 }, zoom: 1 },
      syntheticContainer,
      imageSize
    );
    const visibleBounds = getVisibleBounds(baseCamera);
    const cropRect = safeState.cropRect;
    const cropCenterScreenX = visibleBounds.left + (cropRect.x + cropRect.width / 2) * visibleBounds.width;
    const cropCenterScreenY = visibleBounds.top + (cropRect.y + cropRect.height / 2) * visibleBounds.height;
    const srcCenter = vec2_exports.create();
    vec2_exports.transformMat2d(
      srcCenter,
      [cropCenterScreenX, cropCenterScreenY],
      inv
    );
    const snapRotation = Math.round(safeState.rotation / 90) * 90;
    const { width: rotW, height: rotH } = getRotatedBBox(
      imageSize.width,
      imageSize.height,
      snapRotation
    );
    const sourceW = cropRect.width * rotW / safeState.zoom;
    const sourceH = cropRect.height * rotH / safeState.zoom;
    return {
      x: srcCenter[0] * imageSize.width - sourceW / 2,
      y: srcCenter[1] * imageSize.height - sourceH / 2,
      width: sourceW,
      height: sourceH,
      rotation: safeState.rotation,
      flip: { ...safeState.flip },
      zoom: safeState.zoom
    };
  }
  function getCropRectFromSourceRegion(state2, imageSize, region) {
    if (!isValidSize(imageSize) || region.width <= 0 || region.height <= 0) {
      return null;
    }
    const safeState = sanitizeCropperState(state2);
    const syntheticContainer = { width: 1e3, height: 1e3 };
    const baseCamera = createCamera(
      { ...safeState, pan: { x: 0, y: 0 }, zoom: 1 },
      syntheticContainer,
      imageSize
    );
    const visibleBounds = getVisibleBounds(baseCamera);
    if (visibleBounds.width <= 0 || visibleBounds.height <= 0) {
      return null;
    }
    const sourceCenter = vec2_exports.fromValues(
      (region.x + region.width / 2) / imageSize.width,
      (region.y + region.height / 2) / imageSize.height
    );
    const screenCenter = vec2_exports.create();
    const camera = createCamera(safeState, syntheticContainer, imageSize);
    vec2_exports.transformMat2d(screenCenter, sourceCenter, camera);
    const snapRotation = Math.round(safeState.rotation / 90) * 90;
    const { width: rotW, height: rotH } = getRotatedBBox(
      imageSize.width,
      imageSize.height,
      snapRotation
    );
    if (rotW <= 0 || rotH <= 0) {
      return null;
    }
    const width = region.width * safeState.zoom / rotW;
    const height = region.height * safeState.zoom / rotH;
    const centerX = (screenCenter[0] - visibleBounds.left) / visibleBounds.width;
    const centerY = (screenCenter[1] - visibleBounds.top) / visibleBounds.height;
    return {
      x: centerX - width / 2,
      y: centerY - height / 2,
      width,
      height
    };
  }
  var CARDINAL_ROTATION_EPSILON = 1e-6;
  function isCardinalRotation(rotation) {
    const normalizedRotation = normalizeRotation(rotation);
    const nearestCardinal = Math.round(normalizedRotation / 90) * 90;
    return Math.abs(normalizedRotation - nearestCardinal) < CARDINAL_ROTATION_EPSILON;
  }
  function snapCropRectToSourcePixels(state2, imageSize, cropRect, handle) {
    const safeState = sanitizeCropperState(state2);
    if (!isCardinalRotation(safeState.rotation)) {
      return cropRect;
    }
    return snapCropRectEdgesToSourcePixels(safeState, imageSize, cropRect, {
      left: handle.includes("w"),
      top: handle.includes("n"),
      right: handle.includes("e"),
      bottom: handle.includes("s")
    });
  }
  function snapCropRectToSourcePixelGrid(state2, imageSize, cropRect) {
    return snapCropRectEdgesToSourcePixels(state2, imageSize, cropRect, {
      left: true,
      top: true,
      right: true,
      bottom: true
    });
  }
  function snapCropRectEdgesToSourcePixels(state2, imageSize, cropRect, edges) {
    if (!isValidSize(imageSize)) {
      return cropRect;
    }
    const stateWithCrop = sanitizeCropperState({ ...state2, cropRect });
    const region = getSourceRegion(stateWithCrop, imageSize);
    const shouldSnapX = edges.left || edges.right;
    const shouldSnapY = edges.top || edges.bottom;
    const left = edges.left ? Math.round(region.x) : region.x;
    const top = edges.top ? Math.round(region.y) : region.y;
    const right = edges.right ? Math.round(region.x + region.width) : region.x + region.width;
    const bottom = edges.bottom ? Math.round(region.y + region.height) : region.y + region.height;
    if (right <= left || bottom <= top) {
      return cropRect;
    }
    const snappedCropRect = getCropRectFromSourceRegion(
      stateWithCrop,
      imageSize,
      {
        ...region,
        x: left,
        y: top,
        width: right - left,
        height: bottom - top
      }
    );
    if (!snappedCropRect) {
      return cropRect;
    }
    return {
      x: shouldSnapX ? snappedCropRect.x : cropRect.x,
      y: shouldSnapY ? snappedCropRect.y : cropRect.y,
      width: shouldSnapX ? snappedCropRect.width : cropRect.width,
      height: shouldSnapY ? snappedCropRect.height : cropRect.height
    };
  }

  // packages/media-editor/build-module/image-editor/react/hooks/use-aria-announcer.mjs
  var ARIA_DEBOUNCE_MS = 300;
  function getFlipAnnouncement(state2, previousState) {
    if (!previousState || previousState.flip.horizontal === state2.flip.horizontal && previousState.flip.vertical === state2.flip.vertical) {
      return void 0;
    }
    const { horizontal, vertical } = state2.flip;
    if (horizontal && vertical) {
      return (0, import_i18n132.__)("Flipped horizontally and vertically");
    }
    if (horizontal) {
      return (0, import_i18n132.__)("Flipped horizontally");
    }
    if (vertical) {
      return (0, import_i18n132.__)("Flipped vertically");
    }
    return (0, import_i18n132.__)("Flip removed");
  }
  function getRotationAnnouncement(state2, previousState) {
    if (previousState && Math.round(previousState.rotation) === Math.round(state2.rotation)) {
      return void 0;
    }
    const singleFlip = state2.flip.horizontal !== state2.flip.vertical;
    const visualDir = singleFlip ? -1 : 1;
    let visualRotation = Math.round(state2.rotation) * visualDir % 360;
    if (visualRotation > 180) {
      visualRotation -= 360;
    }
    if (visualRotation <= -180) {
      visualRotation += 360;
    }
    if (visualRotation === 0) {
      return previousState ? (0, import_i18n132.__)("Rotation 0 degrees") : void 0;
    }
    if (visualRotation > 0) {
      return (0, import_i18n132.sprintf)(
        /* translators: %d: rotation angle in degrees. */
        (0, import_i18n132.__)("Rotated %d degrees clockwise"),
        visualRotation
      );
    }
    return (0, import_i18n132.sprintf)(
      /* translators: %d: rotation angle in degrees. */
      (0, import_i18n132.__)("Rotated %d degrees counterclockwise"),
      Math.abs(visualRotation)
    );
  }
  function getCropAnnouncement(state2, previousState) {
    if (!state2.image) {
      return void 0;
    }
    const imageSize = {
      width: state2.image.naturalWidth,
      height: state2.image.naturalHeight
    };
    const region = getSourceRegion(state2, imageSize);
    if (previousState?.image) {
      const previousRegion = getSourceRegion(
        { ...state2, cropRect: previousState.cropRect },
        imageSize
      );
      if (Math.round(previousRegion.width) === Math.round(region.width) && Math.round(previousRegion.height) === Math.round(region.height)) {
        return void 0;
      }
    }
    return (0, import_i18n132.sprintf)(
      /* translators: 1: crop width in pixels, 2: crop height in pixels. */
      (0, import_i18n132.__)("Crop %1$d by %2$d pixels"),
      Math.round(region.width),
      Math.round(region.height)
    );
  }
  function getZoomAnnouncement(state2, previousState) {
    if (previousState && Math.round(previousState.zoom * 100) === Math.round(state2.zoom * 100)) {
      return void 0;
    }
    return (0, import_i18n132.sprintf)(
      /* translators: %d: zoom level as a percentage. */
      (0, import_i18n132.__)("Zoom %d%%"),
      Math.round(state2.zoom * 100)
    );
  }
  function buildAnnouncement(state2, previousState) {
    const flip4 = getFlipAnnouncement(state2, previousState);
    if (flip4) {
      return flip4;
    }
    const parts = [
      getRotationAnnouncement(state2, previousState),
      getZoomAnnouncement(state2, previousState),
      getCropAnnouncement(state2, previousState)
    ].filter((part) => part !== void 0);
    return parts.join(", ");
  }
  function useAriaAnnouncer(state2) {
    const timerRef = (0, import_element150.useRef)();
    const prevMessageRef = (0, import_element150.useRef)("");
    const prevStateRef = (0, import_element150.useRef)(null);
    const latestStateRef = (0, import_element150.useRef)(state2);
    (0, import_element150.useLayoutEffect)(() => {
      latestStateRef.current = state2;
    }, [state2]);
    (0, import_element150.useEffect)(() => {
      clearTimeout(timerRef.current);
      timerRef.current = setTimeout(() => {
        const current = latestStateRef.current;
        const msg = buildAnnouncement(current, prevStateRef.current);
        prevStateRef.current = current;
        if (msg !== prevMessageRef.current) {
          prevMessageRef.current = msg;
          (0, import_a11y4.speak)(msg);
        }
      }, ARIA_DEBOUNCE_MS);
      return () => {
        clearTimeout(timerRef.current);
      };
    }, [
      state2.zoom,
      state2.rotation,
      state2.cropRect.width,
      state2.cropRect.height,
      state2.flip.horizontal,
      state2.flip.vertical
    ]);
  }

  // packages/media-editor/build-module/image-editor/react/components/stencils/rectangle-stencil.mjs
  var import_element151 = __toESM(require_element(), 1);
  var import_i18n133 = __toESM(require_i18n(), 1);

  // packages/media-editor/build-module/image-editor/react/visually-hidden-style.mjs
  var VISUALLY_HIDDEN_STYLE = {
    position: "absolute",
    width: 1,
    height: 1,
    padding: 0,
    margin: -1,
    overflow: "hidden",
    clip: "rect(0, 0, 0, 0)",
    whiteSpace: "nowrap",
    border: 0
  };

  // packages/media-editor/build-module/image-editor/react/components/stencils/rectangle-stencil.mjs
  var import_jsx_runtime273 = __toESM(require_jsx_runtime(), 1);
  var CORNER_POSITIONS = ["nw", "ne", "se", "sw"];
  var ALL_POSITIONS = [
    "nw",
    "n",
    "ne",
    "e",
    "se",
    "s",
    "sw",
    "w"
  ];
  function getHandleLabel(pos) {
    switch (pos) {
      case "n":
        return (0, import_i18n133.__)("Resize from top edge");
      case "s":
        return (0, import_i18n133.__)("Resize from bottom edge");
      case "e":
        return (0, import_i18n133.__)("Resize from right edge");
      case "w":
        return (0, import_i18n133.__)("Resize from left edge");
      case "nw":
        return (0, import_i18n133.__)("Resize from top-left corner");
      case "ne":
        return (0, import_i18n133.__)("Resize from top-right corner");
      case "sw":
        return (0, import_i18n133.__)("Resize from bottom-left corner");
      case "se":
        return (0, import_i18n133.__)("Resize from bottom-right corner");
    }
  }
  var KEYBOARD_SETTLE_DELAY = 500;
  function RectangleStencil({
    cropRect,
    containerSize,
    imageSize,
    onCropChange,
    onResizeStart,
    onResizeEnd,
    aspectRatio,
    freeformCrop = false,
    isResizeDisabled = false,
    stencilTransition,
    cropBounds,
    onEscape,
    minCropSize,
    snapCropRect,
    keyboardResizeStep
  }) {
    const boundsMinX = cropBounds?.minX ?? 0;
    const boundsMinY = cropBounds?.minY ?? 0;
    const boundsMaxX = cropBounds?.maxX ?? 1;
    const boundsMaxY = cropBounds?.maxY ?? 1;
    const bounds = (0, import_element151.useMemo)(
      () => ({
        minX: boundsMinX,
        minY: boundsMinY,
        maxX: boundsMaxX,
        maxY: boundsMaxY
      }),
      [boundsMinX, boundsMinY, boundsMaxX, boundsMaxY]
    );
    const keyboardSettleTimerRef = (0, import_element151.useRef)();
    const keyboardResizeActiveRef = (0, import_element151.useRef)(false);
    const resizeHandleDescriptionId = (0, import_element151.useId)();
    const hasLockedRatio = !!(aspectRatio && aspectRatio > 0);
    const activePointerResizeRef = (0, import_element151.useRef)(null);
    (0, import_element151.useEffect)(() => {
      return () => {
        clearTimeout(keyboardSettleTimerRef.current);
        keyboardResizeActiveRef.current = false;
        activePointerResizeRef.current?.cancel(false);
      };
    }, []);
    (0, import_element151.useEffect)(() => {
      if (isResizeDisabled) {
        activePointerResizeRef.current?.cancel();
      }
    }, [isResizeDisabled]);
    const latestHandlersRef = (0, import_element151.useRef)(null);
    const normalizedRatio = (0, import_element151.useMemo)(() => {
      if (!hasLockedRatio || imageSize.width === 0) {
        return 0;
      }
      return aspectRatio * imageSize.height / imageSize.width;
    }, [aspectRatio, hasLockedRatio, imageSize.width, imageSize.height]);
    const offsetX = (containerSize.width - imageSize.width) / 2;
    const offsetY = (containerSize.height - imageSize.height) / 2;
    const left = offsetX + cropRect.x * imageSize.width;
    const top = offsetY + cropRect.y * imageSize.height;
    const width = cropRect.width * imageSize.width;
    const height = cropRect.height * imageSize.height;
    const handlePointerDown = (0, import_element151.useCallback)(
      (handle, event) => {
        if (isResizeDisabled || event.pointerType === "touch" && event.isPrimary === false) {
          event.preventDefault();
          event.stopPropagation();
          return;
        }
        if (event.button !== 0) {
          return;
        }
        event.preventDefault();
        event.stopPropagation();
        const ownerDoc = event.currentTarget.ownerDocument;
        if (ownerDoc.activeElement instanceof HTMLElement) {
          ownerDoc.activeElement.blur();
        }
        const el = event.currentTarget;
        el.setPointerCapture(event.pointerId);
        const drag2 = {
          handle,
          startX: event.clientX,
          startY: event.clientY,
          startRect: { ...cropRect }
        };
        let rafId = 0;
        let latestX = event.clientX;
        let latestY = event.clientY;
        let latestShift = event.shiftKey;
        const onMove = (e3) => {
          const pe = e3;
          latestX = pe.clientX;
          latestY = pe.clientY;
          latestShift = pe.shiftKey;
          if (rafId) {
            return;
          }
          rafId = requestAnimationFrame(() => {
            rafId = 0;
            const h3 = latestHandlersRef.current;
            if (!h3) {
              return;
            }
            let newRect;
            if (h3.hasLockedRatio) {
              newRect = h3.computeLockedRect(drag2, latestX, latestY);
            } else if (latestShift) {
              newRect = h3.computeShiftLockedRect(
                drag2,
                latestX,
                latestY
              );
            } else {
              newRect = h3.computeFreeRect(drag2, latestX, latestY);
              newRect = h3.snapCropRect?.(newRect, drag2.handle) ?? newRect;
            }
            h3.onCropChange(newRect);
          });
        };
        let ended = false;
        const endResize = (notifyResizeEnd = true, restoreFocus = true) => {
          if (ended) {
            return;
          }
          ended = true;
          if (rafId) {
            cancelAnimationFrame(rafId);
            rafId = 0;
          }
          el.removeEventListener("pointermove", onMove);
          el.removeEventListener("pointerup", onEnd);
          el.removeEventListener("lostpointercapture", onEnd);
          activePointerResizeRef.current = null;
          if (notifyResizeEnd) {
            latestHandlersRef.current?.onResizeEnd?.();
          }
          if (restoreFocus) {
            el.focus({ preventScroll: true });
          }
        };
        const cancelResize = (notifyResizeEnd = true) => endResize(notifyResizeEnd, false);
        const onEnd = () => endResize();
        el.addEventListener("pointermove", onMove);
        el.addEventListener("pointerup", onEnd);
        el.addEventListener("lostpointercapture", onEnd);
        activePointerResizeRef.current = { cancel: cancelResize };
        onResizeStart?.(handle);
        clearTimeout(keyboardSettleTimerRef.current);
        keyboardResizeActiveRef.current = false;
      },
      [cropRect, isResizeDisabled, onResizeStart]
    );
    const computeFreeRect = (0, import_element151.useCallback)(
      (drag2, clientX, clientY) => computeFreeResizeRect(
        drag2,
        clientX,
        clientY,
        imageSize,
        bounds,
        minCropSize
      ),
      [imageSize, bounds, minCropSize]
    );
    const computeLockedRect = (0, import_element151.useCallback)(
      (drag2, clientX, clientY, driverAxis) => computeLockedResizeRect(
        drag2,
        clientX,
        clientY,
        imageSize,
        bounds,
        normalizedRatio,
        minCropSize,
        driverAxis
      ),
      [imageSize, bounds, normalizedRatio, minCropSize]
    );
    const computeShiftLockedRect = (0, import_element151.useCallback)(
      (drag2, clientX, clientY) => computeShiftLockedResizeRect(
        drag2,
        clientX,
        clientY,
        imageSize,
        bounds,
        minCropSize
      ),
      [imageSize, bounds, minCropSize]
    );
    latestHandlersRef.current = {
      hasLockedRatio,
      computeLockedRect,
      computeFreeRect,
      computeShiftLockedRect,
      onCropChange,
      onResizeEnd,
      snapCropRect
    };
    const handleKeyDown = (0, import_element151.useCallback)(
      (handle, event) => {
        const key = event.key;
        if (isResizeDisabled) {
          return;
        }
        if (key === "Escape") {
          event.preventDefault();
          event.stopPropagation();
          onEscape?.();
          return;
        }
        if (key !== "ArrowUp" && key !== "ArrowDown" && key !== "ArrowLeft" && key !== "ArrowRight") {
          return;
        }
        event.preventDefault();
        event.stopPropagation();
        if (!keyboardResizeActiveRef.current) {
          keyboardResizeActiveRef.current = true;
          onResizeStart?.(handle);
        }
        const scheduleKeyboardResizeEnd = () => {
          clearTimeout(keyboardSettleTimerRef.current);
          keyboardSettleTimerRef.current = setTimeout(() => {
            keyboardResizeActiveRef.current = false;
            onResizeEnd?.();
          }, KEYBOARD_SETTLE_DELAY);
        };
        const stepMultiplier = event.shiftKey ? KEYBOARD_SHIFT_STEP_MULTIPLIER : 1;
        const stepX = keyboardResizeStep?.width ?? DEFAULT_KEYBOARD_STEP;
        const stepY = keyboardResizeStep?.height ?? DEFAULT_KEYBOARD_STEP;
        const adjustedStepX = stepX * stepMultiplier;
        const adjustedStepY = stepY * stepMultiplier;
        let dx = 0;
        let dy = 0;
        if (key === "ArrowLeft") {
          dx = -adjustedStepX;
        }
        if (key === "ArrowRight") {
          dx = adjustedStepX;
        }
        if (key === "ArrowUp") {
          dy = -adjustedStepY;
        }
        if (key === "ArrowDown") {
          dy = adjustedStepY;
        }
        const keyboardDriverAxis = dx !== 0 ? "width" : "height";
        if (hasLockedRatio) {
          const syntheticDrag = {
            handle,
            startX: 0,
            startY: 0,
            startRect: { ...cropRect }
          };
          const clientX = dx * imageSize.width;
          const clientY = dy * imageSize.height;
          onCropChange(
            computeLockedRect(
              syntheticDrag,
              clientX,
              clientY,
              keyboardDriverAxis
            )
          );
          scheduleKeyboardResizeEnd();
        } else {
          const syntheticDrag = {
            handle,
            startX: 0,
            startY: 0,
            startRect: { ...cropRect }
          };
          const clientX = dx * imageSize.width;
          const clientY = dy * imageSize.height;
          const rect = computeFreeRect(syntheticDrag, clientX, clientY);
          onCropChange(snapCropRect?.(rect, handle) ?? rect);
          scheduleKeyboardResizeEnd();
        }
      },
      [
        cropRect,
        hasLockedRatio,
        imageSize.width,
        imageSize.height,
        computeLockedRect,
        computeFreeRect,
        onCropChange,
        onResizeStart,
        onResizeEnd,
        onEscape,
        keyboardResizeStep,
        snapCropRect,
        isResizeDisabled
      ]
    );
    if (containerSize.width === 0 || containerSize.height === 0) {
      return null;
    }
    const handles = hasLockedRatio ? CORNER_POSITIONS : ALL_POSITIONS;
    return /* @__PURE__ */ (0, import_jsx_runtime273.jsxs)(
      "div",
      {
        className: "wp-media-editor-image-editor__stencil",
        "data-testid": "cropper-stencil",
        style: {
          left,
          top,
          width,
          height,
          transition: stencilTransition
        },
        children: [
          freeformCrop && /* @__PURE__ */ (0, import_jsx_runtime273.jsx)(
            "div",
            {
              id: resizeHandleDescriptionId,
              style: VISUALLY_HIDDEN_STYLE,
              children: (0, import_i18n133.__)(
                "Use arrow keys to resize the crop area. Hold Shift for larger steps."
              )
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime273.jsx)(
            "div",
            {
              className: "wp-media-editor-image-editor__stencil-rect",
              style: {
                width: "100%",
                height: "100%",
                top: 0,
                left: 0
              }
            }
          ),
          freeformCrop && handles.map((pos) => /* @__PURE__ */ (0, import_jsx_runtime273.jsx)(
            "button",
            {
              type: "button",
              className: `wp-media-editor-image-editor__handle wp-media-editor-image-editor__handle--${pos}`,
              onPointerDown: (event) => handlePointerDown(pos, event),
              onTouchStart: (event) => {
                if (event.touches.length < 2) {
                  event.stopPropagation();
                }
              },
              onKeyDown: (event) => handleKeyDown(pos, event),
              "aria-label": getHandleLabel(pos),
              "aria-describedby": resizeHandleDescriptionId
            },
            pos
          ))
        ]
      }
    );
  }

  // packages/media-editor/build-module/image-editor/react/components/overlays/dimming-overlay.mjs
  var import_jsx_runtime274 = __toESM(require_jsx_runtime(), 1);
  function DimmingOverlay({
    cropRect,
    containerSize,
    imageSize,
    transition
  }) {
    if (containerSize.width === 0 || containerSize.height === 0) {
      return null;
    }
    const offsetX = (containerSize.width - imageSize.width) / 2;
    const offsetY = (containerSize.height - imageSize.height) / 2;
    const left = offsetX + cropRect.x * imageSize.width;
    const top = offsetY + cropRect.y * imageSize.height;
    const width = cropRect.width * imageSize.width;
    const height = cropRect.height * imageSize.height;
    const composedTransition = transition ? `${transition}, box-shadow 0.15s ease` : void 0;
    return /* @__PURE__ */ (0, import_jsx_runtime274.jsx)(
      "div",
      {
        className: "wp-media-editor-image-editor__dimming",
        "data-testid": "cropper-dimming",
        style: {
          left,
          top,
          width,
          height,
          transition: composedTransition
        }
      }
    );
  }

  // packages/media-editor/build-module/image-editor/react/components/overlays/grid-overlay.mjs
  var import_jsx_runtime275 = __toESM(require_jsx_runtime(), 1);
  function GridOverlay({
    cropRect,
    containerSize,
    imageSize
  }) {
    if (containerSize.width === 0 || containerSize.height === 0) {
      return null;
    }
    const offsetX = (containerSize.width - imageSize.width) / 2;
    const offsetY = (containerSize.height - imageSize.height) / 2;
    const left = offsetX + cropRect.x * imageSize.width;
    const top = offsetY + cropRect.y * imageSize.height;
    const width = cropRect.width * imageSize.width;
    const height = cropRect.height * imageSize.height;
    const thirdW = width / 3;
    const thirdH = height / 3;
    return /* @__PURE__ */ (0, import_jsx_runtime275.jsxs)(
      "div",
      {
        className: "wp-media-editor-image-editor__grid",
        "data-testid": "cropper-grid",
        style: {
          left,
          top,
          width,
          height
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(
            "div",
            {
              className: "wp-media-editor-image-editor__grid-line wp-media-editor-image-editor__grid-line--horizontal",
              style: { top: thirdH }
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(
            "div",
            {
              className: "wp-media-editor-image-editor__grid-line wp-media-editor-image-editor__grid-line--horizontal",
              style: { top: thirdH * 2 }
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(
            "div",
            {
              className: "wp-media-editor-image-editor__grid-line wp-media-editor-image-editor__grid-line--vertical",
              style: { left: thirdW }
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime275.jsx)(
            "div",
            {
              className: "wp-media-editor-image-editor__grid-line wp-media-editor-image-editor__grid-line--vertical",
              style: { left: thirdW * 2 }
            }
          )
        ]
      }
    );
  }

  // packages/media-editor/build-module/image-editor/react/components/overlays/dimensions-overlay.mjs
  var import_element152 = __toESM(require_element(), 1);
  var import_jsx_runtime276 = __toESM(require_jsx_runtime(), 1);
  var HANDLE_GAP_PX = 12;
  var TRANSLATE_PERCENT = {
    before: "-100%",
    center: "-50%",
    after: "0"
  };
  var GAP_DIRECTION = {
    before: -1,
    center: 0,
    after: 1
  };
  var OPPOSITE_SIDE = {
    before: "after",
    center: "center",
    after: "before"
  };
  function preferredAnchor(handle) {
    let x2 = "center";
    if (handle.includes("w")) {
      x2 = "before";
    } else if (handle.includes("e")) {
      x2 = "after";
    }
    let y3 = "center";
    if (handle.includes("n")) {
      y3 = "before";
    } else if (handle.includes("s")) {
      y3 = "after";
    }
    return { x: x2, y: y3 };
  }
  function sideStart(side, handlePos, length2) {
    if (side === "before") {
      return handlePos - HANDLE_GAP_PX - length2;
    }
    if (side === "after") {
      return handlePos + HANDLE_GAP_PX;
    }
    return handlePos - length2 / 2;
  }
  function fittingSide(preferred, handlePos, length2, containerLength) {
    const fits = (side) => {
      const start2 = sideStart(side, handlePos, length2);
      return start2 >= 0 && start2 + length2 <= containerLength;
    };
    if (fits(preferred)) {
      return preferred;
    }
    const opposite = OPPOSITE_SIDE[preferred];
    if (opposite !== preferred && fits(opposite)) {
      return opposite;
    }
    if (preferred !== "center" && fits("center")) {
      return "center";
    }
    const overflow = (side) => {
      const start2 = sideStart(side, handlePos, length2);
      return Math.max(0, -start2) + Math.max(0, start2 + length2 - containerLength);
    };
    const candidates = [preferred, opposite, "center"];
    return candidates.reduce(
      (best, side) => overflow(side) < overflow(best) ? side : best
    );
  }
  function DimensionsOverlay({
    cropRect,
    containerSize,
    imageSize,
    activeHandle,
    outputWidth,
    outputHeight
  }) {
    const tooltipRef = (0, import_element152.useRef)(null);
    const [tooltipSize, setTooltipSize] = (0, import_element152.useState)(null);
    (0, import_element152.useLayoutEffect)(() => {
      if (!tooltipRef.current) {
        return;
      }
      const rect = tooltipRef.current.getBoundingClientRect();
      setTooltipSize((prev) => {
        if (prev && prev.width === rect.width && prev.height === rect.height) {
          return prev;
        }
        return { width: rect.width, height: rect.height };
      });
    }, [outputWidth, outputHeight]);
    if (!activeHandle || containerSize.width === 0 || containerSize.height === 0) {
      return null;
    }
    const offsetX = (containerSize.width - imageSize.width) / 2;
    const offsetY = (containerSize.height - imageSize.height) / 2;
    const left = offsetX + cropRect.x * imageSize.width;
    const top = offsetY + cropRect.y * imageSize.height;
    const width = cropRect.width * imageSize.width;
    const height = cropRect.height * imageSize.height;
    let handleX = left + width / 2;
    if (activeHandle.includes("w")) {
      handleX = left;
    } else if (activeHandle.includes("e")) {
      handleX = left + width;
    }
    let handleY = top + height / 2;
    if (activeHandle.includes("n")) {
      handleY = top;
    } else if (activeHandle.includes("s")) {
      handleY = top + height;
    }
    const preferred = preferredAnchor(activeHandle);
    const anchor = tooltipSize ? {
      x: fittingSide(
        preferred.x,
        handleX,
        tooltipSize.width,
        containerSize.width
      ),
      y: fittingSide(
        preferred.y,
        handleY,
        tooltipSize.height,
        containerSize.height
      )
    } : preferred;
    return /* @__PURE__ */ (0, import_jsx_runtime276.jsx)(
      "div",
      {
        ref: tooltipRef,
        className: "wp-media-editor-image-editor__dimensions-tooltip",
        "data-testid": "cropper-dimensions-tooltip",
        style: {
          left: handleX + GAP_DIRECTION[anchor.x] * HANDLE_GAP_PX,
          top: handleY + GAP_DIRECTION[anchor.y] * HANDLE_GAP_PX,
          transform: `translate(${TRANSLATE_PERCENT[anchor.x]}, ${TRANSLATE_PERCENT[anchor.y]})`
        },
        "aria-hidden": "true",
        children: `W: ${Math.round(outputWidth)}px H: ${Math.round(
          outputHeight
        )}px`
      }
    );
  }

  // packages/media-editor/build-module/image-editor/react/components/viewport-provider.mjs
  var import_element154 = __toESM(require_element(), 1);

  // packages/media-editor/build-module/image-editor/react/hooks/use-viewport-state.mjs
  var import_element153 = __toESM(require_element(), 1);

  // packages/media-editor/build-module/image-editor/core/viewport-state.mjs
  var DEFAULT_VIEWPORT_STATE = {
    zoom: 1,
    pan: { x: 0, y: 0 }
  };
  function viewportReducer(state2, action) {
    switch (action.type) {
      case "SET_VIEWPORT_ZOOM": {
        const zoom = Math.min(4, Math.max(0.1, action.payload));
        return zoom === state2.zoom ? state2 : { ...state2, zoom };
      }
      case "SET_VIEWPORT_PAN": {
        const { x: x2, y: y3 } = action.payload;
        return x2 === state2.pan.x && y3 === state2.pan.y ? state2 : { ...state2, pan: action.payload };
      }
      case "RESET_VIEWPORT":
        return state2.zoom === DEFAULT_VIEWPORT_STATE.zoom && state2.pan.x === DEFAULT_VIEWPORT_STATE.pan.x && state2.pan.y === DEFAULT_VIEWPORT_STATE.pan.y ? state2 : DEFAULT_VIEWPORT_STATE;
    }
  }

  // packages/media-editor/build-module/image-editor/react/hooks/use-viewport-state.mjs
  function useViewportState() {
    const [viewport, dispatch8] = (0, import_element153.useReducer)(
      viewportReducer,
      DEFAULT_VIEWPORT_STATE
    );
    const setViewportZoom = (0, import_element153.useCallback)((zoom) => {
      dispatch8({ type: "SET_VIEWPORT_ZOOM", payload: zoom });
    }, []);
    const setViewportPan = (0, import_element153.useCallback)((pan) => {
      dispatch8({ type: "SET_VIEWPORT_PAN", payload: pan });
    }, []);
    const resetViewport = (0, import_element153.useCallback)(() => {
      dispatch8({ type: "RESET_VIEWPORT" });
    }, []);
    return (0, import_element153.useMemo)(
      () => ({ viewport, setViewportZoom, setViewportPan, resetViewport }),
      [viewport, setViewportZoom, setViewportPan, resetViewport]
    );
  }

  // packages/media-editor/build-module/image-editor/react/components/viewport-provider.mjs
  var import_jsx_runtime277 = __toESM(require_jsx_runtime(), 1);
  var ViewportContext = (0, import_element154.createContext)(null);
  function ViewportProvider({
    children
  }) {
    const viewportState = useViewportState();
    return /* @__PURE__ */ (0, import_jsx_runtime277.jsx)(ViewportContext.Provider, { value: viewportState, children });
  }
  function useViewport() {
    const context = (0, import_element154.useContext)(ViewportContext);
    if (!context) {
      throw new Error(
        "useViewport must be used within a ViewportProvider."
      );
    }
    return context;
  }

  // packages/media-editor/build-module/image-editor/react/components/cropper.mjs
  var import_jsx_runtime278 = __toESM(require_jsx_runtime(), 1);
  var CROP_RECT_EPSILON = 1e-6;
  var CARDINAL_ROTATION_EPSILON2 = 1e-6;
  var SETTLE_TRANSITION_DURATION_MS = 200;
  var SETTLE_TRANSITION_FALLBACK_MS = SETTLE_TRANSITION_DURATION_MS + 100;
  var SETTLE_TRANSFORM_TRANSITION = `transform ${SETTLE_TRANSITION_DURATION_MS}ms ease-out`;
  var SETTLE_STENCIL_TRANSITION = [
    `left ${SETTLE_TRANSITION_DURATION_MS}ms ease-out`,
    `top ${SETTLE_TRANSITION_DURATION_MS}ms ease-out`,
    `width ${SETTLE_TRANSITION_DURATION_MS}ms ease-out`,
    `height ${SETTLE_TRANSITION_DURATION_MS}ms ease-out`
  ].join(", ");
  function CropperInner({
    src,
    controller,
    stencil: StencilComponent = RectangleStencil,
    showGrid = false,
    isPlacementActive = false,
    showDimming = true,
    showDimensions = true,
    minZoom,
    maxZoom,
    aspectRatio,
    freeformCrop = false,
    focusOnMount = false,
    onImageLoaded,
    onStateChange,
    onGestureStart,
    onGestureEnd,
    className
  }, ref) {
    const {
      state: state2,
      setImage,
      setCropRect,
      settleCrop,
      setVisualSize,
      adjustCropRectForViewport
    } = controller;
    const {
      viewport: viewportState,
      setViewportPan,
      resetViewport
    } = useViewport();
    const canvasRef = (0, import_element155.useRef)(null);
    const cropAreaDescriptionId = (0, import_element155.useId)();
    const [isCropAreaFocused, setIsCropAreaFocused] = (0, import_element155.useState)(focusOnMount);
    const [isFocusVisible, setIsFocusVisible] = (0, import_element155.useState)(false);
    const [canvasSize, setCanvasSize] = (0, import_element155.useState)({
      width: 0,
      height: 0
    });
    (0, import_element155.useLayoutEffect)(() => {
      if (focusOnMount) {
        canvasRef.current?.focus({ preventScroll: true });
      }
    }, [focusOnMount]);
    const handleCropAreaFocus = (0, import_element155.useCallback)(
      (event) => {
        const target = event.target;
        if (target === event.currentTarget) {
          setIsCropAreaFocused(true);
        }
        if (event.relatedTarget !== null && target.matches(":focus-visible")) {
          setIsFocusVisible(true);
        }
      },
      []
    );
    const handleCropAreaBlur = (0, import_element155.useCallback)(
      (event) => {
        if (event.target === event.currentTarget) {
          setIsCropAreaFocused(false);
        }
        if (!event.currentTarget.contains(
          event.relatedTarget
        )) {
          setIsFocusVisible(false);
        }
      },
      []
    );
    (0, import_element155.useEffect)(() => {
      const element = canvasRef.current;
      if (!element) {
        return;
      }
      const observer = new ResizeObserver((entries) => {
        for (const entry of entries) {
          const { width, height } = entry.contentRect;
          setCanvasSize((prev) => {
            if (prev.width === width && prev.height === height) {
              return prev;
            }
            return { width, height };
          });
        }
      });
      observer.observe(element);
      return () => {
        observer.disconnect();
      };
    }, []);
    (0, import_element155.useEffect)(() => {
      onStateChange?.(state2);
    }, [state2, onStateChange]);
    useAriaAnnouncer(state2);
    const naturalWidth = state2.image?.naturalWidth ?? 0;
    const naturalHeight = state2.image?.naturalHeight ?? 0;
    const { elementSize, visualSize } = (0, import_element155.useMemo)(
      () => getImageFit(
        canvasSize,
        { width: naturalWidth, height: naturalHeight },
        state2.rotation
      ),
      [canvasSize, naturalWidth, naturalHeight, state2.rotation]
    );
    (0, import_element155.useEffect)(() => {
      setVisualSize(visualSize);
    }, [visualSize, setVisualSize]);
    (0, import_element155.useEffect)(() => {
      if (freeformCrop || visualSize.width === 0 || visualSize.height === 0 || !aspectRatio || aspectRatio <= 0) {
        return;
      }
      const rect = computeInscribedRect(aspectRatio, visualSize);
      const current = state2.cropRect;
      if (Math.abs(current.x - rect.x) < CROP_RECT_EPSILON && Math.abs(current.y - rect.y) < CROP_RECT_EPSILON && Math.abs(current.width - rect.width) < CROP_RECT_EPSILON && Math.abs(current.height - rect.height) < CROP_RECT_EPSILON) {
        return;
      }
      adjustCropRectForViewport(rect);
    }, [
      freeformCrop,
      aspectRatio,
      visualSize,
      adjustCropRectForViewport,
      state2.cropRect
    ]);
    const prevAspectRatioRef = (0, import_element155.useRef)(aspectRatio);
    (0, import_element155.useEffect)(() => {
      if (prevAspectRatioRef.current === aspectRatio) {
        return;
      }
      prevAspectRatioRef.current = aspectRatio;
      if (!freeformCrop || visualSize.width === 0 || visualSize.height === 0 || !aspectRatio || aspectRatio <= 0) {
        return;
      }
      const rect = computeInscribedRect(aspectRatio, visualSize);
      const current = state2.cropRect;
      if (Math.abs(current.x - rect.x) < CROP_RECT_EPSILON && Math.abs(current.y - rect.y) < CROP_RECT_EPSILON && Math.abs(current.width - rect.width) < CROP_RECT_EPSILON && Math.abs(current.height - rect.height) < CROP_RECT_EPSILON) {
        return;
      }
      adjustCropRectForViewport(rect);
    }, [
      aspectRatio,
      freeformCrop,
      visualSize,
      adjustCropRectForViewport,
      state2.cropRect
    ]);
    const cropBounds = (0, import_element155.useMemo)(() => {
      if (!state2.image || elementSize.width === 0) {
        return void 0;
      }
      return getImageCropBounds(state2, elementSize, visualSize);
    }, [state2, elementSize, visualSize]);
    const effectiveMinZoom = minZoom !== void 0 ? minZoom : getMinZoom(state2);
    const [isResizing, setIsResizing] = (0, import_element155.useState)(false);
    const isResizingRef = (0, import_element155.useRef)(false);
    const isSettlingRef = (0, import_element155.useRef)(false);
    const [isTouchPinching, setIsTouchPinchingState] = (0, import_element155.useState)(false);
    const isTouchPinchingRef = (0, import_element155.useRef)(false);
    const setTouchPinching = (0, import_element155.useCallback)((isPinching) => {
      isTouchPinchingRef.current = isPinching;
      setIsTouchPinchingState(isPinching);
    }, []);
    const [activeHandle, setActiveHandle] = (0, import_element155.useState)(
      null
    );
    const viewScaleRest = (0, import_element155.useMemo)(
      () => getViewScale(
        state2.cropRect,
        canvasSize,
        visualSize,
        SETTLE_TARGET_CANVAS_FILL,
        MAX_VIEW_SCALE
      ),
      [state2.cropRect, canvasSize, visualSize]
    );
    const [frozenViewScale, setFrozenViewScale] = (0, import_element155.useState)(1);
    const viewScale = isResizing ? frozenViewScale : viewScaleRest;
    const scaledVisualSize = (0, import_element155.useMemo)(
      () => ({
        width: visualSize.width * viewScale,
        height: visualSize.height * viewScale
      }),
      [visualSize.width, visualSize.height, viewScale]
    );
    const displayScale = naturalWidth > 0 ? elementSize.width / naturalWidth * state2.zoom * viewScale : 0;
    const keyboardResizeStep = (0, import_element155.useMemo)(() => {
      if (displayScale < PIXEL_SNAP_DISPLAY_SCALE || aspectRatio && aspectRatio > 0 || naturalWidth <= 0 || naturalHeight <= 0) {
        return void 0;
      }
      const snapRotation = Math.round(state2.rotation / 90) * 90;
      if (Math.abs(state2.rotation - snapRotation) >= CARDINAL_ROTATION_EPSILON2) {
        return void 0;
      }
      const bbox = getRotatedBBox(
        naturalWidth,
        naturalHeight,
        snapRotation
      );
      if (bbox.width <= 0 || bbox.height <= 0) {
        return void 0;
      }
      return {
        width: state2.zoom / bbox.width,
        height: state2.zoom / bbox.height
      };
    }, [
      displayScale,
      aspectRatio,
      naturalWidth,
      naturalHeight,
      state2.rotation,
      state2.zoom
    ]);
    const minCropSize = (0, import_element155.useMemo)(() => {
      if (naturalWidth <= 0 || naturalHeight <= 0) {
        return void 0;
      }
      const snapRotation = Math.round(state2.rotation / 90) * 90;
      const bbox = getRotatedBBox(
        naturalWidth,
        naturalHeight,
        snapRotation
      );
      const minPixels = getMinCropPixels(displayScale);
      return {
        width: Math.min(1, minPixels * state2.zoom / bbox.width),
        height: Math.min(1, minPixels * state2.zoom / bbox.height)
      };
    }, [
      naturalWidth,
      naturalHeight,
      state2.rotation,
      state2.zoom,
      displayScale
    ]);
    const snapCropRect = (0, import_element155.useCallback)(
      (rect, handle) => {
        if (displayScale < PIXEL_SNAP_DISPLAY_SCALE || naturalWidth <= 0 || naturalHeight <= 0) {
          return rect;
        }
        return snapCropRectToSourcePixels(
          state2,
          { width: naturalWidth, height: naturalHeight },
          rect,
          handle
        );
      },
      [displayScale, naturalWidth, naturalHeight, state2]
    );
    const wasPixelSnapEnabledRef = (0, import_element155.useRef)(false);
    (0, import_element155.useEffect)(() => {
      const isPixelSnapEnabled = freeformCrop && (!aspectRatio || aspectRatio <= 0) && displayScale >= PIXEL_SNAP_DISPLAY_SCALE && naturalWidth > 0 && naturalHeight > 0;
      const wasPixelSnapEnabled = wasPixelSnapEnabledRef.current;
      wasPixelSnapEnabledRef.current = isPixelSnapEnabled;
      if (!isPixelSnapEnabled || wasPixelSnapEnabled) {
        return;
      }
      const snappedCropRect = snapCropRectToSourcePixelGrid(
        state2,
        { width: naturalWidth, height: naturalHeight },
        state2.cropRect
      );
      const currentCropRect = state2.cropRect;
      if (Math.abs(currentCropRect.x - snappedCropRect.x) < CROP_RECT_EPSILON && Math.abs(currentCropRect.y - snappedCropRect.y) < CROP_RECT_EPSILON && Math.abs(currentCropRect.width - snappedCropRect.width) < CROP_RECT_EPSILON && Math.abs(currentCropRect.height - snappedCropRect.height) < CROP_RECT_EPSILON) {
        return;
      }
      setCropRect(snappedCropRect);
    }, [
      aspectRatio,
      displayScale,
      freeformCrop,
      naturalWidth,
      naturalHeight,
      setCropRect,
      state2
    ]);
    const {
      handlers,
      onWheelNative,
      isDragging,
      isZooming,
      isPlacementActive: isInteractionPlacementActive
    } = useInteraction(state2, controller, canvasSize, scaledVisualSize, {
      minZoom: effectiveMinZoom,
      maxZoom,
      onGestureStart,
      onGestureEnd
    });
    const canvasHandlers = {
      ...handlers,
      onPointerDownCapture: () => {
        setIsFocusVisible(false);
      },
      onTouchStartCapture: (event) => {
        if (event.touches.length > 1) {
          setTouchPinching(true);
        }
      },
      onTouchMoveCapture: (event) => {
        if (event.touches.length > 1) {
          setTouchPinching(true);
        }
      },
      onTouchEndCapture: (event) => {
        if (event.touches.length === 0) {
          setTouchPinching(false);
        }
      },
      onTouchCancelCapture: (event) => {
        if (event.touches.length === 0) {
          setTouchPinching(false);
        }
      },
      onKeyDownCapture: (event) => {
        if (!["Shift", "Control", "Alt", "Meta"].includes(event.key)) {
          setIsFocusVisible(true);
        }
      },
      onPointerDown: (event) => {
        if (isResizingRef.current || isTouchPinchingRef.current || event.pointerType === "touch" && event.isPrimary === false) {
          event.preventDefault();
          return;
        }
        handlers.onPointerDown?.(event);
        setIsFocusVisible(false);
      }
    };
    (0, import_element155.useEffect)(() => {
      const el = canvasRef.current;
      if (!el) {
        return;
      }
      const handleWheel = (event) => {
        if (isResizingRef.current || isSettlingRef.current) {
          event.preventDefault();
          return;
        }
        onWheelNative(event);
      };
      el.addEventListener("wheel", handleWheel, {
        passive: false
      });
      return () => {
        el.removeEventListener("wheel", handleWheel);
      };
    }, [onWheelNative]);
    const transformString = useTransformStyle(state2, visualSize);
    const handleImageLoad = (0, import_element155.useCallback)(
      (event) => {
        const img = event.currentTarget;
        const size4 = {
          width: img.naturalWidth,
          height: img.naturalHeight
        };
        setImage({
          src,
          naturalWidth: size4.width,
          naturalHeight: size4.height
        });
        onImageLoaded?.(size4);
      },
      [src, setImage, onImageLoaded]
    );
    const handleCropChange = (0, import_element155.useCallback)(
      (rect) => {
        if (isTouchPinchingRef.current) {
          return;
        }
        setCropRect(rect);
        if (isResizingRef.current && scaledVisualSize.width > 0 && scaledVisualSize.height > 0) {
          const offsetX = (canvasSize.width - scaledVisualSize.width) / 2;
          const offsetY = (canvasSize.height - scaledVisualSize.height) / 2;
          const rightOverflow = Math.max(
            0,
            offsetX + (rect.x + rect.width) * scaledVisualSize.width - canvasSize.width
          );
          const leftOverflow = Math.max(
            0,
            -(offsetX + rect.x * scaledVisualSize.width)
          );
          const bottomOverflow = Math.max(
            0,
            offsetY + (rect.y + rect.height) * scaledVisualSize.height - canvasSize.height
          );
          const topOverflow = Math.max(
            0,
            -(offsetY + rect.y * scaledVisualSize.height)
          );
          setViewportPan({
            x: -rightOverflow + leftOverflow,
            y: -bottomOverflow + topOverflow
          });
        }
      },
      [setCropRect, setViewportPan, canvasSize, scaledVisualSize]
    );
    const [settling, setSettling] = (0, import_element155.useState)(false);
    const settleTimerRef = (0, import_element155.useRef)();
    const finishSettling = (0, import_element155.useCallback)(() => {
      clearTimeout(settleTimerRef.current);
      isSettlingRef.current = false;
      setSettling(false);
    }, []);
    (0, import_element155.useEffect)(() => {
      return () => {
        clearTimeout(settleTimerRef.current);
      };
    }, []);
    const isInteractiveGrid = showGrid === "interactive";
    const showInteractiveGrid = isInteractiveGrid && (isInteractionPlacementActive || isResizing || isPlacementActive);
    const outputSize = (0, import_element155.useMemo)(() => {
      if (!showDimensions || !activeHandle || !state2.image) {
        return null;
      }
      const region = getSourceRegion(state2, {
        width: state2.image.naturalWidth,
        height: state2.image.naturalHeight
      });
      return { width: region.width, height: region.height };
    }, [showDimensions, activeHandle, state2]);
    const handleEscape = (0, import_element155.useCallback)(() => {
      setIsFocusVisible(true);
      canvasRef.current?.focus({ preventScroll: true });
    }, []);
    const handleResizeStart = (0, import_element155.useCallback)(
      (handle) => {
        if (isTouchPinchingRef.current) {
          return;
        }
        setFrozenViewScale(viewScaleRest);
        isResizingRef.current = true;
        setIsResizing(true);
        setActiveHandle(handle ?? null);
        finishSettling();
        resetViewport();
        onGestureStart?.();
      },
      [finishSettling, onGestureStart, resetViewport, viewScaleRest]
    );
    const handleResizeEnd = (0, import_element155.useCallback)(() => {
      const isCancellingForPinch = isTouchPinchingRef.current;
      isResizingRef.current = false;
      setIsResizing(false);
      setActiveHandle(null);
      clearTimeout(settleTimerRef.current);
      if (isCancellingForPinch) {
        finishSettling();
        resetViewport();
        return;
      }
      isSettlingRef.current = true;
      setSettling(true);
      resetViewport();
      settleCrop();
      onGestureEnd?.();
      settleTimerRef.current = setTimeout(
        finishSettling,
        SETTLE_TRANSITION_FALLBACK_MS
      );
    }, [finishSettling, settleCrop, onGestureEnd, resetViewport]);
    const handleSettleTransitionEnd = (0, import_element155.useCallback)(
      (event) => {
        if (!isSettlingRef.current || event.propertyName !== "transform") {
          return;
        }
        finishSettling();
      },
      [finishSettling]
    );
    let imageTransition;
    if (settling) {
      imageTransition = SETTLE_TRANSFORM_TRANSITION;
    } else if (isZooming) {
      imageTransition = "transform 150ms linear";
    }
    const settleStencilTransition = settling ? SETTLE_STENCIL_TRANSITION : void 0;
    const imageStyle = (0, import_element155.useMemo)(() => {
      if (elementSize.width === 0 || elementSize.height === 0) {
        return {};
      }
      const centerX = (canvasSize.width - elementSize.width) / 2;
      const centerY = (canvasSize.height - elementSize.height) / 2;
      return {
        width: elementSize.width,
        height: elementSize.height,
        maxWidth: elementSize.width,
        maxHeight: elementSize.height,
        left: centerX,
        top: centerY,
        // Always lead with `scale()` (identity at rest) so the transform's
        // function list stays structurally constant across rest, resize, and
        // settle. A conditional that dropped `scale()` at viewScale === 1
        // would change the list shape exactly when the settle transition
        // crosses 1:1, forcing the browser to fall back to matrix-decomposition
        // interpolation instead of interpolating each function in turn.
        transform: `scale(${viewScale}) ${transformString}`,
        transition: imageTransition,
        imageRendering: displayScale > 1 ? "pixelated" : void 0
      };
    }, [
      canvasSize,
      elementSize,
      transformString,
      imageTransition,
      displayScale,
      viewScale
    ]);
    const settleTransition = settling ? SETTLE_TRANSFORM_TRANSITION : void 0;
    const willChange = isResizing || settling ? "transform" : void 0;
    let stageStyle;
    if (viewportState.pan.x !== 0 || viewportState.pan.y !== 0) {
      stageStyle = {
        transform: `translate(${viewportState.pan.x}px, ${viewportState.pan.y}px)`,
        transition: settleTransition,
        willChange
      };
    } else if (settling) {
      stageStyle = {
        transform: "translate(0px, 0px)",
        transition: settleTransition,
        willChange
      };
    }
    const setContainerRef = (0, import_element155.useCallback)(
      (element) => {
        if (typeof ref === "function") {
          ref(element);
        } else if (ref) {
          ref.current = element;
        }
      },
      [ref]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
      "div",
      {
        ref: setContainerRef,
        className: clsx_default(
          "wp-media-editor-image-editor",
          isDragging && "wp-media-editor-image-editor--dragging",
          className
        ),
        children: /* @__PURE__ */ (0, import_jsx_runtime278.jsxs)(
          "div",
          {
            ref: canvasRef,
            className: clsx_default(
              "wp-media-editor-image-editor__canvas",
              isInteractiveGrid && "wp-media-editor-image-editor__canvas--grid-interactive",
              showInteractiveGrid && "wp-media-editor-image-editor__canvas--show-grid",
              settling && "wp-media-editor-image-editor__canvas--settling",
              // Marks the cropper as in keyboard-interaction mode.
              // CSS uses :focus on the canvas to show the stencil
              // outline and :focus on a handle to show its ring,
              // so the class applies whenever any cropper element
              // has keyboard focus.
              isFocusVisible && "wp-media-editor-image-editor__canvas--focus-visible"
            ),
            tabIndex: 0,
            role: "group",
            "aria-label": (0, import_i18n134.__)("Crop area"),
            "aria-describedby": isCropAreaFocused ? cropAreaDescriptionId : void 0,
            onFocus: handleCropAreaFocus,
            onBlur: handleCropAreaBlur,
            ...canvasHandlers,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
                "div",
                {
                  id: cropAreaDescriptionId,
                  style: VISUALLY_HIDDEN_STYLE,
                  children: (0, import_i18n134.__)(
                    "When this area is focused, use arrow keys to move the image and plus or minus to zoom. Tab to resize handles and controls."
                  )
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime278.jsxs)(
                "div",
                {
                  className: "wp-media-editor-image-editor__stage",
                  "data-testid": "cropper-stage",
                  style: stageStyle,
                  onTransitionEnd: handleSettleTransitionEnd,
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
                      "img",
                      {
                        className: "wp-media-editor-image-editor__image",
                        "data-testid": "cropper-image",
                        src,
                        alt: "",
                        onLoad: handleImageLoad,
                        style: imageStyle,
                        draggable: false
                      }
                    ),
                    showDimming && /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
                      DimmingOverlay,
                      {
                        cropRect: state2.cropRect,
                        containerSize: canvasSize,
                        imageSize: scaledVisualSize,
                        transition: settleStencilTransition
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
                      StencilComponent,
                      {
                        cropRect: state2.cropRect,
                        containerSize: canvasSize,
                        imageSize: scaledVisualSize,
                        onCropChange: handleCropChange,
                        onResizeStart: handleResizeStart,
                        onResizeEnd: handleResizeEnd,
                        onEscape: handleEscape,
                        aspectRatio,
                        freeformCrop,
                        isResizeDisabled: isTouchPinching,
                        stencilTransition: settleStencilTransition,
                        cropBounds,
                        minCropSize,
                        snapCropRect,
                        keyboardResizeStep
                      }
                    ),
                    (showGrid === true || isInteractiveGrid) && /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
                      GridOverlay,
                      {
                        cropRect: state2.cropRect,
                        containerSize: canvasSize,
                        imageSize: scaledVisualSize
                      }
                    ),
                    activeHandle && outputSize && /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(
                      DimensionsOverlay,
                      {
                        cropRect: state2.cropRect,
                        containerSize: canvasSize,
                        imageSize: scaledVisualSize,
                        activeHandle,
                        outputWidth: outputSize.width,
                        outputHeight: outputSize.height
                      }
                    )
                  ]
                }
              )
            ]
          }
        )
      }
    );
  }
  var CropperInnerWithRef = (0, import_element155.forwardRef)(
    CropperInner
  );
  var Cropper = (0, import_element155.forwardRef)(
    (props, ref) => /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(ViewportProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime278.jsx)(CropperInnerWithRef, { ...props, ref }) })
  );

  // packages/media-editor/build-module/state/use-media-editor-state.mjs
  var import_element156 = __toESM(require_element(), 1);

  // packages/media-editor/build-module/state/types.mjs
  var DEFAULT_CROP_OPTIONS = {
    aspectRatioValue: "0"
  };

  // packages/media-editor/build-module/state/composite-reducer.mjs
  function mediaEditorReducer(state2, action) {
    switch (action.type) {
      case "CROPPER": {
        const nextCropper = cropperReducer(state2.cropper, action.action);
        if (nextCropper === state2.cropper) {
          return state2;
        }
        return { ...state2, cropper: nextCropper };
      }
      case "SET_ASPECT_RATIO_VALUE": {
        const { presetKey, resolved, visualSize } = action.payload;
        const shouldReshape = resolved !== void 0 && resolved > 0 && visualSize.width > 0 && visualSize.height > 0;
        const nextCropOptions = {
          ...state2.cropOptions,
          aspectRatioValue: presetKey
        };
        if (!shouldReshape) {
          if (state2.cropOptions.aspectRatioValue === presetKey) {
            return state2;
          }
          return { ...state2, cropOptions: nextCropOptions };
        }
        const newCropRect = computeInscribedRect(resolved, visualSize);
        const nextCropper = cropperReducer(state2.cropper, {
          type: "SET_CROP_RECT",
          payload: newCropRect
        });
        return {
          cropper: nextCropper,
          cropOptions: nextCropOptions
        };
      }
      case "RESET_CROP_OPTIONS": {
        if (state2.cropOptions.aspectRatioValue === DEFAULT_CROP_OPTIONS.aspectRatioValue) {
          return state2;
        }
        return {
          ...state2,
          cropOptions: { ...DEFAULT_CROP_OPTIONS }
        };
      }
      case "RESTORE_SNAPSHOT":
        return action.payload;
      case "VIEWPORT_ADJUST_CROP_RECT": {
        const nextCropper = cropperReducer(state2.cropper, {
          type: "SET_CROP_RECT",
          payload: action.payload
        });
        if (nextCropper === state2.cropper) {
          return state2;
        }
        return { ...state2, cropper: nextCropper };
      }
    }
  }
  function areMediaEditorStatesEqual(a3, b3) {
    if (a3 === b3) {
      return true;
    }
    return areCropperStatesEqual(a3.cropper, b3.cropper) && a3.cropOptions.aspectRatioValue === b3.cropOptions.aspectRatioValue;
  }
  function buildInitialMediaEditorState(initialCropper, initialOptions) {
    return {
      cropper: initialCropper,
      cropOptions: { ...DEFAULT_CROP_OPTIONS, ...initialOptions }
    };
  }

  // packages/media-editor/build-module/state/use-media-editor-state.mjs
  function resolveAspectRatio(presetKey, cropperImage) {
    const num = parseFloat(presetKey);
    if (num === 0 || Number.isNaN(num)) {
      return void 0;
    }
    if (num === ORIGINAL_ASPECT_RATIO) {
      if (cropperImage && cropperImage.naturalWidth > 0 && cropperImage.naturalHeight > 0) {
        return cropperImage.naturalWidth / cropperImage.naturalHeight;
      }
      return void 0;
    }
    if (num > 0) {
      return num;
    }
    return void 0;
  }
  function areCropperImagesEqual(a3, b3) {
    return a3?.src === b3?.src && a3?.naturalWidth === b3?.naturalWidth && a3?.naturalHeight === b3?.naturalHeight;
  }
  function useMediaEditorState(initialState) {
    const [state2, dispatch8] = (0, import_element156.useReducer)(
      mediaEditorReducer,
      null,
      () => buildInitialMediaEditorState(
        enforceContainment({
          ...DEFAULT_STATE2,
          ...initialState?.cropper
        }),
        initialState?.cropOptions
      )
    );
    const [initialBaseline, setInitialBaseline] = (0, import_element156.useState)(() => state2);
    const stateRef = (0, import_element156.useRef)(state2);
    const visualSizeRef = (0, import_element156.useRef)({ width: 0, height: 0 });
    const historyRef = (0, import_element156.useRef)([]);
    const redoStackRef = (0, import_element156.useRef)([]);
    const [hasUndo, setHasUndo] = (0, import_element156.useState)(false);
    const [hasRedo, setHasRedo] = (0, import_element156.useState)(false);
    const isGestureOpenRef = (0, import_element156.useRef)(false);
    const gestureSnapshotRef = (0, import_element156.useRef)(null);
    const pushSnapshot = (0, import_element156.useCallback)((snapshot) => {
      const last = historyRef.current[historyRef.current.length - 1];
      if (last && areMediaEditorStatesEqual(last, snapshot)) {
        return;
      }
      historyRef.current = [...historyRef.current, snapshot];
      redoStackRef.current = [];
      setHasUndo(true);
      setHasRedo(false);
    }, []);
    const dispatchWithHistory = (0, import_element156.useCallback)(
      (action, recordHistory = true) => {
        const preState = stateRef.current;
        const postState = mediaEditorReducer(preState, action);
        if (recordHistory) {
          if (!areMediaEditorStatesEqual(preState, postState)) {
            if (isGestureOpenRef.current) {
              if (gestureSnapshotRef.current === null) {
                gestureSnapshotRef.current = preState;
              }
            } else {
              pushSnapshot(preState);
            }
          }
        }
        stateRef.current = postState;
        dispatch8(action);
      },
      [pushSnapshot]
    );
    const beginGesture = (0, import_element156.useCallback)(() => {
      if (isGestureOpenRef.current) {
        return;
      }
      isGestureOpenRef.current = true;
      gestureSnapshotRef.current = null;
    }, []);
    const endGesture = (0, import_element156.useCallback)(() => {
      const snapshot = gestureSnapshotRef.current;
      if (snapshot && !areMediaEditorStatesEqual(snapshot, stateRef.current)) {
        pushSnapshot(snapshot);
      }
      gestureSnapshotRef.current = null;
      isGestureOpenRef.current = false;
    }, [pushSnapshot]);
    const dispatchCropperAction = (0, import_element156.useCallback)(
      (action) => {
        dispatchWithHistory({ type: "CROPPER", action });
      },
      [dispatchWithHistory]
    );
    const cropperSetters = (0, import_element156.useMemo)(
      () => buildCropperSetters(
        dispatchCropperAction,
        () => stateRef.current.cropper
      ),
      [dispatchCropperAction]
    );
    const setImage = (0, import_element156.useCallback)((image) => {
      if (areCropperImagesEqual(stateRef.current.cropper.image, image)) {
        return;
      }
      const action = {
        type: "CROPPER",
        action: { type: "SET_IMAGE", payload: image }
      };
      const next = mediaEditorReducer(stateRef.current, action);
      stateRef.current = next;
      dispatch8(action);
      setInitialBaseline(next);
      isGestureOpenRef.current = false;
      gestureSnapshotRef.current = null;
      historyRef.current = [];
      redoStackRef.current = [];
      setHasUndo(false);
      setHasRedo(false);
    }, []);
    const reset = (0, import_element156.useCallback)(
      (resetState) => {
        dispatchWithHistory({
          type: "CROPPER",
          action: { type: "RESET", payload: resetState }
        });
      },
      [dispatchWithHistory]
    );
    const setAspectRatioValue = (0, import_element156.useCallback)(
      (presetKey) => {
        const resolved = resolveAspectRatio(
          presetKey,
          stateRef.current.cropper.image
        );
        dispatchWithHistory({
          type: "SET_ASPECT_RATIO_VALUE",
          payload: {
            presetKey,
            resolved,
            visualSize: visualSizeRef.current
          }
        });
      },
      [dispatchWithHistory]
    );
    const resetCropOptions = (0, import_element156.useCallback)(() => {
      dispatchWithHistory({ type: "RESET_CROP_OPTIONS" });
    }, [dispatchWithHistory]);
    const undo2 = (0, import_element156.useCallback)(() => {
      endGesture();
      const prev = historyRef.current[historyRef.current.length - 1];
      if (!prev) {
        return;
      }
      redoStackRef.current = [stateRef.current, ...redoStackRef.current];
      historyRef.current = historyRef.current.slice(0, -1);
      setHasUndo(historyRef.current.length > 0);
      setHasRedo(true);
      stateRef.current = prev;
      dispatch8({ type: "RESTORE_SNAPSHOT", payload: prev });
    }, [endGesture]);
    const redo2 = (0, import_element156.useCallback)(() => {
      endGesture();
      const next = redoStackRef.current[0];
      if (!next) {
        return;
      }
      historyRef.current = [...historyRef.current, stateRef.current];
      redoStackRef.current = redoStackRef.current.slice(1);
      setHasUndo(true);
      setHasRedo(redoStackRef.current.length > 0);
      stateRef.current = next;
      dispatch8({ type: "RESTORE_SNAPSHOT", payload: next });
    }, [endGesture]);
    const setVisualSize = (0, import_element156.useCallback)((size4) => {
      visualSizeRef.current = size4;
    }, []);
    const adjustCropRectForViewport = (0, import_element156.useCallback)(
      (rect) => {
        dispatchWithHistory(
          { type: "VIEWPORT_ADJUST_CROP_RECT", payload: rect },
          false
        );
      },
      [dispatchWithHistory]
    );
    const isDirty = !areMediaEditorStatesEqual(state2, initialBaseline);
    const isCropperDirty = !areCropperStatesEqual(
      state2.cropper,
      initialBaseline.cropper
    );
    const getCroppedImage = (0, import_element156.useCallback)(
      (mimeType, quality) => {
        if (!state2.cropper.image) {
          return Promise.reject(
            new Error("No image loaded \u2014 call setImage first.")
          );
        }
        return exportCroppedImage(
          state2.cropper.image.src,
          state2.cropper,
          mimeType,
          quality
        );
      },
      [state2.cropper]
    );
    const controller = (0, import_element156.useMemo)(
      () => ({
        // CropperController surface (state is the cropper slice so a
        // <Cropper> takes this controller as-is).
        ...cropperSetters,
        state: state2.cropper,
        setImage,
        reset,
        isDirty,
        getCroppedImage,
        // Composite extensions
        cropOptions: state2.cropOptions,
        setAspectRatioValue,
        resetCropOptions,
        isCropperDirty,
        hasUndo,
        hasRedo,
        undo: undo2,
        redo: redo2,
        beginGesture,
        endGesture,
        setVisualSize,
        adjustCropRectForViewport
      }),
      [
        cropperSetters,
        state2.cropper,
        setImage,
        reset,
        isDirty,
        getCroppedImage,
        state2.cropOptions,
        setAspectRatioValue,
        resetCropOptions,
        isCropperDirty,
        hasUndo,
        hasRedo,
        undo2,
        redo2,
        beginGesture,
        endGesture,
        setVisualSize,
        adjustCropRectForViewport
      ]
    );
    return controller;
  }

  // packages/media-editor/build-module/state/media-editor-state-provider.mjs
  var import_element157 = __toESM(require_element(), 1);
  var import_jsx_runtime279 = __toESM(require_jsx_runtime(), 1);
  var MediaEditorStateContext = (0, import_element157.createContext)(
    null
  );
  function MediaEditorStateProvider({
    initialCropperState,
    initialCropOptions,
    children
  }) {
    const controller = useMediaEditorState({
      cropper: initialCropperState,
      cropOptions: initialCropOptions
    });
    return /* @__PURE__ */ (0, import_jsx_runtime279.jsx)(MediaEditorStateContext.Provider, { value: controller, children });
  }
  function useMediaEditor() {
    const context = (0, import_element157.useContext)(MediaEditorStateContext);
    if (!context) {
      throw new Error(
        "useMediaEditor must be used within a MediaEditorStateProvider."
      );
    }
    return context;
  }

  // packages/media-editor/build-module/components/media-editor-canvas/index.mjs
  var import_jsx_runtime280 = __toESM(require_jsx_runtime(), 1);
  function MediaEditorCanvas({
    isPlacementActive = false,
    onGestureStart,
    onGestureEnd
  }) {
    const { media } = useMediaEditorContext();
    const controller = useMediaEditor();
    const { aspectRatioValue } = controller.cropOptions;
    const cropperImage = controller.state.image;
    const { beginGesture, endGesture, setImage } = controller;
    const [status, setStatus] = (0, import_element158.useState)(
      "loading"
    );
    const aspectRatio = (0, import_element158.useMemo)(
      () => resolveAspectRatio(aspectRatioValue, cropperImage),
      [aspectRatioValue, cropperImage]
    );
    const handleGestureStart = (0, import_element158.useCallback)(() => {
      beginGesture();
      onGestureStart?.();
    }, [beginGesture, onGestureStart]);
    const handleGestureEnd = (0, import_element158.useCallback)(() => {
      endGesture();
      onGestureEnd?.();
    }, [endGesture, onGestureEnd]);
    const mediaUrl = media?.source_url;
    const mediaType = getMediaTypeFromMimeType(media?.mime_type);
    const mediaWidth = Number(media?.media_details?.width);
    const mediaHeight = Number(media?.media_details?.height);
    (0, import_element158.useEffect)(() => {
      if (cropperImage || !mediaUrl || !Number.isFinite(mediaWidth) || !Number.isFinite(mediaHeight) || mediaWidth <= 0 || mediaHeight <= 0) {
        return;
      }
      setImage({
        src: mediaUrl,
        naturalWidth: mediaWidth,
        naturalHeight: mediaHeight
      });
    }, [cropperImage, mediaUrl, mediaWidth, mediaHeight, setImage]);
    const isImage = mediaType.type === "image";
    (0, import_element158.useEffect)(() => {
      if (!mediaUrl || !isImage) {
        return;
      }
      setStatus("loading");
      const probe = new window.Image();
      probe.onload = () => setStatus("loaded");
      probe.onerror = () => setStatus("error");
      probe.src = mediaUrl;
      if (probe.complete) {
        setStatus(probe.naturalWidth > 0 ? "loaded" : "error");
      }
      return () => {
        probe.onload = null;
        probe.onerror = null;
      };
    }, [mediaUrl, isImage]);
    if (!mediaUrl || !isImage) {
      return null;
    }
    if (status === "error") {
      return /* @__PURE__ */ (0, import_jsx_runtime280.jsx)("div", { className: "media-editor-canvas", children: /* @__PURE__ */ (0, import_jsx_runtime280.jsx)("div", { className: "media-editor-canvas__error", role: "alert", children: /* @__PURE__ */ (0, import_jsx_runtime280.jsx)("p", { children: (0, import_i18n135.__)("Failed to load image.") }) }) });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime280.jsxs)("div", { className: "media-editor-canvas", children: [
      status === "loading" && /* @__PURE__ */ (0, import_jsx_runtime280.jsx)("div", { className: "media-editor-canvas__spinner", children: /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(import_components87.Spinner, {}) }),
      /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(
        "div",
        {
          className: clsx_default("media-editor-canvas__cropper", {
            "is-loaded": status === "loaded"
          }),
          children: /* @__PURE__ */ (0, import_jsx_runtime280.jsx)(
            Cropper,
            {
              src: mediaUrl,
              controller,
              aspectRatio,
              freeformCrop: true,
              showGrid: "interactive",
              isPlacementActive,
              onGestureStart: handleGestureStart,
              onGestureEnd: handleGestureEnd
            }
          )
        }
      )
    ] });
  }

  // packages/media-editor/build-module/components/media-editor-fine-rotation/index.mjs
  var import_i18n136 = __toESM(require_i18n(), 1);

  // packages/media-editor/build-module/hooks/use-crop-gesture-handlers.mjs
  var import_element159 = __toESM(require_element(), 1);
  var CROP_CONTROL_ATTR = "data-crop-control";
  var KEYBOARD_GESTURE_IDLE_MS = 300;
  function useCropGestureHandlers(options = {}) {
    const { commitOnKeyUp = true } = options;
    const { beginGesture, endGesture } = useMediaEditor();
    const keyboardTimerRef = (0, import_element159.useRef)();
    const clearKeyboardTimer = (0, import_element159.useCallback)(() => {
      clearTimeout(keyboardTimerRef.current);
    }, []);
    const scheduleKeyboardEnd = (0, import_element159.useCallback)(() => {
      clearKeyboardTimer();
      keyboardTimerRef.current = setTimeout(() => {
        endGesture();
      }, KEYBOARD_GESTURE_IDLE_MS);
    }, [clearKeyboardTimer, endGesture]);
    (0, import_element159.useEffect)(() => clearKeyboardTimer, [clearKeyboardTimer]);
    const handlePointerDownCapture = (0, import_element159.useCallback)(() => {
      clearKeyboardTimer();
      beginGesture();
    }, [beginGesture, clearKeyboardTimer]);
    const handlePointerEnd = (0, import_element159.useCallback)(() => {
      clearKeyboardTimer();
      endGesture();
    }, [clearKeyboardTimer, endGesture]);
    const handleKeyDownCapture = (0, import_element159.useCallback)(() => {
      beginGesture();
      if (!commitOnKeyUp) {
        scheduleKeyboardEnd();
      }
    }, [beginGesture, commitOnKeyUp, scheduleKeyboardEnd]);
    const handleKeyUp = (0, import_element159.useCallback)(() => {
      if (commitOnKeyUp) {
        endGesture();
        return;
      }
      scheduleKeyboardEnd();
    }, [commitOnKeyUp, endGesture, scheduleKeyboardEnd]);
    return {
      [CROP_CONTROL_ATTR]: true,
      onPointerDownCapture: handlePointerDownCapture,
      onPointerUp: handlePointerEnd,
      onPointerCancel: handlePointerEnd,
      onKeyDownCapture: handleKeyDownCapture,
      onKeyUp: handleKeyUp
    };
  }

  // packages/media-editor/build-module/components/rotation-ruler/index.mjs
  var import_element161 = __toESM(require_element(), 1);

  // packages/media-editor/build-module/components/rotation-ruler/use-ruler-drag.mjs
  var import_element160 = __toESM(require_element(), 1);
  function pxToValueDelta(deltaPx, pixelsPerStep, step) {
    return -deltaPx / pixelsPerStep * step;
  }
  function clampValue(value, min3, max3) {
    if (value < min3) {
      return min3;
    }
    if (value > max3) {
      return max3;
    }
    return value;
  }
  function quantize(value, step) {
    return Math.round(value / step) * step;
  }
  function useRulerDrag(options) {
    const {
      value,
      onChange,
      min: min3,
      max: max3,
      step,
      pixelsPerStep,
      disabled: disabled2,
      onPointerDownStart
    } = options;
    const latestRef = (0, import_element160.useRef)({
      value,
      startX: 0,
      startValue: 0,
      activeStep: step,
      dragging: false,
      captureElement: null,
      capturePointerId: 0,
      windowPointerUp: null
    });
    (0, import_element160.useEffect)(() => {
      latestRef.current.value = value;
    }, [value]);
    const endDrag = (0, import_element160.useCallback)(() => {
      const state2 = latestRef.current;
      if (!state2.dragging) {
        return;
      }
      state2.dragging = false;
      if (state2.captureElement && state2.captureElement.hasPointerCapture(state2.capturePointerId)) {
        state2.captureElement.releasePointerCapture(
          state2.capturePointerId
        );
      }
      state2.captureElement = null;
      if (state2.windowPointerUp) {
        window.removeEventListener("pointerup", state2.windowPointerUp);
        window.removeEventListener(
          "pointercancel",
          state2.windowPointerUp
        );
        state2.windowPointerUp = null;
      }
    }, []);
    (0, import_element160.useEffect)(() => endDrag, [endDrag]);
    const onPointerDown = (0, import_element160.useCallback)(
      (event) => {
        if (disabled2 || event.button !== 0) {
          return;
        }
        const state2 = latestRef.current;
        event.currentTarget.setPointerCapture(event.pointerId);
        state2.captureElement = event.currentTarget;
        state2.capturePointerId = event.pointerId;
        state2.startX = event.clientX;
        state2.startValue = state2.value;
        state2.activeStep = event.shiftKey ? step / 2 : step;
        state2.dragging = true;
        onPointerDownStart?.();
        const onWindowUp = () => endDrag();
        state2.windowPointerUp = onWindowUp;
        window.addEventListener("pointerup", onWindowUp);
        window.addEventListener("pointercancel", onWindowUp);
      },
      [disabled2, onPointerDownStart, endDrag, step]
    );
    const onPointerMove = (0, import_element160.useCallback)(
      (event) => {
        const state2 = latestRef.current;
        if (!state2.dragging) {
          return;
        }
        const requestedStep = event.shiftKey ? step / 2 : step;
        if (requestedStep !== state2.activeStep) {
          state2.startX = event.clientX;
          state2.startValue = state2.value;
          state2.activeStep = requestedStep;
        }
        const deltaPx = event.clientX - state2.startX;
        const deltaValue = pxToValueDelta(
          deltaPx,
          pixelsPerStep,
          state2.activeStep
        );
        const raw = state2.startValue + deltaValue;
        const stepped = quantize(raw, state2.activeStep);
        const next = clampValue(stepped, min3, max3);
        if (next !== state2.value) {
          state2.value = next;
          onChange(next);
        }
      },
      [onChange, min3, max3, step, pixelsPerStep]
    );
    return {
      onPointerDown,
      onPointerMove,
      onPointerUp: endDrag,
      onPointerCancel: endDrag
    };
  }

  // packages/media-editor/build-module/components/rotation-ruler/index.mjs
  var import_jsx_runtime281 = __toESM(require_jsx_runtime(), 1);
  var STRIP_HEIGHT = 32;
  var LABEL_BASELINE_Y = 11;
  var MAJOR_INTERVAL = 15;
  var TICK_HEIGHT_MINOR = 4;
  var TICK_HEIGHT_MID = 8;
  var TICK_HEIGHT_MAJOR = 14;
  function useTicks(min3, max3) {
    return (0, import_element161.useMemo)(() => {
      const out = [];
      for (let v3 = Math.ceil(min3); v3 <= Math.floor(max3); v3 += 1) {
        let kind = "minor";
        let height = TICK_HEIGHT_MINOR;
        if (v3 % 15 === 0) {
          kind = "major";
          height = TICK_HEIGHT_MAJOR;
        } else if (v3 % 5 === 0) {
          kind = "mid";
          height = TICK_HEIGHT_MID;
        }
        out.push({ value: v3, kind, height });
      }
      return out;
    }, [min3, max3]);
  }
  function formatValue(value) {
    const rounded = Math.round(value * 10) / 10;
    return Number.isInteger(rounded) ? rounded.toFixed(0) : rounded.toFixed(1);
  }
  function RotationRuler(props) {
    const {
      value,
      onChange,
      min: min3 = -45,
      max: max3 = 45,
      step = 1,
      label,
      unit = "\xB0",
      pixelsPerStep = 6,
      className,
      id,
      disabled: disabled2 = false
    } = props;
    const inputRef = (0, import_element161.useRef)(null);
    const generatedId = (0, import_element161.useId)();
    const inputId = id ?? generatedId;
    const dragHandlers = useRulerDrag({
      value,
      onChange,
      min: min3,
      max: max3,
      step,
      pixelsPerStep,
      disabled: disabled2,
      onPointerDownStart: () => inputRef.current?.focus()
    });
    const handleKeyDown = (event) => {
      const isIncrement = event.key === "ArrowRight" || event.key === "ArrowUp";
      const isDecrement = event.key === "ArrowLeft" || event.key === "ArrowDown";
      if (!isIncrement && !isDecrement) {
        return;
      }
      event.preventDefault();
      if (disabled2) {
        return;
      }
      const direction = isIncrement ? 1 : -1;
      const magnitude = event.shiftKey ? step / 2 : step;
      const next = clampValue(value + direction * magnitude, min3, max3);
      if (next !== value) {
        onChange(next);
      }
    };
    const display = `${formatValue(value)}${unit}`;
    const ticks = useTicks(min3, max3);
    const pxPerUnit = pixelsPerStep / step;
    const stripStyle = (0, import_element161.useMemo)(() => {
      const offset4 = -value * pxPerUnit;
      return {
        transform: `translateX(calc(-50% + ${offset4}px))`
      };
    }, [value, pxPerUnit]);
    const closestMajor = Math.round(value / MAJOR_INTERVAL) * MAJOR_INTERVAL;
    const onMajor = Math.abs(value - closestMajor) < 0.01;
    const numberText = onMajor ? `${closestMajor}` : formatValue(value);
    const isNegative = numberText.startsWith("-");
    const digits = isNegative ? numberText.slice(1) : numberText;
    const majorTicks = ticks.filter((tick) => tick.kind === "major");
    return /* @__PURE__ */ (0, import_jsx_runtime281.jsxs)(
      "div",
      {
        className: clsx_default("rotation-ruler", className),
        role: "presentation",
        "data-disabled": disabled2 || void 0,
        ...dragHandlers,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(
            "input",
            {
              ref: inputRef,
              id: inputId,
              type: "range",
              className: "rotation-ruler__input",
              min: min3,
              max: max3,
              step: "any",
              value,
              disabled: disabled2,
              "aria-label": label,
              "aria-valuetext": display,
              onChange: (event) => onChange(
                clampValue(event.target.valueAsNumber, min3, max3)
              ),
              onKeyDown: handleKeyDown
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime281.jsx)("div", { className: "rotation-ruler__strip", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime281.jsxs)(
            "svg",
            {
              className: "rotation-ruler__ticks",
              style: stripStyle,
              width: (max3 - min3) * pxPerUnit,
              height: STRIP_HEIGHT,
              viewBox: `${min3 * pxPerUnit} 0 ${(max3 - min3) * pxPerUnit} ${STRIP_HEIGHT}`,
              preserveAspectRatio: "xMidYMid meet",
              children: [
                ticks.map((tick) => /* @__PURE__ */ (0, import_jsx_runtime281.jsx)(
                  "line",
                  {
                    x1: tick.value * pxPerUnit,
                    x2: tick.value * pxPerUnit,
                    y1: STRIP_HEIGHT - tick.height,
                    y2: STRIP_HEIGHT,
                    className: `rotation-ruler__tick rotation-ruler__tick--${tick.kind}`
                  },
                  tick.value
                )),
                majorTicks.map((tick) => /* @__PURE__ */ (0, import_jsx_runtime281.jsxs)(
                  "text",
                  {
                    x: tick.value * pxPerUnit,
                    y: LABEL_BASELINE_Y,
                    textAnchor: "middle",
                    className: "rotation-ruler__label",
                    children: [
                      tick.value,
                      unit
                    ]
                  },
                  tick.value
                ))
              ]
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime281.jsx)("div", { className: "rotation-ruler__active-label", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime281.jsxs)("span", { className: "rotation-ruler__active-label-number", children: [
            isNegative && /* @__PURE__ */ (0, import_jsx_runtime281.jsx)("span", { className: "rotation-ruler__active-label-sign", children: "-" }),
            digits,
            /* @__PURE__ */ (0, import_jsx_runtime281.jsx)("span", { className: "rotation-ruler__active-label-unit", children: unit })
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime281.jsx)("div", { className: "rotation-ruler__pointer", "aria-hidden": "true" })
        ]
      }
    );
  }

  // packages/media-editor/build-module/components/media-editor-fine-rotation/index.mjs
  var import_jsx_runtime282 = __toESM(require_jsx_runtime(), 1);
  function MediaEditorFineRotation({
    onPlacementControlInteraction
  }) {
    const { state: state2, setRotation } = useMediaEditor();
    const rotationGestureHandlers = useCropGestureHandlers({
      commitOnKeyUp: false
    });
    const baseAngle = Math.round(state2.rotation / 90) * 90;
    const singleFlip = state2.flip.horizontal !== state2.flip.vertical;
    const visualDir = singleFlip ? -1 : 1;
    const fineOffset = (state2.rotation - baseAngle) * visualDir;
    const handleRotationSlider = (value) => {
      const EPS = 0.01;
      const clamped = Math.max(
        -MAX_ROTATION_OFFSET + EPS,
        Math.min(MAX_ROTATION_OFFSET - EPS, value)
      );
      onPlacementControlInteraction?.();
      setRotation(baseAngle + clamped * visualDir);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime282.jsx)(
      "div",
      {
        role: "presentation",
        className: "media-editor-fine-rotation",
        ...rotationGestureHandlers,
        children: /* @__PURE__ */ (0, import_jsx_runtime282.jsx)(
          RotationRuler,
          {
            label: (0, import_i18n136.__)("Fine rotation"),
            min: -MAX_ROTATION_OFFSET,
            max: MAX_ROTATION_OFFSET,
            value: fineOffset,
            onChange: handleRotationSlider
          }
        )
      }
    );
  }

  // packages/media-editor/build-module/components/media-editor-image-controls/index.mjs
  var import_components88 = __toESM(require_components(), 1);
  var import_i18n137 = __toESM(require_i18n(), 1);

  // packages/media-editor/build-module/components/media-editor/use-crop-options.mjs
  var import_element162 = __toESM(require_element(), 1);
  function getAspectRatioOptions(aspectRatioPresets) {
    return [
      ...DEFAULT_ASPECT_RATIOS.filter((preset) => preset.value <= 0),
      ...aspectRatioPresets ?? DEFAULT_ASPECT_RATIOS.filter((preset) => preset.value > 0)
    ];
  }
  function useCropOptions({
    aspectRatioPresets
  } = {}) {
    const controller = useMediaEditor();
    const { aspectRatioValue } = controller.cropOptions;
    const cropperImage = controller.state.image;
    const aspectRatioOptions = (0, import_element162.useMemo)(
      () => getAspectRatioOptions(aspectRatioPresets),
      [aspectRatioPresets]
    );
    const resolvedAspectRatio = (0, import_element162.useMemo)(
      () => resolveAspectRatio(aspectRatioValue, cropperImage),
      [aspectRatioValue, cropperImage]
    );
    return {
      aspectRatioValue,
      setAspectRatioValue: controller.setAspectRatioValue,
      aspectRatioOptions,
      resolvedAspectRatio,
      resetCropOptions: controller.resetCropOptions
    };
  }

  // packages/media-editor/build-module/components/media-editor-image-controls/index.mjs
  var import_jsx_runtime283 = __toESM(require_jsx_runtime(), 1);
  var DEFAULT_ZOOM_FACTOR = 1.2;
  function MediaEditorImageControls({
    withLabels = false,
    showAspectRatioControl = false,
    aspectRatioPresets,
    zoomFactor = DEFAULT_ZOOM_FACTOR
  }) {
    const { state: state2, setFlip, snapRotate90, setZoom } = useMediaEditor();
    const { aspectRatioValue, setAspectRatioValue, aspectRatioOptions } = useCropOptions({ aspectRatioPresets });
    const hasAspectRatioControl = !withLabels && showAspectRatioControl;
    const minZoom = getMinZoom(state2);
    const zoomByFactor = (factor) => {
      setZoom(
        Math.min(MAX_ZOOM, Math.max(minZoom, state2.zoom * factor))
      );
    };
    const rotateButtons = /* @__PURE__ */ (0, import_jsx_runtime283.jsxs)(import_jsx_runtime283.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
        import_components88.Button,
        {
          size: "compact",
          icon: rotate_left_default,
          label: (0, import_i18n137.__)("Rotate 90\xB0 counter-clockwise"),
          showTooltip: true,
          onClick: () => snapRotate90(-1)
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
        import_components88.Button,
        {
          size: "compact",
          icon: rotate_right_default,
          label: (0, import_i18n137.__)("Rotate 90\xB0 clockwise"),
          showTooltip: true,
          onClick: () => snapRotate90(1)
        }
      )
    ] });
    const flipButtons = /* @__PURE__ */ (0, import_jsx_runtime283.jsxs)(import_jsx_runtime283.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
        import_components88.Button,
        {
          size: "compact",
          icon: flip_horizontal_default,
          label: (0, import_i18n137.__)("Flip horizontal"),
          showTooltip: true,
          isPressed: state2.flip.horizontal,
          onClick: () => setFlip({
            horizontal: !state2.flip.horizontal,
            vertical: state2.flip.vertical
          })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
        import_components88.Button,
        {
          size: "compact",
          icon: flip_vertical_default,
          label: (0, import_i18n137.__)("Flip vertical"),
          showTooltip: true,
          isPressed: state2.flip.vertical,
          onClick: () => setFlip({
            horizontal: state2.flip.horizontal,
            vertical: !state2.flip.vertical
          })
        }
      )
    ] });
    const zoomButtons = /* @__PURE__ */ (0, import_jsx_runtime283.jsxs)(import_jsx_runtime283.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
        import_components88.Button,
        {
          size: "compact",
          icon: plus_default,
          label: (0, import_i18n137.__)("Zoom in"),
          showTooltip: true,
          disabled: state2.zoom >= MAX_ZOOM,
          accessibleWhenDisabled: true,
          onClick: () => zoomByFactor(zoomFactor)
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
        import_components88.Button,
        {
          size: "compact",
          icon: line_solid_default,
          label: (0, import_i18n137.__)("Zoom out"),
          showTooltip: true,
          disabled: state2.zoom <= minZoom,
          accessibleWhenDisabled: true,
          onClick: () => zoomByFactor(1 / zoomFactor)
        }
      )
    ] });
    const aspectRatioDropdown = hasAspectRatioControl ? /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
      import_components88.DropdownMenu,
      {
        icon: aspect_ratio_default,
        label: (0, import_i18n137.__)("Aspect ratio"),
        popoverProps: { placement: "top" },
        toggleProps: { size: "compact" },
        children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(import_components88.MenuGroup, { label: (0, import_i18n137.__)("Aspect ratio"), children: aspectRatioOptions.map((preset) => {
          const value = preset.value.toString();
          const isSelected2 = value === aspectRatioValue;
          return /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
            import_components88.MenuItem,
            {
              role: "menuitemradio",
              isSelected: isSelected2,
              icon: isSelected2 ? check_default : void 0,
              onClick: () => {
                setAspectRatioValue(value);
                onClose();
              },
              children: preset.label
            },
            value
          );
        }) })
      }
    ) : null;
    if (withLabels) {
      return /* @__PURE__ */ (0, import_jsx_runtime283.jsxs)("div", { className: "media-editor-image-controls is-stacked", children: [
        /* @__PURE__ */ (0, import_jsx_runtime283.jsxs)("div", { className: "media-editor-image-controls__transforms", children: [
          /* @__PURE__ */ (0, import_jsx_runtime283.jsxs)(
            "div",
            {
              className: "media-editor-image-controls__group",
              role: "group",
              "aria-label": (0, import_i18n137.__)("Rotate"),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
                  "span",
                  {
                    className: "media-editor-image-controls__label",
                    "aria-hidden": "true",
                    children: (0, import_i18n137.__)("Rotate")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime283.jsx)("div", { className: "media-editor-image-controls__buttons", children: rotateButtons })
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime283.jsxs)(
            "div",
            {
              className: "media-editor-image-controls__group",
              role: "group",
              "aria-label": (0, import_i18n137.__)("Flip"),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
                  "span",
                  {
                    className: "media-editor-image-controls__label",
                    "aria-hidden": "true",
                    children: (0, import_i18n137.__)("Flip")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime283.jsx)("div", { className: "media-editor-image-controls__buttons", children: flipButtons })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime283.jsxs)(
          "div",
          {
            className: "media-editor-image-controls__group",
            role: "group",
            "aria-label": (0, import_i18n137.__)("Zoom"),
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime283.jsx)(
                "span",
                {
                  className: "media-editor-image-controls__label",
                  "aria-hidden": "true",
                  children: (0, import_i18n137.__)("Zoom")
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime283.jsx)("div", { className: "media-editor-image-controls__buttons", children: zoomButtons })
            ]
          }
        )
      ] });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime283.jsxs)("div", { className: "media-editor-image-controls", children: [
      rotateButtons,
      flipButtons,
      zoomButtons,
      aspectRatioDropdown
    ] });
  }

  // packages/media-editor/build-module/components/media-editor-crop-panel/index.mjs
  var import_components89 = __toESM(require_components(), 1);
  var import_i18n138 = __toESM(require_i18n(), 1);
  var import_jsx_runtime284 = __toESM(require_jsx_runtime(), 1);
  function MediaEditorCropPanel({
    aspectRatioValue,
    onAspectRatioChange,
    aspectRatioOptions,
    showTransformControls = false
  }) {
    return (
      // Tag the whole panel as a crop-control region so the modal's
      // Cmd+Z handler doesn't mistake the SelectControl input for a
      // metadata field (which would suppress undo).
      /* @__PURE__ */ (0, import_jsx_runtime284.jsxs)(
        Stack,
        {
          direction: "column",
          gap: "xl",
          ...{ [CROP_CONTROL_ATTR]: true },
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime284.jsx)(VisuallyHidden, { render: /* @__PURE__ */ (0, import_jsx_runtime284.jsx)("h2", {}), children: (0, import_i18n138.__)("Crop options") }),
            showTransformControls && /* @__PURE__ */ (0, import_jsx_runtime284.jsx)(MediaEditorImageControls, { withLabels: true }),
            /* @__PURE__ */ (0, import_jsx_runtime284.jsx)(
              import_components89.SelectControl,
              {
                label: (0, import_i18n138.__)("Aspect ratio"),
                value: aspectRatioValue,
                onChange: onAspectRatioChange,
                options: aspectRatioOptions.map((preset) => ({
                  label: preset.label,
                  value: preset.value.toString()
                }))
              }
            )
          ]
        }
      )
    );
  }

  // packages/media-editor/build-module/components/media-editor-keyboard-shortcuts-modal/index.mjs
  var import_components90 = __toESM(require_components(), 1);
  var import_element163 = __toESM(require_element(), 1);
  var import_i18n139 = __toESM(require_i18n(), 1);
  var import_keycodes3 = __toESM(require_keycodes(), 1);
  var import_jsx_runtime285 = __toESM(require_jsx_runtime(), 1);
  var SHORTCUTS = [
    {
      description: (0, import_i18n139.__)("Undo"),
      keyCombination: { modifier: "primary", character: "z" }
    },
    {
      description: (0, import_i18n139.__)("Redo"),
      keyCombination: { modifier: "primaryShift", character: "z" }
    },
    {
      description: (0, import_i18n139.__)("Pan"),
      keyCombination: {
        character: ["\u2191", "\u2193", "\u2190", "\u2192"],
        ariaLabel: (0, import_i18n139.__)("Arrow keys")
      }
    },
    {
      description: (0, import_i18n139.__)("Zoom in"),
      keyCombination: { character: "+" }
    },
    {
      description: (0, import_i18n139.__)("Zoom out"),
      keyCombination: { character: "-" }
    },
    {
      description: (0, import_i18n139.__)("Rotate 90\xB0 clockwise"),
      keyCombination: { character: "R" }
    },
    {
      description: (0, import_i18n139.__)("Rotate 90\xB0 counter-clockwise"),
      keyCombination: { modifier: "shift", character: "R" }
    },
    {
      description: (0, import_i18n139.__)("Flip horizontal"),
      keyCombination: { character: "H" }
    },
    {
      description: (0, import_i18n139.__)("Flip vertical"),
      keyCombination: { character: "V" }
    },
    {
      description: (0, import_i18n139.__)("Pan or resize crop (large step)"),
      keyCombination: {
        modifier: "shift",
        character: ["\u2191", "\u2193", "\u2190", "\u2192"],
        ariaLabel: (0, import_i18n139.__)("Shift + Arrow keys")
      }
    }
  ];
  function KeyCombinationDisplay({
    keyCombination
  }) {
    const { modifier, character, ariaLabel } = keyCombination;
    let keys;
    if (Array.isArray(character)) {
      if (modifier) {
        const sample = import_keycodes3.displayShortcutList[modifier](character[0]);
        keys = [...sample.slice(0, -1), ...character];
      } else {
        keys = character;
      }
    } else {
      keys = modifier ? import_keycodes3.displayShortcutList[modifier](character) : [character];
    }
    const charString = Array.isArray(character) ? character.join("") : character;
    let label;
    if (ariaLabel) {
      label = ariaLabel;
    } else if (modifier) {
      label = import_keycodes3.shortcutAriaLabel[modifier](charString);
    } else {
      label = charString;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime285.jsx)(
      "kbd",
      {
        className: "media-editor-keyboard-shortcuts-modal__shortcut-term",
        "aria-label": label,
        children: keys.map(
          (key, index2) => key === "+" && modifier ? /* @__PURE__ */ (0, import_jsx_runtime285.jsx)(import_element163.Fragment, { children: key }, index2) : /* @__PURE__ */ (0, import_jsx_runtime285.jsx)(
            "kbd",
            {
              className: "media-editor-keyboard-shortcuts-modal__shortcut-key",
              children: key
            },
            index2
          )
        )
      }
    );
  }
  function MediaEditorKeyboardShortcutsModal({
    onClose
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime285.jsxs)(
      import_components90.Modal,
      {
        className: "media-editor-keyboard-shortcuts-modal",
        title: (0, import_i18n139.__)("Keyboard shortcuts"),
        onRequestClose: onClose,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime285.jsx)("p", { className: "media-editor-keyboard-shortcuts-modal__note", children: (0, import_i18n139.__)(
            "These shortcuts work when the image editor has focus."
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime285.jsx)(
            "ul",
            {
              className: "media-editor-keyboard-shortcuts-modal__shortcut-list",
              role: "list",
              children: SHORTCUTS.map(({ description, keyCombination }, index2) => /* @__PURE__ */ (0, import_jsx_runtime285.jsxs)(
                "li",
                {
                  className: "media-editor-keyboard-shortcuts-modal__shortcut",
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime285.jsx)("span", { className: "media-editor-keyboard-shortcuts-modal__shortcut-description", children: description }),
                    /* @__PURE__ */ (0, import_jsx_runtime285.jsx)(
                      KeyCombinationDisplay,
                      {
                        keyCombination
                      }
                    )
                  ]
                },
                index2
              ))
            }
          )
        ]
      }
    );
  }

  // packages/media-editor/build-module/components/media-editor/use-save-media-editor.mjs
  var import_api_fetch2 = __toESM(require_api_fetch(), 1);
  var import_data44 = __toESM(require_data(), 1);
  var import_core_data28 = __toESM(require_core_data(), 1);
  var import_element164 = __toESM(require_element(), 1);
  var import_i18n140 = __toESM(require_i18n(), 1);
  var import_notices13 = __toESM(require_notices(), 1);

  // packages/media-editor/build-module/components/media-editor-modal/build-modifiers.mjs
  var CROP_TOLERANCE = 0.1;
  function buildModifiers(state2, imageSize) {
    const modifiers = [];
    if (imageSize.width === 0 || imageSize.height === 0) {
      return modifiers;
    }
    const { cropRect, pan, zoom, flip: flip4 } = state2;
    const hasFlipH = flip4.horizontal;
    const hasFlipV = flip4.vertical;
    if (hasFlipH || hasFlipV) {
      modifiers.push({
        type: "flip",
        args: { flip: { horizontal: hasFlipH, vertical: hasFlipV } }
      });
    }
    const rawAngle = (state2.rotation % 360 + 360) % 360;
    const singleAxisFlip = hasFlipH !== hasFlipV;
    const signedAngle2 = singleAxisFlip ? (360 - rawAngle) % 360 : rawAngle;
    if (signedAngle2 !== 0) {
      modifiers.push({ type: "rotate", args: { angle: signedAngle2 } });
    }
    const snapRotation = Math.round(state2.rotation / 90) * 90;
    const { width: snapW, height: snapH } = getRotatedBBox(
      imageSize.width,
      imageSize.height,
      snapRotation
    );
    const { width: fullW, height: fullH } = getRotatedBBox(
      imageSize.width,
      imageSize.height,
      state2.rotation
    );
    const imgLeft = 0.5 + pan.x - zoom / 2;
    const imgTop = 0.5 + pan.y - zoom / 2;
    const snapX = (cropRect.x - imgLeft) / zoom * snapW;
    const snapY = (cropRect.y - imgTop) / zoom * snapH;
    const widthPx = cropRect.width / zoom * snapW;
    const heightPx = cropRect.height / zoom * snapH;
    const offsetX = (fullW - snapW) / 2;
    const offsetY = (fullH - snapH) / 2;
    const fullX = snapX + offsetX;
    const fullY = snapY + offsetY;
    const leftPct = fullX / fullW * 100;
    const topPct = fullY / fullH * 100;
    const widthPct = widthPx / fullW * 100;
    const heightPct = heightPx / fullH * 100;
    const coversFullFrame = leftPct <= CROP_TOLERANCE && topPct <= CROP_TOLERANCE && widthPct >= 100 - CROP_TOLERANCE && heightPct >= 100 - CROP_TOLERANCE;
    if (!coversFullFrame) {
      modifiers.push({
        type: "crop",
        args: {
          left: leftPct,
          top: topPct,
          width: widthPct,
          height: heightPct
        }
      });
    }
    return modifiers;
  }

  // packages/media-editor/build-module/components/media-editor/use-save-media-editor.mjs
  var METADATA_EDIT_KEYS = [
    "title",
    "caption",
    "description",
    "alt_text",
    "post"
  ];
  var MEDIA_EDITOR_NOTICES_CONTEXT = "media-editor";
  function getCropModifiers(cropper) {
    if (!cropper.isCropperDirty || !cropper.state.image) {
      return [];
    }
    return buildModifiers(cropper.state, {
      width: cropper.state.image.naturalWidth,
      height: cropper.state.image.naturalHeight
    });
  }
  function getMetadataEdits(pendingEdits, media) {
    const metadataEdits = {};
    for (const key of METADATA_EDIT_KEYS) {
      if (pendingEdits && key in pendingEdits) {
        metadataEdits[key] = pendingEdits[key];
      }
    }
    if (!("post" in metadataEdits) && media?.post !== void 0) {
      metadataEdits.post = media.post;
    }
    return metadataEdits;
  }
  function useSaveMediaEditor({
    cropper,
    id,
    isImage,
    media,
    onSaved
  }) {
    const registry = (0, import_data44.useRegistry)();
    const {
      clearEntityRecordEdits,
      receiveEntityRecords,
      saveEditedEntityRecord
    } = (0, import_data44.useDispatch)(import_core_data28.store);
    const { createErrorNotice, removeAllNotices } = (0, import_data44.useDispatch)(import_notices13.store);
    const [isSaving, setIsSaving] = (0, import_element164.useState)(false);
    const save = (0, import_element164.useCallback)(async () => {
      removeAllNotices("snackbar", MEDIA_EDITOR_NOTICES_CONTEXT);
      setIsSaving(true);
      try {
        let saved;
        const modifiers = getCropModifiers(cropper);
        const previous = modifiers.length > 0 && media ? {
          id,
          url: media.source_url
        } : void 0;
        if (modifiers.length > 0) {
          const pendingEdits = registry.select(import_core_data28.store).getEntityRecordNonTransientEdits(
            "postType",
            "attachment",
            id
          );
          const metadataEdits = getMetadataEdits(pendingEdits, media);
          saved = await (0, import_api_fetch2.default)({
            path: `/wp/v2/media/${id}/edit`,
            method: "POST",
            data: {
              src: media?.source_url,
              modifiers,
              ...metadataEdits
            }
          });
          if (saved) {
            receiveEntityRecords(
              "postType",
              "attachment",
              saved,
              void 0,
              true
            );
          }
        } else {
          saved = await saveEditedEntityRecord(
            "postType",
            "attachment",
            id
          );
        }
        const next = saved ?? media;
        if (next && next.id !== id) {
          clearEntityRecordEdits("postType", "attachment", id);
        }
        if (next && next.id) {
          if (next.id === id) {
            cropper.reset();
          }
          onSaved?.({
            id: next.id,
            url: next.source_url,
            media: next,
            previous
          });
        }
      } catch (error2) {
        const message2 = error2 instanceof Error ? error2.message : error2?.message ?? (0, import_i18n140.__)("An unknown error occurred.");
        createErrorNotice(
          isImage ? (0, import_i18n140.sprintf)(
            /* translators: %s: Error message. */
            (0, import_i18n140.__)("Could not save image. %s"),
            message2
          ) : (0, import_i18n140.sprintf)(
            /* translators: %s: Error message. */
            (0, import_i18n140.__)("Could not save media. %s"),
            message2
          ),
          {
            type: "snackbar",
            context: MEDIA_EDITOR_NOTICES_CONTEXT
          }
        );
      } finally {
        setIsSaving(false);
      }
    }, [
      clearEntityRecordEdits,
      createErrorNotice,
      cropper,
      id,
      isImage,
      media,
      onSaved,
      receiveEntityRecords,
      registry,
      removeAllNotices,
      saveEditedEntityRecord
    ]);
    return { isSaving, save };
  }

  // packages/media-editor/build-module/components/media-editor/index.mjs
  var import_jsx_runtime286 = __toESM(require_jsx_runtime(), 1);
  var ATTACHMENT_EMBED_QUERY = { _embed: "author,wp:attached-to" };
  var PLACEMENT_CONTROL_IDLE_MS = 300;
  function MediaEditorSidebar({ tabs }) {
    return /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
      complementary_area_default,
      {
        scope: "media-editor",
        identifier: "media-editor/details",
        title: (0, import_i18n141.__)("Details"),
        icon: drawer_right_default,
        isActiveByDefault: true,
        className: "media-editor__sidebar",
        panelClassName: "media-editor__sidebar-panel",
        headerClassName: "media-editor__sidebar-header",
        closeLabel: (0, import_i18n141.__)("Close media panel"),
        header: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(tabs_exports.List, { variant: "minimal", children: tabs.map((tab) => /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(tabs_exports.Tab, { value: tab.id, children: tab.title }, tab.id)) }),
        children: tabs.map((tab) => /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(tabs_exports.Panel, { value: tab.id, tabIndex: -1, children: tab.panel }, tab.id))
      }
    );
  }
  function HeaderActions({
    isSaving,
    isImage,
    showCloseButton = false,
    onCancel
  }) {
    const [isShortcutsModalOpen, setIsShortcutsModalOpen] = (0, import_element165.useState)(false);
    return /* @__PURE__ */ (0, import_jsx_runtime286.jsxs)(
      import_components91.Flex,
      {
        className: "media-editor__header-actions",
        justify: "flex-end",
        expanded: false,
        gap: 2,
        children: [
          isImage && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
            import_components91.Button,
            {
              size: "compact",
              icon: keyboard_default,
              label: (0, import_i18n141.__)("Keyboard shortcuts"),
              onClick: () => setIsShortcutsModalOpen(true)
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(pinned_items_default.Slot, { scope: "media-editor" }),
          showCloseButton && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
            import_components91.Button,
            {
              size: "compact",
              icon: close_default,
              label: (0, import_i18n141.__)("Close"),
              onClick: onCancel,
              disabled: isSaving,
              accessibleWhenDisabled: true
            }
          ),
          isShortcutsModalOpen && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
            MediaEditorKeyboardShortcutsModal,
            {
              onClose: () => setIsShortcutsModalOpen(false)
            }
          )
        ]
      }
    );
  }
  function HistoryActions({
    isUndoRedoDisabled = false,
    onReset
  }) {
    const {
      reset,
      isDirty,
      hasUndo,
      hasRedo,
      undo: undoCrop,
      redo: redoCrop,
      beginGesture,
      endGesture
    } = useMediaEditor();
    const handleUndo = () => {
      if (isUndoRedoDisabled) {
        return;
      }
      undoCrop();
    };
    const handleRedo = () => {
      if (isUndoRedoDisabled) {
        return;
      }
      redoCrop();
    };
    const handleReset = () => {
      beginGesture();
      reset();
      onReset();
      endGesture();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime286.jsxs)(
      import_components91.Flex,
      {
        className: "media-editor__history-actions",
        expanded: false,
        gap: 2,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
            import_components91.Button,
            {
              size: "compact",
              variant: "tertiary",
              disabled: !isDirty,
              accessibleWhenDisabled: true,
              onClick: handleReset,
              children: (0, import_i18n141.__)("Reset")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
            import_components91.Button,
            {
              size: "compact",
              icon: undo_default,
              label: (0, import_i18n141.__)("Undo"),
              showTooltip: true,
              shortcut: import_keycodes4.displayShortcut.primary("z"),
              disabled: isUndoRedoDisabled || !hasUndo,
              accessibleWhenDisabled: true,
              onClick: handleUndo
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
            import_components91.Button,
            {
              size: "compact",
              icon: redo_default,
              label: (0, import_i18n141.__)("Redo"),
              showTooltip: true,
              shortcut: (0, import_keycodes4.isAppleOS)() ? import_keycodes4.displayShortcut.primaryShift("z") : import_keycodes4.displayShortcut.primary("y"),
              disabled: isUndoRedoDisabled || !hasRedo,
              accessibleWhenDisabled: true,
              onClick: handleRedo
            }
          )
        ]
      }
    );
  }
  function FooterActions({
    isSaving,
    hasMedia,
    hasChanges,
    onCancel,
    onSave
  }) {
    const saveDisabled = isSaving || !hasMedia || !hasChanges;
    return /* @__PURE__ */ (0, import_jsx_runtime286.jsxs)(
      import_components91.Flex,
      {
        className: "media-editor__footer-actions",
        justify: "flex-end",
        expanded: false,
        gap: 2,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
            import_components91.Button,
            {
              __next40pxDefaultSize: true,
              variant: "tertiary",
              onClick: onCancel,
              disabled: isSaving,
              accessibleWhenDisabled: true,
              children: (0, import_i18n141.__)("Cancel")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
            import_components91.Button,
            {
              __next40pxDefaultSize: true,
              variant: "primary",
              onClick: onSave,
              isBusy: isSaving,
              disabled: saveDisabled,
              accessibleWhenDisabled: true,
              children: (0, import_i18n141.__)("Save")
            }
          )
        ]
      }
    );
  }
  function MediaEditorContent({
    fields: fields2 = [],
    id,
    aspectRatioPresets,
    onClose,
    onSaved,
    renderFrame,
    noticesClassName = "media-editor__snackbar",
    noticesPortalElement,
    showCloseButton = false,
    shouldCloseOnEsc = false
  }) {
    const cropper = useMediaEditor();
    const isPanelLayout = (0, import_compose26.useViewportMatch)("small");
    const footerLayout = isPanelLayout ? "wide" : "narrow";
    const { media, hasEdits } = (0, import_data45.useSelect)(
      (select9) => {
        const {
          getEditedEntityRecord,
          getEntityRecord,
          hasEditsForEntityRecord
        } = select9(import_core_data29.store);
        getEntityRecord(
          "postType",
          "attachment",
          id,
          ATTACHMENT_EMBED_QUERY
        );
        return {
          media: getEditedEntityRecord(
            "postType",
            "attachment",
            id
          ),
          hasEdits: hasEditsForEntityRecord(
            "postType",
            "attachment",
            id
          )
        };
      },
      [id]
    );
    const hasChanges = cropper.isCropperDirty || hasEdits;
    const { clearEntityRecordEdits, editEntityRecord, invalidateResolution } = (0, import_data45.useDispatch)(import_core_data29.store);
    const { removeAllNotices } = (0, import_data45.useDispatch)(import_notices14.store);
    const [isDiscardDialogOpen, setIsDiscardDialogOpen] = (0, import_element165.useState)(false);
    const [isPlacementActive, setIsPlacementActive] = (0, import_element165.useState)(false);
    const [isCanvasGestureActive, setIsCanvasGestureActive] = (0, import_element165.useState)(false);
    const placementControlTimerRef = (0, import_element165.useRef)();
    const signalPlacementControlInteraction = (0, import_element165.useCallback)(() => {
      setIsPlacementActive(true);
      clearTimeout(placementControlTimerRef.current);
      placementControlTimerRef.current = setTimeout(() => {
        setIsPlacementActive(false);
      }, PLACEMENT_CONTROL_IDLE_MS);
    }, []);
    const handleCanvasGestureStart = (0, import_element165.useCallback)(() => {
      setIsCanvasGestureActive(true);
    }, []);
    const handleCanvasGestureEnd = (0, import_element165.useCallback)(() => {
      setIsCanvasGestureActive(false);
    }, []);
    const isCropInteractionActive = isPlacementActive || isCanvasGestureActive;
    (0, import_element165.useEffect)(() => {
      return () => {
        clearTimeout(placementControlTimerRef.current);
      };
    }, []);
    (0, import_element165.useEffect)(() => {
      setIsPlacementActive(false);
      setIsCanvasGestureActive(false);
    }, [id]);
    (0, import_element165.useEffect)(() => {
      invalidateResolution("getEntityRecord", [
        "postType",
        "attachment",
        id,
        ATTACHMENT_EMBED_QUERY
      ]);
    }, [id, invalidateResolution]);
    const mediaType = getMediaTypeFromMimeType(media?.mime_type).type;
    const isImage = !!media && mediaType === "image";
    const {
      aspectRatioValue,
      setAspectRatioValue,
      aspectRatioOptions,
      resetCropOptions
    } = useCropOptions({
      aspectRatioPresets
    });
    const { isSaving, save: saveMediaEditor } = useSaveMediaEditor({
      cropper,
      id,
      isImage,
      media,
      onSaved
    });
    const tabs = (0, import_element165.useMemo)(() => {
      const detailsTab = {
        id: "details",
        title: (0, import_i18n141.__)("Details"),
        panel: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
          Stack,
          {
            className: "media-editor__panel",
            direction: "column",
            gap: "lg",
            children: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(MediaForm, {})
          }
        )
      };
      if (!isImage) {
        return [detailsTab];
      }
      return [
        {
          id: "crop",
          title: (0, import_i18n141.__)("Crop"),
          panel: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
            Stack,
            {
              className: "media-editor__panel",
              direction: "column",
              gap: "lg",
              children: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
                MediaEditorCropPanel,
                {
                  aspectRatioValue,
                  onAspectRatioChange: setAspectRatioValue,
                  aspectRatioOptions,
                  showTransformControls: isPanelLayout
                }
              )
            }
          )
        },
        detailsTab
      ];
    }, [
      isImage,
      aspectRatioValue,
      setAspectRatioValue,
      aspectRatioOptions,
      isPanelLayout
    ]);
    const [selectedTabId, setSelectedTabId] = (0, import_element165.useState)();
    const activeTabId = selectedTabId ?? tabs[0]?.id;
    const handleChange = (updates) => {
      editEntityRecord("postType", "attachment", id, updates);
    };
    const discardAndClose = () => {
      removeAllNotices("snackbar", MEDIA_EDITOR_NOTICES_CONTEXT);
      clearEntityRecordEdits("postType", "attachment", id);
      onClose?.();
    };
    const handleRequestClose = () => {
      if (isSaving) {
        return;
      }
      if (hasChanges) {
        setIsDiscardDialogOpen(true);
        return;
      }
      discardAndClose();
    };
    const handleKeyDown = (event) => {
      const isUndoShortcut = import_keycodes4.isKeyboardEvent.primary(event, "z");
      const isRedoShortcut = import_keycodes4.isKeyboardEvent.primaryShift(event, "z") || !(0, import_keycodes4.isAppleOS)() && import_keycodes4.isKeyboardEvent.primary(event, "y");
      if ((isUndoShortcut || isRedoShortcut) && isImage) {
        const target = event.target;
        const isMetadataField = (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) && !target.closest(`[${CROP_CONTROL_ATTR}]`);
        if (!isMetadataField) {
          event.preventDefault();
          if (isCropInteractionActive) {
            return;
          }
          if (isRedoShortcut) {
            cropper.redo();
          } else {
            cropper.undo();
          }
        }
      }
      if (shouldCloseOnEsc) {
        if (event.code !== "Escape" && event.key !== "Escape") {
          return;
        }
        if (isSaving) {
          event.preventDefault();
          return;
        }
        if (hasChanges) {
          event.preventDefault();
          setIsDiscardDialogOpen(true);
        }
      }
    };
    const snackbar = /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
      import_notices14.SnackbarNotices,
      {
        className: noticesClassName,
        context: MEDIA_EDITOR_NOTICES_CONTEXT
      }
    );
    const ruler = isImage ? /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
      MediaEditorFineRotation,
      {
        onPlacementControlInteraction: signalPlacementControlInteraction
      }
    ) : null;
    const children = /* @__PURE__ */ (0, import_jsx_runtime286.jsxs)(
      MediaEditorProvider,
      {
        value: media ?? void 0,
        onChange: handleChange,
        settings: { fields: fields2 },
        children: [
          !media ? /* @__PURE__ */ (0, import_jsx_runtime286.jsx)("div", { className: "media-editor", children: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)("div", { className: "media-editor__loading", children: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(import_components91.Spinner, {}) }) }) : /* @__PURE__ */ (0, import_jsx_runtime286.jsxs)(
            tabs_exports.Root,
            {
              className: "media-editor",
              value: activeTabId,
              onValueChange: (value) => setSelectedTabId(value),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(MediaEditorSidebar, { tabs }),
                /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
                  interface_skeleton_default,
                  {
                    className: "media-editor__skeleton",
                    labels: {
                      body: isImage ? (0, import_i18n141.__)("Image editor") : (0, import_i18n141.__)("Media preview"),
                      sidebar: (0, import_i18n141.__)("Media details")
                    },
                    content: /* @__PURE__ */ (0, import_jsx_runtime286.jsxs)("div", { className: "media-editor__content", children: [
                      /* @__PURE__ */ (0, import_jsx_runtime286.jsx)("div", { className: "media-editor__canvas-area", children: isImage ? /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
                        MediaEditorCanvas,
                        {
                          isPlacementActive,
                          onGestureStart: handleCanvasGestureStart,
                          onGestureEnd: handleCanvasGestureEnd
                        }
                      ) : /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(MediaPreview2, {}) }),
                      isImage && /* @__PURE__ */ (0, import_jsx_runtime286.jsx)("div", { className: "media-editor__canvas-toolbar", children: ruler })
                    ] }),
                    sidebar: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(complementary_area_default.Slot, { scope: "media-editor" })
                  }
                )
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
            import_components91.__experimentalConfirmDialog,
            {
              isOpen: isDiscardDialogOpen,
              confirmButtonText: (0, import_i18n141.__)("Discard"),
              cancelButtonText: (0, import_i18n141.__)("Keep editing"),
              onCancel: () => setIsDiscardDialogOpen(false),
              onConfirm: () => {
                setIsDiscardDialogOpen(false);
                discardAndClose();
              },
              children: (0, import_i18n141.__)(
                "Are you sure you want to discard your unsaved changes?"
              )
            }
          ),
          noticesPortalElement ? (0, import_element165.createPortal)(snackbar, noticesPortalElement) : snackbar
        ]
      }
    );
    const history = isImage ? /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
      HistoryActions,
      {
        isUndoRedoDisabled: isCropInteractionActive,
        onReset: resetCropOptions
      }
    ) : null;
    const imageControls = isImage ? /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
      MediaEditorImageControls,
      {
        showAspectRatioControl: true,
        aspectRatioPresets
      }
    ) : null;
    const actions2 = /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
      FooterActions,
      {
        isSaving,
        hasMedia: !!media,
        hasChanges,
        onCancel: handleRequestClose,
        onSave: saveMediaEditor
      }
    );
    let footerActions;
    if (footerLayout === "wide") {
      footerActions = /* @__PURE__ */ (0, import_jsx_runtime286.jsxs)(import_jsx_runtime286.Fragment, { children: [
        history,
        actions2
      ] });
    } else {
      footerActions = /* @__PURE__ */ (0, import_jsx_runtime286.jsxs)(import_jsx_runtime286.Fragment, { children: [
        imageControls,
        /* @__PURE__ */ (0, import_jsx_runtime286.jsxs)("div", { className: "media-editor-modal__footer-row", children: [
          history,
          actions2
        ] })
      ] });
    }
    return renderFrame({
      children,
      headerActions: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(
        HeaderActions,
        {
          isSaving,
          isImage,
          showCloseButton,
          onCancel: handleRequestClose
        }
      ),
      footerActions,
      footerLayout,
      onRequestClose: handleRequestClose,
      onKeyDown: handleKeyDown,
      shouldCloseOnClickOutside: !hasChanges && !isSaving,
      isSaving,
      hasChanges,
      hasMedia: !!media
    });
  }
  function MediaEditor(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(MediaEditorStateProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime286.jsx)(MediaEditorContent, { ...props }) }, props.id);
  }
  var media_editor_default = MediaEditor;

  // packages/media-editor/build-module/components/media-editor-modal/index.mjs
  var import_jsx_runtime287 = __toESM(require_jsx_runtime(), 1);
  function MediaEditorModal({
    fields: fields2 = [],
    aspectRatioPresets
  }) {
    const { isModalOpen, id, onUpdate, onClose } = (0, import_data46.useSelect)((select9) => {
      const { isOpen: isOpen2, getId: getId2, getOnUpdate: getOnUpdate2, getOnClose: getOnClose2 } = select9(store2);
      return {
        isModalOpen: isOpen2(),
        id: getId2(),
        onUpdate: getOnUpdate2(),
        onClose: getOnClose2()
      };
    }, []);
    const { closeMediaEditorModal: closeMediaEditorModal2 } = (0, import_data46.useDispatch)(store2);
    const { createSuccessNotice } = (0, import_data46.useDispatch)(import_notices15.store);
    if (!isModalOpen || !id) {
      return null;
    }
    const portalElement = typeof document === "undefined" ? null : document.body;
    const stopKeyDownPropagation = (event) => {
      event.stopPropagation();
    };
    const handleClose = () => {
      closeMediaEditorModal2();
      onClose?.();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime287.jsx)(
      media_editor_default,
      {
        id,
        fields: fields2,
        aspectRatioPresets,
        showCloseButton: true,
        shouldCloseOnEsc: true,
        noticesClassName: "media-editor-modal__snackbar",
        noticesPortalElement: portalElement,
        onClose: handleClose,
        onSaved: ({ id: savedId, url, previous }) => {
          if (savedId && onUpdate) {
            const update4 = {
              id: savedId,
              url
            };
            onUpdate(update4);
          }
          handleClose();
          if (previous && savedId !== previous.id && onUpdate) {
            createSuccessNotice((0, import_i18n142.__)("Image edited."), {
              type: "snackbar",
              actions: [
                {
                  label: (0, import_i18n142.__)("Undo"),
                  onClick: () => {
                    onUpdate({
                      id: previous.id,
                      url: previous.url
                    });
                  }
                }
              ]
            });
          }
        },
        renderFrame: ({
          children,
          headerActions,
          footerActions,
          footerLayout,
          onRequestClose,
          onKeyDown,
          shouldCloseOnClickOutside
        }) => /* @__PURE__ */ (0, import_jsx_runtime287.jsx)(
          import_keyboard_shortcuts.ShortcutProvider,
          {
            className: "media-editor-modal__shortcut-scope",
            onKeyDown: stopKeyDownPropagation,
            children: /* @__PURE__ */ (0, import_jsx_runtime287.jsxs)(
              import_components92.Modal,
              {
                className: "media-editor-modal",
                title: (0, import_i18n142.__)("Edit media"),
                size: "fill",
                isDismissible: false,
                shouldCloseOnClickOutside,
                onKeyDown,
                onRequestClose,
                headerActions,
                children: [
                  children,
                  /* @__PURE__ */ (0, import_jsx_runtime287.jsx)(
                    "div",
                    {
                      className: `media-editor-modal__footer is-${footerLayout}`,
                      role: "region",
                      "aria-label": (0, import_i18n142.__)("Editor actions"),
                      children: footerActions
                    }
                  )
                ]
              }
            )
          }
        )
      }
    );
  }

  // packages/media-editor/build-module/private-apis.mjs
  var privateApis14 = {};
  lock6(privateApis14, {
    store: store2,
    MediaEditor,
    MediaEditorModal
  });

  // packages/editor/build-module/components/media-categories/index.mjs
  var import_i18n143 = __toESM(require_i18n(), 1);
  var import_data47 = __toESM(require_data(), 1);
  var import_html_entities10 = __toESM(require_html_entities(), 1);
  var import_core_data30 = __toESM(require_core_data(), 1);
  var getExternalLink = (url, text) => `<a ${getExternalLinkAttributes(url)}>${text}</a>`;
  var getExternalLinkAttributes = (url) => `href="${url}" target="_blank" rel="noopener"`;
  var getOpenverseLicense = (license, licenseVersion) => {
    let licenseName = license.trim();
    if (license !== "pdm") {
      licenseName = license.toUpperCase().replace("SAMPLING", "Sampling");
    }
    if (licenseVersion) {
      licenseName += ` ${licenseVersion}`;
    }
    if (!["pdm", "cc0"].includes(license)) {
      licenseName = `CC ${licenseName}`;
    }
    return licenseName;
  };
  var getOpenverseCaption = (item) => {
    const {
      title,
      foreign_landing_url: foreignLandingUrl,
      creator,
      creator_url: creatorUrl,
      license,
      license_version: licenseVersion,
      license_url: licenseUrl
    } = item;
    const fullLicense = getOpenverseLicense(license, licenseVersion);
    const _creator = (0, import_html_entities10.decodeEntities)(creator);
    let _caption;
    if (_creator) {
      _caption = title ? (0, import_i18n143.sprintf)(
        // translators: %1s: Title of a media work from Openverse; %2$s: Name of the work's creator; %3s: Work's licence e.g: "CC0 1.0".
        (0, import_i18n143._x)('"%1$s" by %2$s/ %3$s', "caption"),
        getExternalLink(
          foreignLandingUrl,
          (0, import_html_entities10.decodeEntities)(title)
        ),
        creatorUrl ? getExternalLink(creatorUrl, _creator) : _creator,
        licenseUrl ? getExternalLink(
          `${licenseUrl}?ref=openverse`,
          fullLicense
        ) : fullLicense
      ) : (0, import_i18n143.sprintf)(
        // translators: %1s: Link attributes for a given Openverse media work; %2s: Name of the work's creator; %3s: Works's licence e.g: "CC0 1.0".
        (0, import_i18n143._x)("<a %1$s>Work</a> by %2$s/ %3$s", "caption"),
        getExternalLinkAttributes(foreignLandingUrl),
        creatorUrl ? getExternalLink(creatorUrl, _creator) : _creator,
        licenseUrl ? getExternalLink(
          `${licenseUrl}?ref=openverse`,
          fullLicense
        ) : fullLicense
      );
    } else {
      _caption = title ? (0, import_i18n143.sprintf)(
        // translators: %1s: Title of a media work from Openverse; %2s: Work's licence e.g: "CC0 1.0".
        (0, import_i18n143._x)('"%1$s"/ %2$s', "caption"),
        getExternalLink(
          foreignLandingUrl,
          (0, import_html_entities10.decodeEntities)(title)
        ),
        licenseUrl ? getExternalLink(
          `${licenseUrl}?ref=openverse`,
          fullLicense
        ) : fullLicense
      ) : (0, import_i18n143.sprintf)(
        // translators: %1s: Link attributes for a given Openverse media work; %2s: Works's licence e.g: "CC0 1.0".
        (0, import_i18n143._x)("<a %1$s>Work</a>/ %2$s", "caption"),
        getExternalLinkAttributes(foreignLandingUrl),
        licenseUrl ? getExternalLink(
          `${licenseUrl}?ref=openverse`,
          fullLicense
        ) : fullLicense
      );
    }
    return _caption.replace(/\s{2}/g, " ");
  };
  var getCoreMediaQuery = (query = {}) => ({
    ...query,
    orderBy: !!query?.search ? "relevance" : "date"
  });
  var coreMediaFetch = async (query = {}) => {
    const finalQuery = getCoreMediaQuery(query);
    const records = await (0, import_data47.resolveSelect)(import_core_data30.store).getEntityRecords(
      "postType",
      "attachment",
      finalQuery
    );
    const totalItems = (0, import_data47.select)(import_core_data30.store).getEntityRecordsTotalItems(
      "postType",
      "attachment",
      finalQuery
    );
    const totalPages = (0, import_data47.select)(import_core_data30.store).getEntityRecordsTotalPages(
      "postType",
      "attachment",
      finalQuery
    );
    return {
      mediaItems: records.map((record) => ({
        ...record,
        alt: record.alt_text,
        url: record.source_url,
        previewUrl: record.media_details?.sizes?.medium?.source_url,
        caption: record.caption?.raw
      })),
      totalItems,
      totalPages
    };
  };
  var getAttachedImagesQuery = (postId2, query = {}) => ({
    ...query,
    media_type: "image",
    parent: postId2
  });
  var normalizePostId = (postId2) => {
    const parsedPostId = typeof postId2 === "number" ? postId2 : Number(postId2);
    return Number.isInteger(parsedPostId) && parsedPostId > 0 ? parsedPostId : void 0;
  };
  var saveAttachmentParent = (attachmentId, postId2) => (
    // `throwOnError` so a failed REST write rejects (rather than being silently
    // swallowed), letting the attach/detach handlers surface an error notice
    // instead of a false success.
    (0, import_data47.dispatch)(import_core_data30.store).saveEntityRecord(
      "postType",
      "attachment",
      {
        id: attachmentId,
        post: postId2
      },
      { throwOnError: true }
    )
  );
  var getMediaItemType = (mediaItem) => mediaItem?.media_type || mediaItem?.mime_type?.split("/")[0] || mediaItem?.type;
  var getImageAttachmentIds = (mediaItems) => [
    ...new Set(
      (Array.isArray(mediaItems) ? mediaItems : [mediaItems]).filter(
        (mediaItem) => getMediaItemType(mediaItem) === "image"
      ).map((mediaItem) => mediaItem?.id).filter(Boolean)
    )
  ];
  var invalidateAttachedImagesQueries = (postId2, query = {}) => {
    const { invalidateResolution } = (0, import_data47.dispatch)(import_core_data30.store);
    invalidateResolution("getEntityRecords", [
      "postType",
      "attachment",
      getCoreMediaQuery(getAttachedImagesQuery(postId2, query))
    ]);
  };
  var subscribeToMediaInvalidation = (args, onChange) => {
    const isResolved = () => (0, import_data47.select)(import_core_data30.store).hasFinishedResolution("getEntityRecords", args);
    let wasResolved = isResolved();
    return (0, import_data47.subscribe)(() => {
      const nowResolved = isResolved();
      if (wasResolved && !nowResolved) {
        onChange();
      }
      wasResolved = nowResolved;
    }, import_core_data30.store);
  };
  var createCoreMediaCategory = ({ getQuery, ...category }) => ({
    ...category,
    async fetch(query = {}) {
      return coreMediaFetch(getQuery(query));
    },
    subscribe(onChange, query = {}) {
      return subscribeToMediaInvalidation(
        [
          "postType",
          "attachment",
          getCoreMediaQuery(getQuery(query))
        ],
        onChange
      );
    }
  });
  var getAttachedImagesCategory = (postId2, typeLabel) => createCoreMediaCategory({
    name: "attached-images",
    labels: {
      name: (0, import_i18n143.__)("Attached images"),
      search_items: (0, import_i18n143.__)("Search attachments")
    },
    mediaType: "image",
    getQuery: (query) => getAttachedImagesQuery(postId2, query),
    // The post type's singular label (e.g. "Page"), threaded through so the
    // shared panel can word its attach/detach copy for the current post type.
    postTypeLabel: typeLabel,
    // Empty-state message. Providing this also keeps the source in the tab
    // list when it has no items, so it stays discoverable and the first
    // image can be attached even with none yet.
    emptyMessage: typeLabel ? (0, import_i18n143.sprintf)(
      // translators: %s: Name of the post type e.g: "Page".
      (0, import_i18n143.__)("No images attached to this %s."),
      typeLabel
    ) : (0, import_i18n143.__)("No images attached to this post."),
    async attach(mediaItems) {
      const attachmentIds = getImageAttachmentIds(mediaItems);
      await Promise.all(
        attachmentIds.map(
          (attachmentId) => saveAttachmentParent(attachmentId, postId2)
        )
      );
      return attachmentIds.length;
    },
    async detach(mediaItem) {
      await saveAttachmentParent(mediaItem.id, 0);
    },
    invalidate(query = {}) {
      invalidateAttachedImagesQueries(postId2, query);
    }
  });
  var inserterMediaCategories = [
    createCoreMediaCategory({
      name: "images",
      labels: {
        name: (0, import_i18n143.__)("Images"),
        search_items: (0, import_i18n143.__)("Search images")
      },
      mediaType: "image",
      getQuery: (query) => ({ ...query, media_type: "image" })
    }),
    createCoreMediaCategory({
      name: "videos",
      labels: {
        name: (0, import_i18n143.__)("Videos"),
        search_items: (0, import_i18n143.__)("Search videos")
      },
      mediaType: "video",
      getQuery: (query) => ({ ...query, media_type: "video" })
    }),
    createCoreMediaCategory({
      name: "audio",
      labels: {
        name: (0, import_i18n143.__)("Audio"),
        search_items: (0, import_i18n143.__)("Search audio")
      },
      mediaType: "audio",
      getQuery: (query) => ({ ...query, media_type: "audio" })
    }),
    {
      name: "openverse",
      labels: {
        name: (0, import_i18n143.__)("Openverse"),
        search_items: (0, import_i18n143.__)("Search Openverse")
      },
      mediaType: "image",
      async fetch(query = {}) {
        const defaultArgs = {
          mature: false,
          excluded_source: "flickr,inaturalist,wikimedia",
          license: "pdm,cc0"
        };
        const finalQuery = { ...query, ...defaultArgs };
        const mapFromInserterMediaRequest = {
          per_page: "page_size",
          search: "q"
        };
        const url = new URL("https://api.openverse.org/v1/images/");
        Object.entries(finalQuery).forEach(([key, value]) => {
          const queryKey = mapFromInserterMediaRequest[key] || key;
          url.searchParams.set(queryKey, value);
        });
        const response = await window.fetch(url, {
          headers: {
            "User-Agent": "WordPress/inserter-media-fetch"
          }
        });
        const jsonResponse = await response.json();
        const results = jsonResponse.results;
        return results.map((result) => ({
          ...result,
          // This is a temp solution for better titles, until Openverse API
          // completes the cleaning up of some titles of their upstream data.
          title: result.title?.toLowerCase().startsWith("file:") ? result.title.slice(5) : result.title,
          sourceId: result.id,
          id: void 0,
          caption: getOpenverseCaption(result),
          previewUrl: result.thumbnail
        }));
      },
      getReportUrl: ({ sourceId }) => `https://wordpress.org/openverse/image/${sourceId}/report/`,
      isExternalResource: true
    }
  ];
  function getInserterMediaCategories(postId2, viewablePostTypeLabel) {
    const currentPostId = normalizePostId(postId2);
    if (!currentPostId || !viewablePostTypeLabel) {
      return inserterMediaCategories;
    }
    return [
      getAttachedImagesCategory(currentPostId, viewablePostTypeLabel),
      ...inserterMediaCategories
    ];
  }

  // packages/editor/build-module/utils/media-upload/on-success.mjs
  var import_data48 = __toESM(require_data(), 1);
  var import_core_data31 = __toESM(require_core_data(), 1);
  function mediaUploadOnSuccess(attachments) {
    const { invalidateResolution } = (0, import_data48.dispatch)(import_core_data31.store);
    for (const attachment of attachments) {
      if (attachment.id) {
        invalidateResolution("getEntityRecord", [
          "postType",
          "attachment",
          attachment.id,
          { context: "view" }
        ]);
        invalidateResolution("getEntityRecord", [
          "postType",
          "attachment",
          attachment.id
        ]);
      }
    }
  }

  // packages/editor/build-module/utils/media-sideload/index.mjs
  var import_media_utils3 = __toESM(require_media_utils(), 1);
  var { sideloadMedia: mediaSideload } = unlock(import_media_utils3.privateApis);
  var media_sideload_default = mediaSideload;

  // packages/editor/build-module/utils/media-sideload-from-url/index.mjs
  var import_api_fetch3 = __toESM(require_api_fetch(), 1);
  var import_data49 = __toESM(require_data(), 1);
  var import_media_utils4 = __toESM(require_media_utils(), 1);
  var noop8 = () => {
  };
  function mediaSideloadFromUrl({
    url,
    onSuccess,
    onError = noop8
  }) {
    const currentPost = (0, import_data49.select)(store).getCurrentPost();
    const currentPostId = typeof currentPost?.id === "number" ? currentPost.id : currentPost?.wp_id;
    const postData = currentPostId ? { post: currentPostId } : {};
    (0, import_api_fetch3.default)({
      path: "/wp/v2/media",
      method: "POST",
      data: {
        url,
        ...postData
      }
    }).then((attachment) => {
      onSuccess?.((0, import_media_utils4.transformAttachment)(attachment));
    }).catch((error2) => {
      onError(error2?.message || error2);
    });
  }

  // packages/editor/build-module/utils/media-finalize/index.mjs
  var import_api_fetch4 = __toESM(require_api_fetch(), 1);
  var import_media_utils5 = __toESM(require_media_utils(), 1);
  async function mediaFinalize(id, subSizes = []) {
    const response = await (0, import_api_fetch4.default)({
      path: `/wp/v2/media/${id}/finalize`,
      method: "POST",
      data: { sub_sizes: subSizes }
    });
    return response ? (0, import_media_utils5.transformAttachment)(response) : void 0;
  }

  // packages/editor/build-module/utils/media-delete/index.mjs
  var import_api_fetch5 = __toESM(require_api_fetch(), 1);
  async function mediaDelete(id) {
    await (0, import_api_fetch5.default)({
      path: `/wp/v2/media/${id}?force=true`,
      method: "DELETE"
    });
  }

  // packages/editor/build-module/components/global-styles/index.mjs
  var import_core_data44 = __toESM(require_core_data(), 1);
  var import_data64 = __toESM(require_data(), 1);
  var import_element200 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/global-styles-ui.mjs
  var import_components150 = __toESM(require_components(), 1);
  var import_blocks11 = __toESM(require_blocks(), 1);
  var import_data61 = __toESM(require_data(), 1);
  var import_block_editor18 = __toESM(require_block_editor(), 1);
  var import_element197 = __toESM(require_element(), 1);
  var import_compose32 = __toESM(require_compose(), 1);

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

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

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

  // packages/global-styles-ui/build-module/screen-root.mjs
  var import_components99 = __toESM(require_components(), 1);
  var import_i18n148 = __toESM(require_i18n(), 1);
  var import_data51 = __toESM(require_data(), 1);
  var import_core_data33 = __toESM(require_core_data(), 1);

  // packages/global-styles-ui/build-module/icon-with-current-color.mjs
  var import_jsx_runtime289 = __toESM(require_jsx_runtime(), 1);
  function IconWithCurrentColor({
    className,
    ...props
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime289.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_components93 = __toESM(require_components(), 1);
  var import_jsx_runtime290 = __toESM(require_jsx_runtime(), 1);
  function GenericNavigationButton({
    icon,
    children,
    ...props
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime290.jsxs)(import_components93.__experimentalItem, { ...props, children: [
      icon && /* @__PURE__ */ (0, import_jsx_runtime290.jsxs)(import_components93.__experimentalHStack, { justify: "flex-start", children: [
        /* @__PURE__ */ (0, import_jsx_runtime290.jsx)(IconWithCurrentColor, { icon, size: 24 }),
        /* @__PURE__ */ (0, import_jsx_runtime290.jsx)(import_components93.FlexItem, { children })
      ] }),
      !icon && children
    ] });
  }
  function NavigationButtonAsItem(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime290.jsx)(import_components93.Navigator.Button, { as: GenericNavigationButton, ...props });
  }

  // packages/global-styles-ui/build-module/root-menu.mjs
  var import_components94 = __toESM(require_components(), 1);
  var import_i18n146 = __toESM(require_i18n(), 1);
  var import_block_editor5 = __toESM(require_block_editor(), 1);

  // node_modules/colord/plugins/a11y.mjs
  var o3 = function(o4) {
    var t4 = o4 / 255;
    return t4 < 0.04045 ? t4 / 12.92 : Math.pow((t4 + 0.055) / 1.055, 2.4);
  };
  var t3 = function(t4) {
    return 0.2126 * o3(t4.r) + 0.7152 * o3(t4.g) + 0.0722 * o3(t4.b);
  };
  function a11y_default(o4) {
    o4.prototype.luminance = function() {
      return o5 = t3(this.rgba), void 0 === (r4 = 2) && (r4 = 0), void 0 === n3 && (n3 = Math.pow(10, r4)), Math.round(n3 * o5) / n3 + 0;
      var o5, r4, n3;
    }, o4.prototype.contrast = function(r4) {
      void 0 === r4 && (r4 = "#FFF");
      var n3, a3, i3, e3, v3, u3, d3, c6 = r4 instanceof o4 ? r4 : new o4(r4);
      return e3 = this.rgba, v3 = c6.toRgb(), u3 = t3(e3), d3 = t3(v3), n3 = u3 > d3 ? (u3 + 0.05) / (d3 + 0.05) : (d3 + 0.05) / (u3 + 0.05), void 0 === (a3 = 2) && (a3 = 0), void 0 === i3 && (i3 = Math.pow(10, a3)), Math.floor(i3 * n3) / i3 + 0;
    }, o4.prototype.isReadable = function(o5, t4) {
      return void 0 === o5 && (o5 = "#FFF"), void 0 === t4 && (t4 = {}), this.contrast(o5) >= (e3 = void 0 === (i3 = (r4 = t4).size) ? "normal" : i3, "AAA" === (a3 = void 0 === (n3 = r4.level) ? "AA" : n3) && "normal" === e3 ? 7 : "AA" === a3 && "large" === e3 ? 3 : 4.5);
      var r4, n3, a3, i3, e3;
    };
  }

  // packages/global-styles-ui/build-module/hooks.mjs
  var import_element168 = __toESM(require_element(), 1);
  var import_data50 = __toESM(require_data(), 1);
  var import_core_data32 = __toESM(require_core_data(), 1);
  var import_i18n145 = __toESM(require_i18n(), 1);

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

  // packages/global-styles-ui/build-module/lock-unlock.mjs
  var import_private_apis10 = __toESM(require_private_apis(), 1);
  var { lock: lock7, unlock: unlock7 } = (0, import_private_apis10.__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: getViewportBreakpoints3 } = unlock7(privateApis);
  var VALID_ELEMENT_STATES = {
    link: [
      { value: ":link", label: (0, import_i18n144.__)("Link") },
      { value: ":any-link", label: (0, import_i18n144.__)("Any Link") },
      { value: ":visited", label: (0, import_i18n144.__)("Visited") },
      { value: ":hover", label: (0, import_i18n144.__)("Hover") },
      { value: ":focus", label: (0, import_i18n144.__)("Focus") },
      { value: ":focus-visible", label: (0, import_i18n144.__)("Focus-visible") },
      { value: ":active", label: (0, import_i18n144.__)("Active") }
    ],
    button: [
      { value: ":link", label: (0, import_i18n144.__)("Link") },
      { value: ":any-link", label: (0, import_i18n144.__)("Any Link") },
      { value: ":visited", label: (0, import_i18n144.__)("Visited") },
      { value: ":hover", label: (0, import_i18n144.__)("Hover") },
      { value: ":focus", label: (0, import_i18n144.__)("Focus") },
      { value: ":focus-visible", label: (0, import_i18n144.__)("Focus-visible") },
      { value: ":active", label: (0, import_i18n144.__)("Active") }
    ]
  };
  var VALID_BLOCK_STATES = {
    "core/button": [
      { value: ":hover", label: (0, import_i18n144.__)("Hover") },
      { value: ":focus", label: (0, import_i18n144.__)("Focus") },
      { value: ":focus-visible", label: (0, import_i18n144.__)("Focus-visible") },
      { value: ":active", label: (0, import_i18n144.__)("Active") }
    ]
  };
  var RESPONSIVE_STATES = [
    { value: "@tablet", label: (0, import_i18n144.__)("Tablet") },
    { value: "@mobile", label: (0, import_i18n144.__)("Mobile") }
  ];
  function getValidPseudoStates(name2) {
    if (VALID_BLOCK_STATES[name2]) {
      return VALID_BLOCK_STATES[name2] ?? [];
    }
    if (VALID_ELEMENT_STATES[name2]) {
      return VALID_ELEMENT_STATES[name2];
    }
    return [];
  }
  function getValidViewportStates(viewportSettings) {
    const breakpoints = getViewportBreakpoints3(viewportSettings);
    return RESPONSIVE_STATES.filter(
      (state2) => (state2.value !== "@tablet" || breakpoints.tablet !== void 0) && (state2.value !== "@mobile" || breakpoints.mobile !== void 0)
    );
  }
  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];
  }
  function getVariationClassName(variation) {
    if (!variation) {
      return "";
    }
    return `is-style-${variation}`;
  }
  function getNewIndexFromPresets(presets, slugPrefix) {
    const nameRegex = new RegExp(`^${slugPrefix}([\\d]+)$`);
    const highestPresetValue = presets.reduce((currentHighest, preset) => {
      if (typeof preset?.slug === "string") {
        const matches = preset?.slug.match(nameRegex);
        if (matches) {
          const id = parseInt(matches[1], 10);
          if (id > currentHighest) {
            return id;
          }
        }
      }
      return currentHighest;
    }, 0);
    return highestPresetValue + 1;
  }

  // packages/global-styles-ui/build-module/hooks.mjs
  k([a11y_default]);
  function useStyle(path, blockName, readFrom = "merged", shouldDecodeEncode = true, state2) {
    const { user, base, merged, onChange } = (0, import_element168.useContext)(GlobalStylesContext);
    const statePathParts = state2?.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_element168.useMemo)(() => {
      const rawValue = getStyle(
        sourceValue,
        stylePath,
        blockName,
        shouldDecodeEncode
      );
      if (pseudoSelectorState) {
        return rawValue?.[pseudoSelectorState] ?? {};
      }
      return rawValue;
    }, [
      sourceValue,
      stylePath,
      blockName,
      shouldDecodeEncode,
      pseudoSelectorState
    ]);
    const setStyleValue = (0, import_element168.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_element168.useContext)(GlobalStylesContext);
    let sourceValue = merged;
    if (readFrom === "base") {
      sourceValue = base;
    } else if (readFrom === "user") {
      sourceValue = user;
    }
    const settingValue = (0, import_element168.useMemo)(
      () => getSetting(sourceValue, path, blockName),
      [sourceValue, path, blockName]
    );
    const setSettingValue = (0, import_element168.useCallback)(
      (newValue) => {
        const newGlobalStyles = setSetting(
          user,
          path,
          newValue,
          blockName
        );
        onChange(newGlobalStyles);
      },
      [user, onChange, path, blockName]
    );
    return [settingValue, setSettingValue];
  }
  var EMPTY_ARRAY12 = [];
  function hasThemeVariation({
    title,
    settings,
    styles
  }) {
    return title === (0, import_i18n145.__)("Default") || Object.keys(settings || {}).length > 0 || Object.keys(styles || {}).length > 0;
  }
  function useCurrentMergeThemeStyleVariationsWithUserConfig(properties = []) {
    const { variationsFromTheme } = (0, import_data50.useSelect)((select9) => {
      const _variationsFromTheme = select9(
        import_core_data32.store
      ).__experimentalGetCurrentThemeGlobalStylesVariations?.();
      return {
        variationsFromTheme: _variationsFromTheme || EMPTY_ARRAY12
      };
    }, []);
    const { user: userVariation } = (0, import_element168.useContext)(GlobalStylesContext);
    return (0, import_element168.useMemo)(() => {
      const clonedUserVariation = structuredClone(userVariation);
      const userVariationWithoutProperties = removePropertiesFromObject(
        clonedUserVariation,
        properties
      );
      userVariationWithoutProperties.title = (0, import_i18n145.__)("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]);
  }
  function useColorRandomizer(blockName) {
    const [themeColors, setThemeColors] = useSetting(
      "color.palette.theme",
      blockName
    );
    const randomizeColors = (0, import_element168.useCallback)(() => {
      if (!themeColors || !themeColors.length) {
        return;
      }
      const randomRotationValue = Math.floor(Math.random() * 225);
      const newColors = themeColors.map((colorObject) => {
        const { color } = colorObject;
        const newColor = w(color).rotate(randomRotationValue).toHex();
        return {
          ...colorObject,
          color: newColor
        };
      });
      setThemeColors(newColors);
    }, [themeColors, setThemeColors]);
    return window.__experimentalEnableColorRandomizer ? [randomizeColors] : [];
  }

  // packages/global-styles-ui/build-module/root-menu.mjs
  var import_jsx_runtime291 = __toESM(require_jsx_runtime(), 1);
  var {
    useHasDimensionsPanel,
    useHasTypographyPanel,
    useHasColorPanel,
    useSettingsForBlockElement,
    useHasBackgroundPanel
  } = unlock7(import_block_editor5.privateApis);
  function RootMenu() {
    const [rawSettings] = useSetting("");
    const settings = useSettingsForBlockElement(rawSettings);
    const hasBackgroundPanel = useHasBackgroundPanel(rawSettings);
    const hasTypographyPanel = useHasTypographyPanel(settings);
    const hasColorPanel = useHasColorPanel(settings);
    const hasShadowPanel = true;
    const hasDimensionsPanel = useHasDimensionsPanel(settings);
    const hasLayoutPanel = hasDimensionsPanel;
    return /* @__PURE__ */ (0, import_jsx_runtime291.jsx)(import_jsx_runtime291.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime291.jsxs)(import_components94.__experimentalItemGroup, { children: [
      hasTypographyPanel && /* @__PURE__ */ (0, import_jsx_runtime291.jsx)(
        NavigationButtonAsItem,
        {
          icon: typography_default,
          path: "/typography",
          children: (0, import_i18n146.__)("Typography")
        }
      ),
      hasColorPanel && /* @__PURE__ */ (0, import_jsx_runtime291.jsx)(NavigationButtonAsItem, { icon: color_default, path: "/colors", children: (0, import_i18n146.__)("Colors") }),
      hasBackgroundPanel && /* @__PURE__ */ (0, import_jsx_runtime291.jsx)(
        NavigationButtonAsItem,
        {
          icon: background_default,
          path: "/background",
          "aria-label": (0, import_i18n146.__)("Background styles"),
          children: (0, import_i18n146.__)("Background")
        }
      ),
      hasShadowPanel && /* @__PURE__ */ (0, import_jsx_runtime291.jsx)(NavigationButtonAsItem, { icon: shadow_default, path: "/shadows", children: (0, import_i18n146.__)("Shadows") }),
      hasLayoutPanel && /* @__PURE__ */ (0, import_jsx_runtime291.jsx)(NavigationButtonAsItem, { icon: layout_default, path: "/layout", children: (0, import_i18n146.__)("Layout") })
    ] }) });
  }
  var root_menu_default = RootMenu;

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

  // packages/global-styles-ui/build-module/preview-hooks.mjs
  function useStylesPreviewColors() {
    const [textColor = "black"] = useStyle("color.text");
    const [backgroundColor = "white"] = useStyle("color.background");
    const [headingColor = textColor] = useStyle(
      "elements.h1.color.text"
    );
    const [linkColor = headingColor] = useStyle(
      "elements.link.color.text"
    );
    const [buttonBackgroundColor = linkColor] = useStyle(
      "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_element169 = __toESM(require_element(), 1);
  var import_components95 = __toESM(require_components(), 1);
  var import_i18n147 = __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((a3, b3) => Math.abs(input - a3) - Math.abs(input - b3));
    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 i3 = start2; i3 <= end; i3 += 100) {
          result.push(i3);
        }
      } 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 formatFontFaceName(input) {
    if (!input) {
      return "";
    }
    let output = input.trim();
    if (output.includes(",")) {
      output = (output.split(",").find((item) => item.trim() !== "") ?? "").trim();
    }
    output = output.replace(/^["']|["']$/g, "");
    if (window.navigator.userAgent.toLowerCase().includes("firefox")) {
      output = `"${output}"`;
    }
    return 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;
  }
  function getFacePreviewStyle(face) {
    return {
      fontFamily: formatFontFamily(face.fontFamily),
      fontStyle: face.fontStyle || "normal",
      fontWeight: face.fontWeight || "400"
    };
  }

  // packages/global-styles-ui/build-module/typography-example.mjs
  var import_jsx_runtime292 = __toESM(require_jsx_runtime(), 1);
  function PreviewTypography({
    fontSize,
    variation
  }) {
    const { base } = (0, import_element169.useContext)(GlobalStylesContext);
    let config2 = base;
    if (variation) {
      config2 = { ...base, ...variation };
    }
    const [textColor] = useStyle("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_runtime292.jsxs)(
      import_components95.__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_runtime292.jsx)("span", { style: headingPreviewStyle, children: (0, import_i18n147._x)("A", "Uppercase letter A") }),
          /* @__PURE__ */ (0, import_jsx_runtime292.jsx)("span", { style: bodyPreviewStyle, children: (0, import_i18n147._x)("a", "Lowercase letter A") })
        ]
      }
    );
  }

  // packages/global-styles-ui/build-module/highlighted-colors.mjs
  var import_components96 = __toESM(require_components(), 1);
  var import_jsx_runtime293 = __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_runtime293.jsx)(
      import_components96.__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_components97 = __toESM(require_components(), 1);
  var import_compose27 = __toESM(require_compose(), 1);
  var import_element170 = __toESM(require_element(), 1);
  var import_jsx_runtime294 = __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"] = useStyle("color.background");
    const [gradientValue] = useStyle("color.gradient");
    const disableMotion = (0, import_compose27.useReducedMotion)();
    const [isHovered, setIsHovered] = (0, import_element170.useState)(false);
    const [containerResizeListener, { width }] = (0, import_compose27.useResizeObserver)();
    const [throttledWidth, setThrottledWidthState] = (0, import_element170.useState)(width);
    const [ratioState, setRatioState] = (0, import_element170.useState)();
    const setThrottledWidth = (0, import_compose27.useThrottle)(
      setThrottledWidthState,
      250,
      THROTTLE_OPTIONS
    );
    (0, import_element170.useLayoutEffect)(() => {
      if (width) {
        setThrottledWidth(width);
      }
    }, [width, setThrottledWidth]);
    (0, import_element170.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 isReady2 = !!width;
    return /* @__PURE__ */ (0, import_jsx_runtime294.jsxs)(import_jsx_runtime294.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime294.jsx)("div", { style: { position: "relative" }, children: containerResizeListener }),
      !isReady2 && // Match the preview aspect ratio so layout doesn't jump once width is measured.
      /* @__PURE__ */ (0, import_jsx_runtime294.jsx)(
        Skeleton,
        {
          className: "global-styles-ui-preview__wrapper",
          style: {
            aspectRatio: normalizedWidth / normalizedHeight
          }
        }
      ),
      isReady2 && /* @__PURE__ */ (0, import_jsx_runtime294.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_runtime294.jsx)(
            import_components97.__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_runtime295 = __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] = useStyle("typography.fontWeight");
    const [fontFamily = "serif"] = useStyle(
      "typography.fontFamily"
    );
    const [headingFontFamily = fontFamily] = useStyle(
      "elements.h1.typography.fontFamily"
    );
    const [headingFontWeight = fontWeight] = useStyle(
      "elements.h1.typography.fontWeight"
    );
    const [textColor = "black"] = useStyle("color.text");
    const [headingColor = textColor] = useStyle(
      "elements.h1.color.text"
    );
    const { paletteColors } = useStylesPreviewColors();
    return /* @__PURE__ */ (0, import_jsx_runtime295.jsxs)(
      preview_wrapper_default,
      {
        label,
        isFocused,
        withHoverView,
        children: [
          ({ ratio, key }) => /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(
            import_components98.__unstableMotion.div,
            {
              variants: firstFrameVariants,
              style: {
                height: "100%",
                overflow: "hidden"
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime295.jsxs)(
                import_components98.__experimentalHStack,
                {
                  spacing: 10 * ratio,
                  justify: "center",
                  style: {
                    height: "100%",
                    overflow: "hidden"
                  },
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(
                      PreviewTypography,
                      {
                        fontSize: 65 * ratio,
                        variation
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(import_components98.__experimentalVStack, { spacing: 4 * ratio, children: /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(
                      HighlightedColors,
                      {
                        normalizedColorSwatchSize: 32,
                        ratio
                      }
                    ) })
                  ]
                }
              )
            },
            key
          ),
          ({ key }) => /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(
            import_components98.__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_runtime295.jsx)(
                import_components98.__experimentalHStack,
                {
                  spacing: 0,
                  justify: "flex-start",
                  style: {
                    height: "100%",
                    overflow: "hidden"
                  },
                  children: paletteColors.slice(0, 4).map(({ color }, index2) => /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(
                    "div",
                    {
                      style: {
                        height: "100%",
                        background: color,
                        flexGrow: 1
                      }
                    },
                    index2
                  ))
                }
              )
            },
            key
          ),
          ({ ratio, key }) => /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(
            import_components98.__unstableMotion.div,
            {
              variants: secondFrameVariants,
              style: {
                height: "100%",
                width: "100%",
                overflow: "hidden",
                position: "absolute",
                top: 0
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime295.jsx)(
                import_components98.__experimentalVStack,
                {
                  spacing: 3 * ratio,
                  justify: "center",
                  style: {
                    height: "100%",
                    overflow: "hidden",
                    padding: 10 * ratio,
                    boxSizing: "border-box"
                  },
                  children: label && /* @__PURE__ */ (0, import_jsx_runtime295.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_runtime296 = __toESM(require_jsx_runtime(), 1);
  function ScreenRoot() {
    const hasVariations = (0, import_data51.useSelect)((select9) => {
      const { __experimentalGetCurrentThemeGlobalStylesVariations } = select9(import_core_data33.store);
      return !!__experimentalGetCurrentThemeGlobalStylesVariations()?.length;
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime296.jsxs)(
      import_components99.Card,
      {
        size: "small",
        isBorderless: true,
        className: "global-styles-ui-screen-root",
        isRounded: false,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components99.CardBody, { children: /* @__PURE__ */ (0, import_jsx_runtime296.jsxs)(import_components99.__experimentalVStack, { spacing: 4, children: [
            /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components99.Card, { className: "global-styles-ui-screen-root__active-style-tile", children: /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components99.CardMedia, { className: "global-styles-ui-screen-root__active-style-tile-preview", children: /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(preview_styles_default, {}) }) }),
            hasVariations && /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components99.__experimentalItemGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(NavigationButtonAsItem, { path: "/variations", children: /* @__PURE__ */ (0, import_jsx_runtime296.jsxs)(import_components99.__experimentalHStack, { justify: "space-between", children: [
              /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components99.FlexItem, { children: (0, import_i18n148.__)("Browse styles") }),
              /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
                IconWithCurrentColor,
                {
                  icon: (0, import_i18n148.isRTL)() ? chevron_left_default : chevron_right_default
                }
              )
            ] }) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(root_menu_default, {})
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components99.CardDivider, {}),
          /* @__PURE__ */ (0, import_jsx_runtime296.jsxs)(import_components99.CardBody, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
              import_components99.__experimentalSpacer,
              {
                as: "p",
                paddingTop: 2,
                paddingX: "13px",
                marginBottom: 4,
                children: (0, import_i18n148.__)(
                  "Customize the appearance of specific blocks for the whole site."
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components99.__experimentalItemGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(NavigationButtonAsItem, { path: "/blocks", children: /* @__PURE__ */ (0, import_jsx_runtime296.jsxs)(import_components99.__experimentalHStack, { justify: "space-between", children: [
              /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(import_components99.FlexItem, { children: (0, import_i18n148.__)("Blocks") }),
              /* @__PURE__ */ (0, import_jsx_runtime296.jsx)(
                IconWithCurrentColor,
                {
                  icon: (0, import_i18n148.isRTL)() ? chevron_left_default : chevron_right_default
                }
              )
            ] }) }) })
          ] })
        ]
      }
    );
  }
  var screen_root_default = ScreenRoot;

  // packages/global-styles-ui/build-module/screen-block-list.mjs
  var import_blocks8 = __toESM(require_blocks(), 1);
  var import_i18n150 = __toESM(require_i18n(), 1);
  var import_components102 = __toESM(require_components(), 1);
  var import_data53 = __toESM(require_data(), 1);
  var import_element171 = __toESM(require_element(), 1);
  var import_block_editor7 = __toESM(require_block_editor(), 1);
  var import_compose28 = __toESM(require_compose(), 1);
  var import_a11y6 = __toESM(require_a11y(), 1);

  // packages/global-styles-ui/build-module/variations/variations-panel.mjs
  var import_blocks7 = __toESM(require_blocks(), 1);
  var import_data52 = __toESM(require_data(), 1);
  var import_components100 = __toESM(require_components(), 1);
  var import_jsx_runtime297 = __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_data52.useSelect)(
      (select9) => {
        const { getBlockStyles } = select9(import_blocks7.store);
        return getBlockStyles(name2);
      },
      [name2]
    );
    const [variations] = useStyle("variations", name2);
    const variationNames = Object.keys(variations ?? {});
    return getFilteredBlockStyles(blockStyles, variationNames);
  }
  function VariationsPanel({ name: name2 }) {
    const coreBlockStyles = useBlockVariations(name2);
    return /* @__PURE__ */ (0, import_jsx_runtime297.jsx)(import_components100.__experimentalItemGroup, { isBordered: true, isSeparated: true, children: coreBlockStyles.map((style, index2) => {
      if (style?.isDefault) {
        return null;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime297.jsx)(
        NavigationButtonAsItem,
        {
          path: "/blocks/" + encodeURIComponent(name2) + "/variations/" + encodeURIComponent(style.name),
          children: style.label
        },
        index2
      );
    }) });
  }

  // packages/global-styles-ui/build-module/screen-header.mjs
  var import_components101 = __toESM(require_components(), 1);
  var import_i18n149 = __toESM(require_i18n(), 1);
  var import_block_editor6 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime298 = __toESM(require_jsx_runtime(), 1);
  var { StateControl, StateControlBadges } = unlock7(import_block_editor6.privateApis);
  function ScreenHeader({
    title,
    description,
    onBack,
    viewportStates,
    pseudoStates,
    selectedViewport = "default",
    selectedPseudoState = "default",
    onChangeViewport,
    onChangePseudoState,
    showResponsiveStateControls = true
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(import_components101.__experimentalVStack, { spacing: 0, children: /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(import_components101.__experimentalView, { children: /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(import_components101.__experimentalSpacer, { marginBottom: 0, paddingX: 4, paddingY: 3, children: /* @__PURE__ */ (0, import_jsx_runtime298.jsxs)(import_components101.__experimentalVStack, { spacing: 2, children: [
      /* @__PURE__ */ (0, import_jsx_runtime298.jsxs)(import_components101.__experimentalHStack, { spacing: 2, alignment: "top", children: [
        /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
          import_components101.Navigator.BackButton,
          {
            icon: (0, import_i18n149.isRTL)() ? chevron_right_default : chevron_left_default,
            size: "small",
            label: (0, import_i18n149.__)("Back"),
            onClick: onBack
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(import_components101.__experimentalSpacer, { children: /* @__PURE__ */ (0, import_jsx_runtime298.jsxs)(import_components101.__experimentalHStack, { justify: "space-between", alignment: "top", children: [
          /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
            import_components101.__experimentalHeading,
            {
              className: "global-styles-ui-header",
              level: 2,
              size: 13,
              children: title
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime298.jsxs)(import_components101.__experimentalVStack, { spacing: 2, alignment: "right", children: [
            /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
              StateControl,
              {
                viewportStates: showResponsiveStateControls ? viewportStates : [],
                pseudoStates,
                viewportValue: selectedViewport,
                pseudoStateValue: selectedPseudoState,
                onChangeViewport,
                onChangePseudoState
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(
              StateControlBadges,
              {
                viewportStates,
                pseudoStates,
                viewportValue: selectedViewport,
                pseudoStateValue: selectedPseudoState
              }
            )
          ] })
        ] }) })
      ] }),
      description && /* @__PURE__ */ (0, import_jsx_runtime298.jsx)(import_components101.__experimentalText, { className: "global-styles-ui-header__description", children: description })
    ] }) }) }) });
  }

  // packages/global-styles-ui/build-module/screen-block-list.mjs
  var import_jsx_runtime299 = __toESM(require_jsx_runtime(), 1);
  var {
    useHasDimensionsPanel: useHasDimensionsPanel2,
    useHasTypographyPanel: useHasTypographyPanel2,
    useHasBorderPanel,
    useSettingsForBlockElement: useSettingsForBlockElement2,
    useHasColorPanel: useHasColorPanel2,
    useHasBackgroundPanel: useHasBackgroundPanel2
  } = unlock7(import_block_editor7.privateApis);
  function useSortedBlockTypes() {
    const blockItems = (0, import_data53.useSelect)(
      (select9) => select9(import_blocks8.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 settings = useSettingsForBlockElement2(rawSettings, blockName);
    const hasTypographyPanel = useHasTypographyPanel2(settings);
    const hasColorPanel = useHasColorPanel2(settings);
    const hasBackgroundPanel = useHasBackgroundPanel2(settings);
    const hasBorderPanel = useHasBorderPanel(settings);
    const hasDimensionsPanel = useHasDimensionsPanel2(settings);
    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_runtime299.jsx)(
      NavigationButtonAsItem,
      {
        path: "/blocks/" + encodeURIComponent(block.name),
        children: /* @__PURE__ */ (0, import_jsx_runtime299.jsxs)(import_components102.__experimentalHStack, { justify: "flex-start", children: [
          /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(import_block_editor7.BlockIcon, { icon: block.icon }),
          /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(import_components102.FlexItem, { children: block.title })
        ] })
      }
    );
  }
  function BlockList({ filterValue }) {
    const sortedBlockTypes = useSortedBlockTypes();
    const debouncedSpeak = (0, import_compose28.useDebounce)(import_a11y6.speak, 500);
    const { isMatchingSearchTerm } = (0, import_data53.useSelect)(import_blocks8.store);
    const filteredBlockTypes = !filterValue ? sortedBlockTypes : sortedBlockTypes.filter(
      (blockType) => isMatchingSearchTerm(blockType, filterValue)
    );
    const blockTypesListRef = (0, import_element171.useRef)(null);
    (0, import_element171.useEffect)(() => {
      if (!filterValue) {
        return;
      }
      const count = blockTypesListRef.current?.childElementCount || 0;
      const resultsFoundMessage = (0, import_i18n150.sprintf)(
        /* translators: %d: number of results. */
        (0, import_i18n150._n)("%d result found.", "%d results found.", count),
        count
      );
      debouncedSpeak(resultsFoundMessage, "polite");
    }, [filterValue, debouncedSpeak]);
    return /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(
      "div",
      {
        ref: blockTypesListRef,
        className: "global-styles-ui-block-types-item-list",
        role: "list",
        children: filteredBlockTypes.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(import_components102.__experimentalText, { align: "center", as: "p", children: (0, import_i18n150.__)("No blocks found.") }) : filteredBlockTypes.map((block) => /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(
          BlockMenuItem,
          {
            block
          },
          "menu-itemblock-" + block.name
        ))
      }
    );
  }
  var MemoizedBlockList = (0, import_element171.memo)(BlockList);
  function ScreenBlockList() {
    const [filterValue, setFilterValue] = (0, import_element171.useState)("");
    const deferredFilterValue = (0, import_element171.useDeferredValue)(filterValue);
    return /* @__PURE__ */ (0, import_jsx_runtime299.jsxs)(import_jsx_runtime299.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(
        ScreenHeader,
        {
          title: (0, import_i18n150.__)("Blocks"),
          description: (0, import_i18n150.__)(
            "Customize the appearance of specific blocks and for the whole site."
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(
        import_components102.SearchControl,
        {
          className: "global-styles-ui-block-types-search",
          onChange: setFilterValue,
          value: filterValue,
          label: (0, import_i18n150.__)("Search"),
          placeholder: (0, import_i18n150.__)("Search")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime299.jsx)(MemoizedBlockList, { filterValue: deferredFilterValue })
    ] });
  }
  var screen_block_list_default = ScreenBlockList;

  // packages/global-styles-ui/build-module/screen-block.mjs
  var import_blocks10 = __toESM(require_blocks(), 1);
  var import_block_editor9 = __toESM(require_block_editor(), 1);
  var import_element173 = __toESM(require_element(), 1);
  var import_data54 = __toESM(require_data(), 1);
  var import_core_data34 = __toESM(require_core_data(), 1);
  var import_components105 = __toESM(require_components(), 1);
  var import_i18n151 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/block-preview-panel.mjs
  var import_block_editor8 = __toESM(require_block_editor(), 1);
  var import_blocks9 = __toESM(require_blocks(), 1);
  var import_components103 = __toESM(require_components(), 1);
  var import_element172 = __toESM(require_element(), 1);
  var import_jsx_runtime300 = __toESM(require_jsx_runtime(), 1);
  var { getViewportBreakpoints: getViewportBreakpoints4, getViewportBreakpointValueInPixels: getViewportBreakpointValueInPixels3 } = unlock7(
    privateApis
  );
  var DEFAULT_PREVIEW_WIDTH_BY_VIEWPORT = {
    default: 783,
    "@tablet": 600,
    "@mobile": 480
  };
  function getPreviewWidthByViewport(selectedViewport, viewportSettings) {
    const breakpoints = getViewportBreakpoints4(viewportSettings);
    const mobileWidth = getViewportBreakpointValueInPixels3(
      breakpoints.mobile
    );
    if (selectedViewport === "@mobile" && mobileWidth) {
      return mobileWidth;
    }
    const tabletWidth = getViewportBreakpointValueInPixels3(
      breakpoints.tablet
    );
    if (selectedViewport === "@tablet" && tabletWidth) {
      if (!mobileWidth) {
        return tabletWidth;
      }
      if (breakpoints.mobile === "480px" && breakpoints.tablet === "782px") {
        return DEFAULT_PREVIEW_WIDTH_BY_VIEWPORT["@tablet"];
      }
      return Math.round((mobileWidth + tabletWidth) / 2);
    }
    if (selectedViewport === "default") {
      const desktopBreakpoint = tabletWidth ?? mobileWidth;
      if (desktopBreakpoint) {
        return desktopBreakpoint + 1;
      }
    }
    return DEFAULT_PREVIEW_WIDTH_BY_VIEWPORT[selectedViewport];
  }
  var BlockPreviewPanel = ({
    name: name2,
    variation = "",
    selectedViewport = "default",
    selectedState = "default",
    stateStyles,
    viewportSettings
  }) => {
    const blockExample = (0, import_blocks9.getBlockType)(name2)?.example;
    const blocks = (0, import_element172.useMemo)(() => {
      if (!blockExample) {
        return null;
      }
      const example = {
        ...blockExample,
        attributes: {
          ...blockExample.attributes,
          style: void 0,
          className: variation ? getVariationClassName(variation) : blockExample.attributes?.className
        }
      };
      return (0, import_blocks9.getBlockFromExample)(name2, example);
    }, [name2, blockExample, variation]);
    const stateCSS = (0, import_element172.useMemo)(() => {
      if (selectedState === "default" || !stateStyles) {
        return "";
      }
      return generatePreviewStateStyles(stateStyles, name2);
    }, [selectedState, stateStyles, name2]);
    if (!blockExample) {
      return null;
    }
    const viewportWidth = getPreviewWidthByViewport(selectedViewport, viewportSettings) ?? blockExample.viewportWidth ?? 500;
    const normalizedViewportWidth = blockExample.viewportWidth ?? 500;
    const previewScale = Math.max(viewportWidth / normalizedViewportWidth, 1);
    const previewPadding = 24 * previewScale;
    const previewHeight = 144;
    const sidebarWidth = 235;
    const scale3 = sidebarWidth / viewportWidth;
    const minHeight = scale3 !== 0 && scale3 < 1 && previewHeight ? previewHeight / scale3 : previewHeight;
    return /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(import_components103.__experimentalSpacer, { marginX: 4, marginBottom: 4, children: /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
      "div",
      {
        className: "global-styles-ui__block-preview-panel",
        style: { maxHeight: previewHeight, boxSizing: "initial" },
        children: /* @__PURE__ */ (0, import_jsx_runtime300.jsx)(
          import_block_editor8.BlockPreview,
          {
            blocks,
            viewportWidth,
            minHeight: previewHeight,
            additionalStyles: (
              //We want this CSS to be in sync with the one in InserterPreviewPanel.
              [
                {
                  css: `
								body{
									padding: ${previewPadding}px;
									min-height:${Math.round(minHeight)}px;
									display:flex;
								}
								.is-root-container {
									width: ${100 / previewScale}%;
									transform: scale(${previewScale});
									transform-origin: top left;
								}
								${stateCSS}
							`
                }
              ]
            )
          }
        )
      }
    ) });
  };
  var block_preview_panel_default = BlockPreviewPanel;

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

  // packages/global-styles-ui/build-module/screen-block.mjs
  var import_jsx_runtime302 = __toESM(require_jsx_runtime(), 1);
  var BACKGROUND_BLOCK_DEFAULT_VALUES2 = {
    backgroundSize: "cover",
    backgroundPosition: "50% 50%"
    // used only when backgroundSize is 'contain'.
  };
  function applyFallbackStyle(border) {
    if (!border) {
      return border;
    }
    const hasColorOrWidth = border.color || border.width;
    if (!border.style && hasColorOrWidth) {
      return { ...border, style: "solid" };
    }
    if (border.style && !hasColorOrWidth) {
      return void 0;
    }
    return border;
  }
  function applyAllFallbackStyles(border) {
    if (!border) {
      return border;
    }
    if ((0, import_components105.__experimentalHasSplitBorders)(border)) {
      return {
        top: applyFallbackStyle(border.top),
        right: applyFallbackStyle(border.right),
        bottom: applyFallbackStyle(border.bottom),
        left: applyFallbackStyle(border.left)
      };
    }
    return applyFallbackStyle(border);
  }
  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
  } = unlock7(import_block_editor9.privateApis);
  function ScreenBlock({
    name: name2,
    variation,
    selectedViewport: controlledSelectedViewport,
    showResponsiveStateControls = true,
    showBlockStateControls = true
  }) {
    const {
      user: userConfig,
      merged: mergedConfig,
      onChange: onChangeGlobalStyles
    } = (0, import_element173.useContext)(GlobalStylesContext);
    let prefixParts = [];
    if (variation) {
      prefixParts = ["variations", variation].concat(prefixParts);
    }
    const prefix2 = prefixParts.join(".");
    const [localSelectedViewport, setSelectedViewport] = (0, import_element173.useState)("default");
    const [selectedPseudoState, setSelectedPseudoState] = (0, import_element173.useState)("default");
    const selectedViewport = controlledSelectedViewport ?? localSelectedViewport;
    const viewportSettings = mergedConfig.settings?.viewport;
    const validViewportStates = (0, import_element173.useMemo)(
      () => getValidViewportStates(viewportSettings),
      [viewportSettings]
    );
    const effectiveSelectedViewport = selectedViewport === "default" || validViewportStates.some(
      (state2) => state2.value === selectedViewport
    ) ? selectedViewport : "default";
    const validPseudoStates = (0, import_element173.useMemo)(
      () => getValidPseudoStates(name2),
      [name2]
    );
    const stateParam = [effectiveSelectedViewport, selectedPseudoState].filter((value) => value !== "default").join(".");
    const hasSelectedState = stateParam.length > 0;
    const [style, setStyle2] = useStyle(
      prefix2,
      name2,
      "user",
      false,
      hasSelectedState ? stateParam : void 0
    );
    const [inheritedStyle] = useStyle(
      prefix2,
      name2,
      "merged",
      false,
      hasSelectedState ? stateParam : void 0
    );
    const [userSettings] = useSetting("", name2, "user");
    const [rawSettings, setSettings] = useSetting("", name2);
    const settingsForBlockElement = useSettingsForBlockElement3(
      rawSettings,
      name2
    );
    const blockType = (0, import_blocks10.getBlockType)(name2);
    let disableBlockGap = false;
    if (settingsForBlockElement?.spacing?.blockGap && blockType?.supports?.spacing?.blockGap && (blockType?.supports?.spacing?.__experimentalSkipSerialization === true || blockType?.supports?.spacing?.__experimentalSkipSerialization?.some?.(
      (spacingType) => spacingType === "blockGap"
    ))) {
      disableBlockGap = true;
    }
    let disableAspectRatio = false;
    if (settingsForBlockElement?.dimensions?.aspectRatio && name2 === "core/group") {
      disableAspectRatio = true;
    }
    const settings = (0, import_element173.useMemo)(() => {
      const updatedSettings = structuredClone(settingsForBlockElement);
      if (disableBlockGap) {
        updatedSettings.spacing.blockGap = false;
      }
      if (disableAspectRatio) {
        updatedSettings.dimensions.aspectRatio = false;
      }
      return updatedSettings;
    }, [settingsForBlockElement, disableBlockGap, disableAspectRatio]);
    const blockVariations = useBlockVariations(name2);
    const hasBackgroundPanel = useHasBackgroundPanel3(settings);
    const hasTypographyPanel = useHasTypographyPanel3(settings);
    const hasColorPanel = useHasColorPanel3(settings);
    const hasBorderPanel = useHasBorderPanel2(settings);
    const hasDimensionsPanel = useHasDimensionsPanel3(settings);
    const hasFiltersPanel = useHasFiltersPanel(settings);
    const shouldShowFiltersPanel = hasFiltersPanel && effectiveSelectedViewport === "default";
    const hasImageSettingsPanel = useHasImageSettingsPanel(
      name2,
      userSettings,
      settings
    );
    const hasVariationsPanel = !!blockVariations?.length && !variation && !hasSelectedState;
    const { canEditCSS } = (0, import_data54.useSelect)((select9) => {
      const { getEntityRecord, __experimentalGetCurrentGlobalStylesId } = select9(import_core_data34.store);
      const globalStylesId = __experimentalGetCurrentGlobalStylesId();
      const globalStyles = globalStylesId ? getEntityRecord("root", "globalStyles", globalStylesId) : void 0;
      return {
        canEditCSS: !!globalStyles?._links?.["wp:action-edit-css"]
      };
    }, []);
    const currentBlockStyle = variation ? blockVariations.find((s3) => s3.name === variation) : null;
    const inheritedStyleWithLayout = (0, import_element173.useMemo)(() => {
      return {
        ...inheritedStyle,
        layout: settings.layout
      };
    }, [inheritedStyle, settings.layout]);
    const styleWithLayout = (0, import_element173.useMemo)(() => {
      return {
        ...style,
        layout: userSettings.layout
      };
    }, [style, userSettings.layout]);
    const onChangeDimensions = (newStyle) => {
      const updatedStyle = { ...newStyle };
      delete updatedStyle.layout;
      setStyle2(updatedStyle);
      if (newStyle.layout !== userSettings.layout) {
        setSettings({
          ...userSettings,
          layout: newStyle.layout
        });
      }
    };
    const onChangeLightbox = (newSetting) => {
      if (newSetting === void 0) {
        setSettings({
          ...rawSettings,
          lightbox: void 0
        });
      } else {
        setSettings({
          ...rawSettings,
          lightbox: {
            ...rawSettings.lightbox,
            ...newSetting
          }
        });
      }
    };
    const onChangeTypography = (newStyle) => {
      const { settings: newSettings, ...styleWithoutSettings } = newStyle;
      if (newSettings?.typography) {
        const stylePathForState = [prefix2, stateParam].filter(Boolean).join(".");
        let updatedConfig = setStyle(
          userConfig,
          stylePathForState,
          styleWithoutSettings,
          name2
        );
        updatedConfig = setSetting(
          updatedConfig,
          "typography",
          {
            ...userSettings.typography,
            ...newSettings.typography
          },
          name2
        );
        onChangeGlobalStyles(updatedConfig);
      } else {
        setStyle2(styleWithoutSettings);
      }
    };
    const onChangeBorders = (newStyle) => {
      if (!newStyle?.border) {
        setStyle2(newStyle);
        return;
      }
      const { radius, ...newBorder } = newStyle.border;
      const border = applyAllFallbackStyles(newBorder);
      const updatedBorder = !(0, import_components105.__experimentalHasSplitBorders)(border) ? {
        top: border,
        right: border,
        bottom: border,
        left: border
      } : {
        color: null,
        style: null,
        width: null,
        ...border
      };
      setStyle2({ ...newStyle, border: { ...updatedBorder, radius } });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime302.jsxs)(import_jsx_runtime302.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        ScreenHeader,
        {
          title: variation ? currentBlockStyle?.label : blockType?.title,
          viewportStates: validViewportStates,
          pseudoStates: showBlockStateControls ? validPseudoStates : [],
          selectedViewport: effectiveSelectedViewport,
          selectedPseudoState,
          onChangeViewport: showResponsiveStateControls ? setSelectedViewport : void 0,
          onChangePseudoState: setSelectedPseudoState,
          showResponsiveStateControls
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        block_preview_panel_default,
        {
          name: name2,
          variation,
          selectedViewport: effectiveSelectedViewport,
          selectedState: hasSelectedState ? stateParam : "default",
          stateStyles: hasSelectedState ? inheritedStyle : void 0,
          viewportSettings
        }
      ),
      hasVariationsPanel && /* @__PURE__ */ (0, import_jsx_runtime302.jsx)("div", { className: "global-styles-ui-screen-variations", children: /* @__PURE__ */ (0, import_jsx_runtime302.jsxs)(import_components105.__experimentalVStack, { spacing: 3, children: [
        /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(Subtitle, { children: (0, import_i18n151.__)("Style Variations") }),
        /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(VariationsPanel, { name: name2 })
      ] }) }),
      hasTypographyPanel && /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        StylesTypographyPanel,
        {
          inheritedValue: inheritedStyle,
          value: style,
          onChange: onChangeTypography,
          settings,
          isGlobalStyles: !hasSelectedState,
          showInheritanceLabelIndicators: false
        }
      ),
      hasBackgroundPanel && /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        StylesBackgroundPanel,
        {
          inheritedValue: inheritedStyle,
          value: style,
          onChange: setStyle2,
          settings,
          defaultValues: BACKGROUND_BLOCK_DEFAULT_VALUES2,
          showInheritanceLabelIndicators: false
        }
      ),
      shouldShowFiltersPanel && /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        StylesFiltersPanel,
        {
          inheritedValue: inheritedStyleWithLayout,
          value: styleWithLayout,
          onChange: setStyle2,
          settings,
          includeLayoutControls: true,
          showInheritanceLabelIndicators: false
        }
      ),
      hasDimensionsPanel && /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        StylesDimensionsPanel,
        {
          inheritedValue: inheritedStyleWithLayout,
          value: styleWithLayout,
          onChange: onChangeDimensions,
          settings,
          includeLayoutControls: true,
          showInheritanceLabelIndicators: false
        }
      ),
      hasBorderPanel && /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        StylesBorderPanel,
        {
          inheritedValue: inheritedStyle,
          value: style,
          onChange: onChangeBorders,
          settings,
          showInheritanceLabelIndicators: false
        }
      ),
      hasColorPanel && /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        StylesColorPanel,
        {
          inheritedValue: inheritedStyle,
          value: style,
          onChange: setStyle2,
          settings,
          showInheritanceLabelIndicators: false
        }
      ),
      hasImageSettingsPanel && !hasSelectedState && /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        ImageSettingsPanel,
        {
          onChange: onChangeLightbox,
          value: userSettings,
          inheritedValue: settings
        }
      ),
      canEditCSS && /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(import_components105.PanelBody, { title: (0, import_i18n151.__)("Advanced"), initialOpen: false, children: /* @__PURE__ */ (0, import_jsx_runtime302.jsx)(
        StylesAdvancedPanel,
        {
          value: style,
          onChange: setStyle2,
          inheritedValue: inheritedStyle,
          help: (0, import_i18n151.sprintf)(
            // translators: %s: is the name of a block e.g., 'Image' or 'Table'.
            (0, import_i18n151.__)(
              "Add your own CSS to customize the appearance of the %s block. You do not need to include a CSS selector, just add the property and value."
            ),
            blockType?.title
          )
        }
      ) })
    ] });
  }
  var screen_block_default = ScreenBlock;

  // packages/global-styles-ui/build-module/screen-typography.mjs
  var import_i18n165 = __toESM(require_i18n(), 1);
  var import_components124 = __toESM(require_components(), 1);
  var import_element185 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/screen-body.mjs
  var import_components106 = __toESM(require_components(), 1);
  var import_jsx_runtime303 = __toESM(require_jsx_runtime(), 1);
  function ScreenBody({ children, className }) {
    return /* @__PURE__ */ (0, import_jsx_runtime303.jsx)(
      import_components106.__experimentalSpacer,
      {
        className: clsx_default("global-styles-ui-screen-body", className),
        padding: 4,
        children
      }
    );
  }

  // packages/global-styles-ui/build-module/typography-elements.mjs
  var import_i18n152 = __toESM(require_i18n(), 1);
  var import_components107 = __toESM(require_components(), 1);
  var import_jsx_runtime304 = __toESM(require_jsx_runtime(), 1);
  function ElementItem({ parentMenu, element, label }) {
    const prefix2 = element === "text" || !element ? "" : `elements.${element}.`;
    const extraStyles = element === "link" ? {
      textDecoration: "underline"
    } : {};
    const [fontFamily] = useStyle(
      prefix2 + "typography.fontFamily"
    );
    const [fontStyle] = useStyle(prefix2 + "typography.fontStyle");
    const [fontWeight] = useStyle(
      prefix2 + "typography.fontWeight"
    );
    const [backgroundColor] = useStyle(
      prefix2 + "color.background"
    );
    const [fallbackBackgroundColor] = useStyle("color.background");
    const [gradientValue] = useStyle(prefix2 + "color.gradient");
    const [color] = useStyle(prefix2 + "color.text");
    return /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(NavigationButtonAsItem, { path: parentMenu + "/typography/" + element, children: /* @__PURE__ */ (0, import_jsx_runtime304.jsxs)(import_components107.__experimentalHStack, { justify: "flex-start", children: [
      /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(
        import_components107.FlexItem,
        {
          className: "global-styles-ui-screen-typography__indicator",
          "aria-hidden": "true",
          style: {
            fontFamily: fontFamily ?? "serif",
            background: gradientValue ?? backgroundColor ?? fallbackBackgroundColor,
            color,
            fontStyle,
            fontWeight,
            ...extraStyles
          },
          children: (0, import_i18n152.__)("Aa")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(import_components107.FlexItem, { children: label })
    ] }) });
  }
  function TypographyElements() {
    const parentMenu = "";
    return /* @__PURE__ */ (0, import_jsx_runtime304.jsxs)(import_components107.__experimentalVStack, { spacing: 3, children: [
      /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(Subtitle, { level: 3, children: (0, import_i18n152.__)("Elements") }),
      /* @__PURE__ */ (0, import_jsx_runtime304.jsxs)(import_components107.__experimentalItemGroup, { isBordered: true, isSeparated: true, children: [
        /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(
          ElementItem,
          {
            parentMenu,
            element: "text",
            label: (0, import_i18n152.__)("Text")
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(
          ElementItem,
          {
            parentMenu,
            element: "link",
            label: (0, import_i18n152.__)("Links")
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(
          ElementItem,
          {
            parentMenu,
            element: "heading",
            label: (0, import_i18n152.__)("Headings")
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(
          ElementItem,
          {
            parentMenu,
            element: "caption",
            label: (0, import_i18n152.__)("Captions")
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime304.jsx)(
          ElementItem,
          {
            parentMenu,
            element: "button",
            label: (0, import_i18n152.__)("Buttons")
          }
        )
      ] })
    ] });
  }
  var typography_elements_default = TypographyElements;

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

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

  // packages/global-styles-ui/build-module/variations/variation.mjs
  var import_element174 = __toESM(require_element(), 1);
  var import_keycodes5 = __toESM(require_keycodes(), 1);
  var import_i18n153 = __toESM(require_i18n(), 1);
  var import_jsx_runtime306 = __toESM(require_jsx_runtime(), 1);
  function Variation({
    variation,
    children,
    isPill = false,
    properties,
    showTooltip = false
  }) {
    const [isFocused, setIsFocused] = (0, import_element174.useState)(false);
    const {
      base,
      user,
      onChange: setUserConfig
    } = (0, import_element174.useContext)(GlobalStylesContext);
    const context = (0, import_element174.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_element174.useMemo)(
      () => areGlobalStylesEqual(user, variation),
      [user, variation]
    );
    let label = variation?.title;
    if (variation?.description) {
      label = (0, import_i18n153.sprintf)(
        /* translators: 1: variation title. 2: variation description. */
        (0, import_i18n153._x)("%1$s (%2$s)", "variation label"),
        variation?.title,
        variation?.description
      );
    }
    const content = /* @__PURE__ */ (0, import_jsx_runtime306.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_runtime306.jsx)(
          "div",
          {
            className: clsx_default("global-styles-ui-variations_item-preview", {
              "is-pill": isPill
            }),
            children: children(isFocused)
          }
        )
      }
    );
    return /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(GlobalStylesContext.Provider, { value: context, children: showTooltip ? /* @__PURE__ */ (0, import_jsx_runtime306.jsxs)(tooltip_exports.Root, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(tooltip_exports.Trigger, { render: content }),
      /* @__PURE__ */ (0, import_jsx_runtime306.jsx)(tooltip_exports.Popup, { children: variation?.title })
    ] }) : content });
  }

  // packages/global-styles-ui/build-module/variations/variations-typography.mjs
  var import_jsx_runtime307 = __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_runtime307.jsxs)(import_components109.__experimentalVStack, { spacing: 3, children: [
      title && /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(Subtitle, { level: 3, children: title }),
      /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(
        import_components109.__experimentalGrid,
        {
          columns: 3,
          gap,
          className: "global-styles-ui-style-variations-container",
          children: typographyVariations.map(
            (variation, index2) => {
              return /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(
                Variation,
                {
                  variation,
                  properties: propertiesToFilter,
                  showTooltip: true,
                  children: () => /* @__PURE__ */ (0, import_jsx_runtime307.jsx)(
                    preview_typography_default,
                    {
                      variation
                    }
                  )
                },
                index2
              );
            }
          )
        }
      )
    ] });
  }

  // packages/global-styles-ui/build-module/font-families.mjs
  var import_i18n163 = __toESM(require_i18n(), 1);
  var import_components122 = __toESM(require_components(), 1);
  var import_element184 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/font-library/context.mjs
  var import_element175 = __toESM(require_element(), 1);
  var import_data55 = __toESM(require_data(), 1);
  var import_core_data36 = __toESM(require_core_data(), 1);
  var import_i18n155 = __toESM(require_i18n(), 1);

  // packages/global-styles-ui/build-module/font-library/api.mjs
  var import_api_fetch6 = __toESM(require_api_fetch(), 1);
  var import_core_data35 = __toESM(require_core_data(), 1);
  var FONT_FAMILIES_URL = "/wp/v2/font-families";
  function invalidateFontFamilyCache(registry) {
    const { receiveEntityRecords } = registry.dispatch(import_core_data35.store);
    receiveEntityRecords(
      "postType",
      "wp_font_family",
      [],
      void 0,
      true
      // invalidateCache
    );
  }
  async function fetchInstallFontFamily(data, registry) {
    const config2 = {
      path: FONT_FAMILIES_URL,
      method: "POST",
      body: data
    };
    const response = await (0, import_api_fetch6.default)(config2);
    invalidateFontFamilyCache(registry);
    return {
      id: response.id,
      ...response.font_family_settings,
      fontFace: []
    };
  }
  async function fetchInstallFontFace(fontFamilyId, data, registry) {
    const config2 = {
      path: `${FONT_FAMILIES_URL}/${fontFamilyId}/font-faces`,
      method: "POST",
      body: data
    };
    const response = await (0, import_api_fetch6.default)(config2);
    invalidateFontFamilyCache(registry);
    return {
      id: response.id,
      ...response.font_face_settings
    };
  }

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

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

  // packages/global-styles-ui/build-module/font-library/utils/index.mjs
  var { File: File2 } = window;
  var { kebabCase: kebabCase3 } = unlock7(import_components110.privateApis);
  function setUIValuesNeeded(font2, extraValues = {}) {
    if (!font2.name && (font2.fontFamily || font2.slug)) {
      font2.name = font2.fontFamily || font2.slug;
    }
    return {
      ...font2,
      ...extraValues
    };
  }
  function isUrlEncoded(url) {
    if (typeof url !== "string") {
      return false;
    }
    return url !== decodeURIComponent(url);
  }
  function getFontFaceVariantName(face) {
    const weightName = FONT_WEIGHTS[face.fontWeight ?? ""] || face.fontWeight;
    const styleName = face.fontStyle === "normal" ? "" : FONT_STYLES[face.fontStyle ?? ""] || face.fontStyle;
    return `${weightName} ${styleName}`;
  }
  function mergeFontFaces(existing = [], incoming = []) {
    const map = /* @__PURE__ */ new Map();
    for (const face of existing) {
      map.set(`${face.fontWeight}${face.fontStyle}`, face);
    }
    for (const face of incoming) {
      map.set(`${face.fontWeight}${face.fontStyle}`, face);
    }
    return Array.from(map.values());
  }
  function mergeFontFamilies(existing = [], incoming = []) {
    const map = /* @__PURE__ */ new Map();
    for (const font2 of existing) {
      map.set(font2.slug, { ...font2 });
    }
    for (const font2 of incoming) {
      if (map.has(font2.slug)) {
        const { fontFace: incomingFontFaces, ...restIncoming } = font2;
        const existingFont = map.get(font2.slug);
        const mergedFontFaces = mergeFontFaces(
          existingFont.fontFace,
          incomingFontFaces
        );
        map.set(font2.slug, {
          ...restIncoming,
          fontFace: mergedFontFaces
        });
      } else {
        map.set(font2.slug, { ...font2 });
      }
    }
    return Array.from(map.values());
  }
  async function loadFontFaceInBrowser(fontFace, source, addTo = "all") {
    let dataSource;
    if (typeof source === "string") {
      dataSource = `url(${source})`;
    } else if (source instanceof File2) {
      dataSource = await source.arrayBuffer();
    } else {
      return;
    }
    const newFont = new window.FontFace(
      formatFontFaceName(fontFace.fontFamily),
      dataSource,
      {
        style: fontFace.fontStyle,
        weight: String(fontFace.fontWeight)
      }
    );
    const loadedFace = await newFont.load();
    if (addTo === "document" || addTo === "all") {
      document.fonts.add(loadedFace);
    }
    if (addTo === "iframe" || addTo === "all") {
      const iframe = document.querySelector(
        'iframe[name="editor-canvas"]'
      );
      if (iframe?.contentDocument) {
        iframe.contentDocument.fonts.add(loadedFace);
      }
    }
  }
  function unloadFontFaceInBrowser(fontFace, removeFrom = "all") {
    const unloadFontFace = (fonts) => {
      fonts.forEach((f3) => {
        if (f3.family === formatFontFaceName(fontFace?.fontFamily) && f3.weight === fontFace?.fontWeight && f3.style === fontFace?.fontStyle) {
          fonts.delete(f3);
        }
      });
    };
    if (removeFrom === "document" || removeFrom === "all") {
      unloadFontFace(document.fonts);
    }
    if (removeFrom === "iframe" || removeFrom === "all") {
      const iframe = document.querySelector(
        'iframe[name="editor-canvas"]'
      );
      if (iframe?.contentDocument) {
        unloadFontFace(iframe.contentDocument.fonts);
      }
    }
  }
  function getDisplaySrcFromFontFace(input) {
    if (!input) {
      return;
    }
    let src;
    if (Array.isArray(input)) {
      src = input[0];
    } else {
      src = input;
    }
    if (src.startsWith("file:.")) {
      return;
    }
    if (!isUrlEncoded(src)) {
      src = encodeURI(src);
    }
    return src;
  }
  function makeFontFamilyFormData(fontFamily) {
    const formData = new FormData();
    const { fontFace, category, ...familyWithValidParameters } = fontFamily;
    const fontFamilySettings = {
      ...familyWithValidParameters,
      slug: kebabCase3(fontFamily.slug)
    };
    formData.append(
      "font_family_settings",
      JSON.stringify(fontFamilySettings)
    );
    return formData;
  }
  function makeFontFacesFormData(font2) {
    const fontFacesFormData = (font2?.fontFace ?? []).map(
      (item, faceIndex) => {
        const face = { ...item };
        const formData = new FormData();
        if (face.file) {
          const files = Array.isArray(face.file) ? face.file : [face.file];
          const src = [];
          files.forEach((file, key) => {
            const fileId = `file-${faceIndex}-${key}`;
            formData.append(fileId, file, file.name);
            src.push(fileId);
          });
          face.src = src.length === 1 ? src[0] : src;
          delete face.file;
          formData.append("font_face_settings", JSON.stringify(face));
        } else {
          formData.append("font_face_settings", JSON.stringify(face));
        }
        return formData;
      }
    );
    return fontFacesFormData;
  }
  async function batchInstallFontFaces(fontFamilyId, fontFacesData, registry) {
    const responses = [];
    for (const faceData of fontFacesData) {
      try {
        const response = await fetchInstallFontFace(
          fontFamilyId,
          faceData,
          registry
        );
        responses.push({ status: "fulfilled", value: response });
      } catch (error2) {
        responses.push({ status: "rejected", reason: error2 });
      }
    }
    const results = {
      errors: [],
      successes: []
    };
    responses.forEach((result, index2) => {
      if (result.status === "fulfilled" && result.value) {
        const response = result.value;
        results.successes.push(response);
      } else if (result.reason) {
        results.errors.push({
          data: fontFacesData[index2],
          message: result.reason.message
        });
      }
    });
    return results;
  }
  async function downloadFontFaceAssets(src) {
    src = Array.isArray(src) ? src : [src];
    const files = await Promise.all(
      src.map(async (url) => {
        return fetch(new Request(url)).then((response) => {
          if (!response.ok) {
            throw new Error(
              `Error downloading font face asset from ${url}. Server responded with status: ${response.status}`
            );
          }
          return response.blob();
        }).then((blob) => {
          const filename = url.split("/").pop();
          const file = new File2([blob], filename, {
            type: blob.type
          });
          return file;
        });
      })
    );
    return files.length === 1 ? files[0] : files;
  }
  function checkFontFaceInstalled(fontFace, collection) {
    return -1 !== collection.findIndex((collectionFontFace) => {
      return collectionFontFace.fontWeight === fontFace.fontWeight && collectionFontFace.fontStyle === fontFace.fontStyle;
    });
  }

  // packages/global-styles-ui/build-module/font-library/utils/set-immutably.mjs
  function setImmutably2(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;
  }

  // packages/global-styles-ui/build-module/font-library/utils/toggleFont.mjs
  function toggleFont(font2, face, initialfonts = []) {
    const isFontActivated = (f3) => f3.slug === font2.slug;
    const getActivatedFont = (fonts) => fonts.find(isFontActivated);
    const toggleEntireFontFamily = (activatedFont2) => {
      if (!activatedFont2) {
        return [...initialfonts, font2];
      }
      return initialfonts.filter(
        (f3) => !isFontActivated(f3)
      );
    };
    const toggleFontVariant = (activatedFont2) => {
      const isFaceActivated = (f3) => f3.fontWeight === face.fontWeight && f3.fontStyle === face.fontStyle;
      if (!activatedFont2) {
        return [...initialfonts, { ...font2, fontFace: [face] }];
      }
      let newFontFaces = activatedFont2.fontFace || [];
      if (newFontFaces.find(isFaceActivated)) {
        newFontFaces = newFontFaces.filter(
          (f3) => !isFaceActivated(f3)
        );
      } else {
        newFontFaces = [...newFontFaces, face];
      }
      if (newFontFaces.length === 0) {
        return initialfonts.filter(
          (f3) => !isFontActivated(f3)
        );
      }
      return initialfonts.map(
        (f3) => isFontActivated(f3) ? { ...f3, fontFace: newFontFaces } : f3
      );
    };
    const activatedFont = getActivatedFont(initialfonts);
    if (!face) {
      return toggleEntireFontFamily(activatedFont);
    }
    return toggleFontVariant(activatedFont);
  }

  // packages/global-styles-ui/build-module/font-library/context.mjs
  var import_jsx_runtime308 = __toESM(require_jsx_runtime(), 1);
  var FontLibraryContext = (0, import_element175.createContext)(
    {}
  );
  FontLibraryContext.displayName = "FontLibraryContext";
  function FontLibraryProvider({ children }) {
    const registry = (0, import_data55.useRegistry)();
    const { saveEntityRecord, deleteEntityRecord } = (0, import_data55.useDispatch)(import_core_data36.store);
    const { globalStylesId } = (0, import_data55.useSelect)((select9) => {
      const { __experimentalGetCurrentGlobalStylesId } = select9(import_core_data36.store);
      return { globalStylesId: __experimentalGetCurrentGlobalStylesId() };
    }, []);
    const globalStyles = (0, import_core_data36.useEntityRecord)(
      "root",
      "globalStyles",
      globalStylesId
    );
    const [isInstalling, setIsInstalling] = (0, import_element175.useState)(false);
    const { records: libraryPosts = [], isResolving: isResolvingLibrary } = (0, import_core_data36.useEntityRecords)(
      "postType",
      "wp_font_family",
      {
        _embed: true
      }
    );
    const libraryFonts = (libraryPosts || []).map((fontFamilyPost) => {
      return {
        id: fontFamilyPost.id,
        ...fontFamilyPost.font_family_settings || {},
        fontFace: fontFamilyPost?._embedded?.font_faces?.map(
          (face) => face.font_face_settings
        ) || []
      };
    }) || [];
    const [fontFamilies, setFontFamilies] = useSetting("typography.fontFamilies");
    const saveFontFamilies = async (fonts) => {
      if (!globalStyles.record) {
        return;
      }
      const updatedGlobalStyles = globalStyles.record;
      const finalGlobalStyles = setImmutably2(
        updatedGlobalStyles ?? {},
        ["settings", "typography", "fontFamilies"],
        fonts
      );
      await saveEntityRecord("root", "globalStyles", finalGlobalStyles);
    };
    const [modalTabOpen, setModalTabOpen] = (0, import_element175.useState)("");
    const [libraryFontSelected, setLibraryFontSelected] = (0, import_element175.useState)(void 0);
    const themeFonts = fontFamilies?.theme ? fontFamilies.theme.map((f3) => setUIValuesNeeded(f3, { source: "theme" })).sort((a3, b3) => a3.name.localeCompare(b3.name)) : [];
    const customFonts = fontFamilies?.custom ? fontFamilies.custom.map((f3) => setUIValuesNeeded(f3, { source: "custom" })).sort((a3, b3) => a3.name.localeCompare(b3.name)) : [];
    const baseCustomFonts = libraryFonts ? libraryFonts.map((f3) => setUIValuesNeeded(f3, { source: "custom" })).sort((a3, b3) => a3.name.localeCompare(b3.name)) : [];
    (0, import_element175.useEffect)(() => {
      if (!modalTabOpen) {
        setLibraryFontSelected(void 0);
      }
    }, [modalTabOpen]);
    const handleSetLibraryFontSelected = (font2) => {
      if (!font2) {
        setLibraryFontSelected(void 0);
        return;
      }
      const fonts = font2.source === "theme" ? themeFonts : baseCustomFonts;
      const fontSelected = fonts.find((f3) => f3.slug === font2.slug);
      setLibraryFontSelected({
        ...fontSelected || font2,
        source: font2.source
      });
    };
    const [loadedFontUrls] = (0, import_element175.useState)(/* @__PURE__ */ new Set());
    const getAvailableFontsOutline = (availableFontFamilies) => {
      const outline = availableFontFamilies.reduce(
        (acc, font2) => {
          const availableFontFaces = font2?.fontFace && font2.fontFace?.length > 0 ? font2?.fontFace.map(
            (face) => `${face.fontStyle ?? ""}${face.fontWeight ?? ""}`
          ) : ["normal400"];
          acc[font2.slug] = availableFontFaces;
          return acc;
        },
        {}
      );
      return outline;
    };
    const getActivatedFontsOutline = (source) => {
      switch (source) {
        case "theme":
          return getAvailableFontsOutline(themeFonts);
        case "custom":
        default:
          return getAvailableFontsOutline(customFonts);
      }
    };
    const isFontActivated = (slug, style, weight, source) => {
      if (!style && !weight) {
        return !!getActivatedFontsOutline(source)[slug];
      }
      return !!getActivatedFontsOutline(source)[slug]?.includes(
        (style ?? "") + (weight ?? "")
      );
    };
    const getFontFacesActivated = (slug, source) => {
      return getActivatedFontsOutline(source)[slug] || [];
    };
    async function installFonts(fontFamiliesToInstall) {
      setIsInstalling(true);
      try {
        const fontFamiliesToActivate = [];
        let installationErrors = [];
        for (const fontFamilyToInstall of fontFamiliesToInstall) {
          let isANewFontFamily = false;
          const fontFamilyRecords = await (0, import_data55.resolveSelect)(
            import_core_data36.store
          ).getEntityRecords(
            "postType",
            "wp_font_family",
            {
              slug: fontFamilyToInstall.slug,
              per_page: 1,
              _embed: true
            }
          );
          const fontFamilyPost = fontFamilyRecords && fontFamilyRecords.length > 0 ? fontFamilyRecords[0] : null;
          let installedFontFamily = fontFamilyPost ? {
            id: fontFamilyPost.id,
            ...fontFamilyPost.font_family_settings,
            fontFace: (fontFamilyPost?._embedded?.font_faces ?? []).map(
              (face) => face.font_face_settings
            ) || []
          } : null;
          if (!installedFontFamily) {
            isANewFontFamily = true;
            installedFontFamily = await fetchInstallFontFamily(
              makeFontFamilyFormData(fontFamilyToInstall),
              registry
            );
          }
          const alreadyInstalledFontFaces = installedFontFamily.fontFace && fontFamilyToInstall.fontFace ? installedFontFamily.fontFace.filter(
            (fontFaceToInstall) => fontFaceToInstall && fontFamilyToInstall.fontFace && checkFontFaceInstalled(
              fontFaceToInstall,
              fontFamilyToInstall.fontFace
            )
          ) : [];
          if (installedFontFamily.fontFace && fontFamilyToInstall.fontFace) {
            fontFamilyToInstall.fontFace = fontFamilyToInstall.fontFace.filter(
              (fontFaceToInstall) => !checkFontFaceInstalled(
                fontFaceToInstall,
                installedFontFamily.fontFace
              )
            );
          }
          let successfullyInstalledFontFaces = [];
          let unsuccessfullyInstalledFontFaces = [];
          if (fontFamilyToInstall?.fontFace?.length ?? 0 > 0) {
            const response = await batchInstallFontFaces(
              // @ts-expect-error - Type mismatch: WpFontFamily.id can be number | string, but batchInstallFontFaces expects only string.
              installedFontFamily.id,
              makeFontFacesFormData(
                fontFamilyToInstall
              ),
              registry
            );
            successfullyInstalledFontFaces = response?.successes;
            unsuccessfullyInstalledFontFaces = response?.errors;
          }
          if (successfullyInstalledFontFaces?.length > 0 || alreadyInstalledFontFaces?.length > 0) {
            installedFontFamily.fontFace = [
              ...successfullyInstalledFontFaces
            ];
            fontFamiliesToActivate.push(installedFontFamily);
          }
          if (installedFontFamily && !fontFamilyToInstall?.fontFace?.length) {
            fontFamiliesToActivate.push(installedFontFamily);
          }
          if (isANewFontFamily && (fontFamilyToInstall?.fontFace?.length ?? 0) > 0 && successfullyInstalledFontFaces?.length === 0) {
            await deleteEntityRecord(
              "postType",
              "wp_font_family",
              installedFontFamily.id,
              { force: true }
            );
          }
          installationErrors = installationErrors.concat(
            unsuccessfullyInstalledFontFaces
          );
        }
        const installationErrorMessages = installationErrors.reduce(
          (unique, item) => unique.includes(item.message) ? unique : [...unique, item.message],
          []
        );
        if (fontFamiliesToActivate.length > 0) {
          const activeFonts = activateCustomFontFamilies(
            // @ts-expect-error - Type mismatch: items may have id as number | string, but FontFamily.id should be string | undefined.
            fontFamiliesToActivate
          );
          await saveFontFamilies(activeFonts);
        }
        if (installationErrorMessages.length > 0) {
          const installError = new Error((0, import_i18n155.__)("There was an error installing fonts."));
          installError.installationErrors = installationErrorMessages;
          throw installError;
        }
      } finally {
        setIsInstalling(false);
      }
    }
    async function uninstallFontFamily(fontFamilyToUninstall) {
      if (!fontFamilyToUninstall?.id) {
        throw new Error((0, import_i18n155.__)("Font family to uninstall is not defined."));
      }
      try {
        await deleteEntityRecord(
          "postType",
          "wp_font_family",
          fontFamilyToUninstall.id,
          { force: true }
        );
        const activeFonts = deactivateFontFamily(fontFamilyToUninstall);
        await saveFontFamilies(activeFonts);
        return { deleted: true };
      } catch (error2) {
        console.error(
          `There was an error uninstalling the font family:`,
          error2
        );
        throw error2;
      }
    }
    const deactivateFontFamily = (font2) => {
      const initialCustomFonts = fontFamilies?.[font2.source ?? ""] ?? [];
      const newCustomFonts = initialCustomFonts.filter(
        (f3) => f3.slug !== font2.slug
      );
      const activeFonts = {
        ...fontFamilies,
        [font2.source ?? ""]: newCustomFonts
      };
      setFontFamilies(activeFonts);
      if (font2.fontFace) {
        font2.fontFace.forEach((face) => {
          unloadFontFaceInBrowser(face, "all");
        });
      }
      return activeFonts;
    };
    const activateCustomFontFamilies = (fontsToAdd) => {
      const fontsToActivate = cleanFontsForSave(fontsToAdd);
      const activeFonts = {
        ...fontFamilies,
        // Merge the existing custom fonts with the new fonts.
        custom: mergeFontFamilies(fontFamilies?.custom, fontsToActivate)
      };
      setFontFamilies(activeFonts);
      loadFontsInBrowser(fontsToActivate);
      return activeFonts;
    };
    const cleanFontsForSave = (fonts) => {
      return fonts.map(({ id: _familyDbId, fontFace, ...font2 }) => ({
        ...font2,
        ...fontFace && fontFace.length > 0 ? {
          fontFace: fontFace.map(
            ({ id: _faceDbId, ...face }) => face
          )
        } : {}
      }));
    };
    const loadFontsInBrowser = (fonts) => {
      fonts.forEach((font2) => {
        if (font2.fontFace) {
          font2.fontFace.forEach((face) => {
            const displaySrc = getDisplaySrcFromFontFace(
              face?.src ?? ""
            );
            if (displaySrc) {
              loadFontFaceInBrowser(face, displaySrc, "all");
            }
          });
        }
      });
    };
    const toggleActivateFont = (font2, face) => {
      const initialFonts = fontFamilies?.[font2.source ?? ""] ?? [];
      const newFonts = toggleFont(font2, face, initialFonts);
      setFontFamilies({
        ...fontFamilies,
        [font2.source ?? ""]: newFonts
      });
      const isFaceActivated = isFontActivated(
        font2.slug,
        face?.fontStyle ?? "",
        face?.fontWeight ?? "",
        font2.source ?? "custom"
      );
      if (face && isFaceActivated) {
        unloadFontFaceInBrowser(face, "all");
      } else {
        const displaySrc = getDisplaySrcFromFontFace(face?.src ?? "");
        if (face && displaySrc) {
          loadFontFaceInBrowser(face, displaySrc, "all");
        }
      }
    };
    const loadFontFaceAsset = async (fontFace) => {
      if (!fontFace.src) {
        return;
      }
      const src = getDisplaySrcFromFontFace(fontFace.src);
      if (!src || loadedFontUrls.has(src)) {
        return;
      }
      loadFontFaceInBrowser(fontFace, src, "document");
      loadedFontUrls.add(src);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime308.jsx)(
      FontLibraryContext.Provider,
      {
        value: {
          libraryFontSelected,
          handleSetLibraryFontSelected,
          fontFamilies: fontFamilies ?? {},
          baseCustomFonts,
          isFontActivated,
          getFontFacesActivated,
          loadFontFaceAsset,
          installFonts,
          uninstallFontFamily,
          toggleActivateFont,
          getAvailableFontsOutline,
          modalTabOpen,
          setModalTabOpen,
          saveFontFamilies,
          isResolvingLibrary,
          isInstalling
        },
        children
      }
    );
  }
  var context_default = FontLibraryProvider;

  // packages/global-styles-ui/build-module/font-library/modal.mjs
  var import_i18n161 = __toESM(require_i18n(), 1);
  var import_components120 = __toESM(require_components(), 1);
  var import_core_data39 = __toESM(require_core_data(), 1);
  var import_data57 = __toESM(require_data(), 1);

  // packages/global-styles-ui/build-module/font-library/installed-fonts.mjs
  var import_components114 = __toESM(require_components(), 1);
  var import_core_data37 = __toESM(require_core_data(), 1);
  var import_data56 = __toESM(require_data(), 1);
  var import_element179 = __toESM(require_element(), 1);
  var import_i18n157 = __toESM(require_i18n(), 1);

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

  // packages/global-styles-ui/build-module/font-library/font-demo.mjs
  var import_components111 = __toESM(require_components(), 1);
  var import_element176 = __toESM(require_element(), 1);
  var import_jsx_runtime309 = __toESM(require_jsx_runtime(), 1);
  function getPreviewUrl(fontFace) {
    if (fontFace.preview) {
      return fontFace.preview;
    }
    if (fontFace.src) {
      return Array.isArray(fontFace.src) ? fontFace.src[0] : fontFace.src;
    }
    return void 0;
  }
  function getDisplayFontFace(font2) {
    if ("fontStyle" in font2 && font2.fontStyle || "fontWeight" in font2 && font2.fontWeight) {
      return font2;
    }
    if ("fontFace" in font2 && font2.fontFace && font2.fontFace.length) {
      return font2.fontFace.find(
        (face) => face.fontStyle === "normal" && face.fontWeight === "400"
      ) || font2.fontFace[0];
    }
    return {
      fontStyle: "normal",
      fontWeight: "400",
      fontFamily: font2.fontFamily
    };
  }
  function FontDemo({ font: font2, text }) {
    const ref = (0, import_element176.useRef)(null);
    const fontFace = getDisplayFontFace(font2);
    const style = getFamilyPreviewStyle(font2);
    text = text || ("name" in font2 ? font2.name : "");
    const customPreviewUrl = font2.preview;
    const [isIntersecting, setIsIntersecting] = (0, import_element176.useState)(false);
    const [isAssetLoaded, setIsAssetLoaded] = (0, import_element176.useState)(false);
    const { loadFontFaceAsset } = (0, import_element176.useContext)(FontLibraryContext);
    const previewUrl = customPreviewUrl ?? getPreviewUrl(fontFace);
    const isPreviewImage = previewUrl && previewUrl.match(/\.(png|jpg|jpeg|gif|svg)$/i);
    const faceStyles = getFacePreviewStyle(fontFace);
    const textDemoStyle = {
      fontSize: "18px",
      lineHeight: 1,
      opacity: isAssetLoaded ? "1" : "0",
      ...style,
      ...faceStyles
    };
    (0, import_element176.useEffect)(() => {
      const observer = new window.IntersectionObserver(([entry]) => {
        setIsIntersecting(entry.isIntersecting);
      }, {});
      if (ref.current) {
        observer.observe(ref.current);
      }
      return () => observer.disconnect();
    }, [ref]);
    (0, import_element176.useEffect)(() => {
      const loadAsset = async () => {
        if (isIntersecting) {
          if (!isPreviewImage && fontFace.src) {
            await loadFontFaceAsset(fontFace);
          }
          setIsAssetLoaded(true);
        }
      };
      loadAsset();
    }, [fontFace, isIntersecting, loadFontFaceAsset, isPreviewImage]);
    return /* @__PURE__ */ (0, import_jsx_runtime309.jsx)("div", { ref, children: isPreviewImage ? /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
      "img",
      {
        src: previewUrl,
        loading: "lazy",
        alt: text,
        className: "font-library__font-variant_demo-image"
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime309.jsx)(
      import_components111.__experimentalText,
      {
        style: textDemoStyle,
        className: "font-library__font-variant_demo-text",
        children: text
      }
    ) });
  }
  var font_demo_default = FontDemo;

  // packages/global-styles-ui/build-module/font-library/font-card.mjs
  var import_jsx_runtime310 = __toESM(require_jsx_runtime(), 1);
  function FontCard({
    font: font2,
    onClick,
    variantsText,
    navigatorPath,
    shouldFocus
  }) {
    const variantsCount = font2.fontFace?.length || 1;
    const style = {
      cursor: !!onClick ? "pointer" : "default"
    };
    const navigator2 = (0, import_components112.useNavigator)();
    const ref = (0, import_element177.useRef)(null);
    (0, import_element177.useEffect)(() => {
      if (shouldFocus) {
        ref.current?.focus();
      }
    }, [shouldFocus]);
    return /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(
      import_components112.Button,
      {
        ref,
        __next40pxDefaultSize: true,
        onClick: () => {
          onClick();
          if (navigatorPath) {
            navigator2.goTo(navigatorPath);
          }
        },
        style,
        className: "font-library__font-card",
        children: /* @__PURE__ */ (0, import_jsx_runtime310.jsxs)(import_components112.Flex, { justify: "space-between", wrap: false, children: [
          /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(font_demo_default, { font: font2 }),
          /* @__PURE__ */ (0, import_jsx_runtime310.jsxs)(import_components112.Flex, { justify: "flex-end", children: [
            /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(import_components112.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(import_components112.__experimentalText, { className: "font-library__font-card__count", children: variantsText || (0, import_i18n156.sprintf)(
              /* translators: %d: Number of font variants. */
              (0, import_i18n156._n)(
                "%d variant",
                "%d variants",
                variantsCount
              ),
              variantsCount
            ) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(import_components112.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime310.jsx)(icon_default, { icon: (0, import_i18n156.isRTL)() ? chevron_left_default : chevron_right_default }) })
          ] })
        ] })
      }
    );
  }
  var font_card_default = FontCard;

  // packages/global-styles-ui/build-module/font-library/library-font-variant.mjs
  var import_element178 = __toESM(require_element(), 1);
  var import_components113 = __toESM(require_components(), 1);
  var import_jsx_runtime311 = __toESM(require_jsx_runtime(), 1);
  function LibraryFontVariant({
    face,
    font: font2
  }) {
    const { isFontActivated, toggleActivateFont } = (0, import_element178.useContext)(FontLibraryContext);
    const isInstalled = (font2?.fontFace?.length ?? 0) > 0 ? isFontActivated(
      font2.slug,
      face.fontStyle,
      face.fontWeight,
      font2.source
    ) : isFontActivated(font2.slug, void 0, void 0, font2.source);
    const handleToggleActivation = () => {
      if ((font2?.fontFace?.length ?? 0) > 0) {
        toggleActivateFont(font2, face);
        return;
      }
      toggleActivateFont(font2);
    };
    const displayName = font2.name + " " + getFontFaceVariantName(face);
    const checkboxId = (0, import_element178.useId)();
    return /* @__PURE__ */ (0, import_jsx_runtime311.jsx)("div", { className: "font-library__font-card", children: /* @__PURE__ */ (0, import_jsx_runtime311.jsxs)(import_components113.Flex, { justify: "flex-start", align: "center", gap: "1rem", children: [
      /* @__PURE__ */ (0, import_jsx_runtime311.jsx)(
        import_components113.CheckboxControl,
        {
          checked: isInstalled,
          onChange: handleToggleActivation,
          id: checkboxId
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime311.jsx)("label", { htmlFor: checkboxId, children: /* @__PURE__ */ (0, import_jsx_runtime311.jsx)(
        font_demo_default,
        {
          font: face,
          text: displayName,
          onClick: handleToggleActivation
        }
      ) })
    ] }) });
  }
  var library_font_variant_default = LibraryFontVariant;

  // packages/global-styles-ui/build-module/font-library/utils/sort-font-faces.mjs
  function getNumericFontWeight(value) {
    switch (value) {
      case "normal":
        return 400;
      case "bold":
        return 700;
      case "bolder":
        return 500;
      case "lighter":
        return 300;
      default:
        return parseInt(value, 10);
    }
  }
  function sortFontFaces(faces) {
    return faces.sort((a3, b3) => {
      if (a3.fontStyle === "normal" && b3.fontStyle !== "normal") {
        return -1;
      }
      if (b3.fontStyle === "normal" && a3.fontStyle !== "normal") {
        return 1;
      }
      if (a3.fontStyle === b3.fontStyle) {
        return getNumericFontWeight(a3.fontWeight?.toString() ?? "normal") - getNumericFontWeight(b3.fontWeight?.toString() ?? "normal");
      }
      if (!a3.fontStyle || !b3.fontStyle) {
        return !a3.fontStyle ? 1 : -1;
      }
      return a3.fontStyle.localeCompare(b3.fontStyle);
    });
  }

  // packages/global-styles-ui/build-module/font-library/installed-fonts.mjs
  var import_jsx_runtime312 = __toESM(require_jsx_runtime(), 1);
  function getFontFamiliesKey(fontFamilies) {
    if (!fontFamilies) {
      return "";
    }
    const normalized = {};
    for (const source of Object.keys(fontFamilies).sort()) {
      normalized[source] = (fontFamilies[source] ?? []).map((family) => ({
        slug: family.slug,
        fontFace: (family.fontFace ?? []).map(
          (face) => `${face.fontStyle}-${face.fontWeight}`
        ).sort()
      })).sort((a3, b3) => a3.slug.localeCompare(b3.slug));
    }
    return JSON.stringify(normalized);
  }
  function InstalledFonts() {
    const {
      baseCustomFonts,
      libraryFontSelected,
      handleSetLibraryFontSelected,
      uninstallFontFamily,
      isResolvingLibrary,
      isInstalling,
      saveFontFamilies,
      getFontFacesActivated
    } = (0, import_element179.useContext)(FontLibraryContext);
    const [fontFamilies, setFontFamilies] = useSetting("typography.fontFamilies");
    const [lastSelectedFontSlug, setLastSelectedFontSlug] = (0, import_element179.useState)(void 0);
    const [isConfirmDeleteOpen, setIsConfirmDeleteOpen] = (0, import_element179.useState)(false);
    const [notice, setNotice] = (0, import_element179.useState)(null);
    const [baseFontFamilies] = useSetting("typography.fontFamilies", void 0, "base");
    const globalStylesId = (0, import_data56.useSelect)((select9) => {
      const { __experimentalGetCurrentGlobalStylesId } = select9(import_core_data37.store);
      return __experimentalGetCurrentGlobalStylesId();
    }, []);
    const globalStyles = (0, import_core_data37.useEntityRecord)(
      "root",
      "globalStyles",
      globalStylesId
    );
    const editedFontFamilies = globalStyles?.edits?.settings?.typography?.fontFamilies;
    const savedFontFamilies = globalStyles?.record?.settings?.typography?.fontFamilies;
    const fontFamiliesHasChanges = (0, import_element179.useMemo)(() => {
      if (editedFontFamilies === void 0) {
        return false;
      }
      return getFontFamiliesKey(editedFontFamilies) !== getFontFamiliesKey(savedFontFamilies);
    }, [editedFontFamilies, savedFontFamilies]);
    const themeFonts = fontFamilies?.theme ? fontFamilies.theme.map((f3) => setUIValuesNeeded(f3, { source: "theme" })).sort((a3, b3) => a3.name.localeCompare(b3.name)) : [];
    const themeFontsSlugs = new Set(themeFonts.map((f3) => f3.slug));
    const baseThemeFonts = baseFontFamilies?.theme ? themeFonts.concat(
      baseFontFamilies.theme.filter((f3) => !themeFontsSlugs.has(f3.slug)).map((f3) => setUIValuesNeeded(f3, { source: "theme" })).sort((a3, b3) => a3.name.localeCompare(b3.name))
    ) : [];
    const customFontFamilyId = libraryFontSelected?.source === "custom" && libraryFontSelected?.id;
    const canUserDelete = (0, import_data56.useSelect)(
      (select9) => {
        const { canUser } = select9(import_core_data37.store);
        return customFontFamilyId && canUser("delete", {
          kind: "postType",
          name: "wp_font_family",
          id: customFontFamilyId
        });
      },
      [customFontFamilyId]
    );
    const shouldDisplayDeleteButton = !!libraryFontSelected && libraryFontSelected?.source !== "theme" && canUserDelete;
    const handleUninstallClick = () => {
      setIsConfirmDeleteOpen(true);
    };
    const handleUpdate = async () => {
      setNotice(null);
      try {
        await saveFontFamilies(fontFamilies);
        setNotice({
          type: "success",
          message: (0, import_i18n157.__)("Font family updated successfully.")
        });
      } catch (error2) {
        setNotice({
          type: "error",
          message: (0, import_i18n157.sprintf)(
            /* translators: %s: error message */
            (0, import_i18n157.__)("There was an error updating the font family. %s"),
            error2.message
          )
        });
      }
    };
    const getFontFacesToDisplay = (font2) => {
      if (!font2) {
        return [];
      }
      if (!font2.fontFace || !font2.fontFace.length) {
        return [
          {
            fontFamily: font2.fontFamily,
            fontStyle: "normal",
            fontWeight: "400"
          }
        ];
      }
      return sortFontFaces(font2.fontFace);
    };
    const getFontCardVariantsText = (font2) => {
      const variantsInstalled = font2?.fontFace && (font2?.fontFace?.length ?? 0) > 0 ? font2.fontFace.length : 1;
      const variantsActive = getFontFacesActivated(
        font2.slug,
        font2.source
      ).length;
      return (0, import_i18n157.sprintf)(
        /* translators: 1: Active font variants, 2: Total font variants. */
        (0, import_i18n157.__)("%1$d of %2$d active"),
        variantsActive,
        variantsInstalled
      );
    };
    (0, import_element179.useEffect)(() => {
      handleSetLibraryFontSelected(libraryFontSelected);
    }, []);
    const activeFontsCount = libraryFontSelected ? getFontFacesActivated(
      libraryFontSelected.slug,
      libraryFontSelected.source
    ).length : 0;
    const selectedFontsCount = libraryFontSelected?.fontFace?.length ?? (libraryFontSelected?.fontFamily ? 1 : 0);
    const isIndeterminate = activeFontsCount > 0 && activeFontsCount !== selectedFontsCount;
    const isSelectAllChecked = activeFontsCount === selectedFontsCount;
    const toggleSelectAll = () => {
      if (!libraryFontSelected || !libraryFontSelected?.source) {
        return;
      }
      const initialFonts = fontFamilies?.[libraryFontSelected.source]?.filter(
        (f3) => f3.slug !== libraryFontSelected.slug
      ) ?? [];
      const newFonts = isSelectAllChecked ? initialFonts : [...initialFonts, libraryFontSelected];
      setFontFamilies({
        ...fontFamilies,
        [libraryFontSelected.source]: newFonts
      });
      if (libraryFontSelected.fontFace) {
        libraryFontSelected.fontFace.forEach((face) => {
          if (isSelectAllChecked) {
            unloadFontFaceInBrowser(face, "all");
          } else {
            const displaySrc = getDisplaySrcFromFontFace(
              face?.src ?? ""
            );
            if (displaySrc) {
              loadFontFaceInBrowser(face, displaySrc, "all");
            }
          }
        });
      }
    };
    const hasFonts = baseThemeFonts.length > 0 || baseCustomFonts.length > 0;
    return /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)("div", { className: "font-library__tabpanel-layout", children: [
      isResolvingLibrary && /* @__PURE__ */ (0, import_jsx_runtime312.jsx)("div", { className: "font-library__loading", children: /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components114.ProgressBar, {}) }),
      !isResolvingLibrary && /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_jsx_runtime312.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(
          import_components114.Navigator,
          {
            initialPath: libraryFontSelected ? "/fontFamily" : "/",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components114.Navigator.Screen, { path: "/", children: /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_components114.__experimentalVStack, { spacing: "8", children: [
                notice && /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                  import_components114.Notice,
                  {
                    status: notice.type,
                    onRemove: () => setNotice(null),
                    children: notice.message
                  }
                ),
                !hasFonts && /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components114.__experimentalText, { as: "p", children: (0, import_i18n157.__)("No fonts installed.") }),
                baseThemeFonts.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_components114.__experimentalVStack, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)("h2", {
                    className: "font-library__fonts-title",
                    /* translators: Heading for a list of fonts provided by the theme. */
                    children: (0, import_i18n157._x)("Theme", "font source")
                  }),
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                    "ul",
                    {
                      role: "list",
                      className: "font-library__fonts-list",
                      children: baseThemeFonts.map((font2) => /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                        "li",
                        {
                          className: "font-library__fonts-list-item",
                          children: /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                            font_card_default,
                            {
                              font: font2,
                              navigatorPath: "/fontFamily",
                              variantsText: getFontCardVariantsText(
                                font2
                              ),
                              shouldFocus: font2.slug === lastSelectedFontSlug,
                              onClick: () => {
                                setNotice(null);
                                handleSetLibraryFontSelected(
                                  font2
                                );
                              }
                            }
                          )
                        },
                        font2.slug
                      ))
                    }
                  )
                ] }),
                baseCustomFonts.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_components114.__experimentalVStack, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)("h2", {
                    className: "font-library__fonts-title",
                    /* translators: Heading for a list of fonts installed by the user. */
                    children: (0, import_i18n157._x)("Custom", "font source")
                  }),
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                    "ul",
                    {
                      role: "list",
                      className: "font-library__fonts-list",
                      children: baseCustomFonts.map((font2) => /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                        "li",
                        {
                          className: "font-library__fonts-list-item",
                          children: /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                            font_card_default,
                            {
                              font: font2,
                              navigatorPath: "/fontFamily",
                              variantsText: getFontCardVariantsText(
                                font2
                              ),
                              shouldFocus: font2.slug === lastSelectedFontSlug,
                              onClick: () => {
                                setNotice(null);
                                handleSetLibraryFontSelected(
                                  font2
                                );
                              }
                            }
                          )
                        },
                        font2.slug
                      ))
                    }
                  )
                ] })
              ] }) }),
              /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_components114.Navigator.Screen, { path: "/fontFamily", children: [
                libraryFontSelected && /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                  ConfirmDeleteDialog,
                  {
                    font: libraryFontSelected,
                    isOpen: isConfirmDeleteOpen,
                    setIsOpen: setIsConfirmDeleteOpen,
                    setNotice,
                    uninstallFontFamily,
                    handleSetLibraryFontSelected
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_components114.Flex, { justify: "flex-start", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                    import_components114.Navigator.BackButton,
                    {
                      icon: (0, import_i18n157.isRTL)() ? chevron_right_default : chevron_left_default,
                      size: "small",
                      onClick: () => {
                        setLastSelectedFontSlug(
                          libraryFontSelected?.slug
                        );
                        handleSetLibraryFontSelected(
                          void 0
                        );
                        setNotice(null);
                      },
                      label: (0, import_i18n157.__)("Back")
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                    import_components114.__experimentalHeading,
                    {
                      level: 2,
                      size: 13,
                      className: "global-styles-ui-header",
                      children: libraryFontSelected?.name
                    }
                  )
                ] }),
                notice && /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_jsx_runtime312.Fragment, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components114.__experimentalSpacer, { margin: 1 }),
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                    import_components114.Notice,
                    {
                      status: notice.type,
                      onRemove: () => setNotice(null),
                      children: notice.message
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components114.__experimentalSpacer, { margin: 1 })
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components114.__experimentalSpacer, { margin: 4 }),
                /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components114.__experimentalText, { children: (0, import_i18n157.__)(
                  "Choose font variants. Keep in mind that too many variants could make your site slower."
                ) }),
                /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components114.__experimentalSpacer, { margin: 4 }),
                /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_components114.__experimentalVStack, { spacing: 0, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                    import_components114.CheckboxControl,
                    {
                      className: "font-library__select-all",
                      label: (0, import_i18n157.__)("Select all"),
                      checked: isSelectAllChecked,
                      onChange: toggleSelectAll,
                      indeterminate: isIndeterminate
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components114.__experimentalSpacer, { margin: 8 }),
                  /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                    "ul",
                    {
                      role: "list",
                      className: "font-library__fonts-list",
                      children: libraryFontSelected && getFontFacesToDisplay(
                        libraryFontSelected
                      ).map((face, i3) => /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                        "li",
                        {
                          className: "font-library__fonts-list-item",
                          children: /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
                            library_font_variant_default,
                            {
                              font: libraryFontSelected,
                              face
                            },
                            `face${i3}`
                          )
                        },
                        `face${i3}`
                      ))
                    }
                  )
                ] })
              ] })
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime312.jsxs)(import_components114.__experimentalHStack, { justify: "flex-end", className: "font-library__footer", children: [
          isInstalling && /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(import_components114.ProgressBar, {}),
          shouldDisplayDeleteButton && /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
            import_components114.Button,
            {
              __next40pxDefaultSize: true,
              isDestructive: true,
              variant: "tertiary",
              onClick: handleUninstallClick,
              children: (0, import_i18n157.__)("Delete")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
            import_components114.Button,
            {
              __next40pxDefaultSize: true,
              variant: "primary",
              onClick: handleUpdate,
              disabled: !fontFamiliesHasChanges,
              accessibleWhenDisabled: true,
              children: (0, import_i18n157.__)("Update")
            }
          )
        ] })
      ] })
    ] });
  }
  function ConfirmDeleteDialog({
    font: font2,
    isOpen: isOpen2,
    setIsOpen,
    setNotice,
    uninstallFontFamily,
    handleSetLibraryFontSelected
  }) {
    const navigator2 = (0, import_components114.useNavigator)();
    const handleConfirmUninstall = async () => {
      setNotice(null);
      setIsOpen(false);
      try {
        await uninstallFontFamily(font2);
        navigator2.goBack();
        handleSetLibraryFontSelected(void 0);
        setNotice({
          type: "success",
          message: (0, import_i18n157.__)("Font family uninstalled successfully.")
        });
      } catch (error2) {
        setNotice({
          type: "error",
          message: (0, import_i18n157.__)("There was an error uninstalling the font family.") + error2.message
        });
      }
    };
    const handleCancelUninstall = () => {
      setIsOpen(false);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime312.jsx)(
      import_components114.__experimentalConfirmDialog,
      {
        isOpen: isOpen2,
        cancelButtonText: (0, import_i18n157.__)("Cancel"),
        confirmButtonText: (0, import_i18n157.__)("Delete"),
        onCancel: handleCancelUninstall,
        onConfirm: handleConfirmUninstall,
        size: "medium",
        children: font2 && (0, import_i18n157.sprintf)(
          /* translators: %s: Name of the font. */
          (0, import_i18n157.__)(
            'Are you sure you want to delete "%s" font and all its variants and assets?'
          ),
          font2.name
        )
      }
    );
  }
  var installed_fonts_default = InstalledFonts;

  // packages/global-styles-ui/build-module/font-library/font-collection.mjs
  var import_element181 = __toESM(require_element(), 1);
  var import_components117 = __toESM(require_components(), 1);
  var import_compose29 = __toESM(require_compose(), 1);
  var import_i18n159 = __toESM(require_i18n(), 1);
  var import_core_data38 = __toESM(require_core_data(), 1);

  // packages/global-styles-ui/build-module/font-library/utils/filter-fonts.mjs
  function filterFonts(fonts, filters) {
    const { category, search } = filters;
    let filteredFonts = fonts || [];
    if (category && category !== "all") {
      filteredFonts = filteredFonts.filter(
        (font2) => font2.categories && font2.categories.indexOf(category) !== -1
      );
    }
    if (search) {
      filteredFonts = filteredFonts.filter(
        (font2) => font2.font_family_settings && font2.font_family_settings.name.toLowerCase().includes(search.toLowerCase())
      );
    }
    return filteredFonts;
  }

  // packages/global-styles-ui/build-module/font-library/utils/fonts-outline.mjs
  function getFontsOutline(fonts) {
    return fonts.reduce(
      (acc, font2) => ({
        ...acc,
        [font2.slug]: (font2?.fontFace || []).reduce(
          (faces, face) => ({
            ...faces,
            [`${face.fontStyle}-${face.fontWeight}`]: true
          }),
          {}
        )
      }),
      {}
    );
  }
  function isFontFontFaceInOutline(slug, face, outline) {
    if (!face) {
      return !!outline[slug];
    }
    return !!outline[slug]?.[`${face.fontStyle}-${face.fontWeight}`];
  }

  // packages/global-styles-ui/build-module/font-library/google-fonts-confirm-dialog.mjs
  var import_i18n158 = __toESM(require_i18n(), 1);
  var import_components115 = __toESM(require_components(), 1);
  var import_jsx_runtime313 = __toESM(require_jsx_runtime(), 1);
  function GoogleFontsConfirmDialog() {
    const handleConfirm = () => {
      window.localStorage.setItem(
        "wp-font-library-google-fonts-permission",
        "true"
      );
      window.dispatchEvent(new Event("storage"));
    };
    return /* @__PURE__ */ (0, import_jsx_runtime313.jsx)("div", { className: "font-library__google-fonts-confirm", children: /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(import_components115.Card, { children: /* @__PURE__ */ (0, import_jsx_runtime313.jsxs)(import_components115.CardBody, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(import_components115.__experimentalHeading, { level: 2, children: (0, import_i18n158.__)("Connect to Google Fonts") }),
      /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(import_components115.__experimentalSpacer, { margin: 6 }),
      /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(import_components115.__experimentalText, { as: "p", children: (0, import_i18n158.__)(
        "To install fonts from Google you must give permission to connect directly to Google servers. The fonts you install will be downloaded from Google and stored on your site. Your site will then use these locally-hosted fonts."
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(import_components115.__experimentalSpacer, { margin: 3 }),
      /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(import_components115.__experimentalText, { as: "p", children: (0, import_i18n158.__)(
        "You can alternatively upload files directly on the Upload tab."
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(import_components115.__experimentalSpacer, { margin: 6 }),
      /* @__PURE__ */ (0, import_jsx_runtime313.jsx)(
        import_components115.Button,
        {
          __next40pxDefaultSize: true,
          variant: "primary",
          onClick: handleConfirm,
          children: (0, import_i18n158.__)("Allow access to Google Fonts")
        }
      )
    ] }) }) });
  }
  var google_fonts_confirm_dialog_default = GoogleFontsConfirmDialog;

  // packages/global-styles-ui/build-module/font-library/collection-font-variant.mjs
  var import_element180 = __toESM(require_element(), 1);
  var import_components116 = __toESM(require_components(), 1);
  var import_jsx_runtime314 = __toESM(require_jsx_runtime(), 1);
  function CollectionFontVariant({
    face,
    font: font2,
    handleToggleVariant,
    selected
  }) {
    const handleToggleActivation = () => {
      if (font2?.fontFace) {
        handleToggleVariant(font2, face);
        return;
      }
      handleToggleVariant(font2);
    };
    const displayName = font2.name + " " + getFontFaceVariantName(face);
    const checkboxId = (0, import_element180.useId)();
    return /* @__PURE__ */ (0, import_jsx_runtime314.jsx)("div", { className: "font-library__font-card", children: /* @__PURE__ */ (0, import_jsx_runtime314.jsxs)(import_components116.Flex, { justify: "flex-start", align: "center", gap: "1rem", children: [
      /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
        import_components116.CheckboxControl,
        {
          checked: selected,
          onChange: handleToggleActivation,
          id: checkboxId
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime314.jsx)("label", { htmlFor: checkboxId, children: /* @__PURE__ */ (0, import_jsx_runtime314.jsx)(
        font_demo_default,
        {
          font: face,
          text: displayName,
          onClick: handleToggleActivation
        }
      ) })
    ] }) });
  }
  var collection_font_variant_default = CollectionFontVariant;

  // packages/global-styles-ui/build-module/font-library/font-collection.mjs
  var import_jsx_runtime315 = __toESM(require_jsx_runtime(), 1);
  var DEFAULT_CATEGORY = {
    slug: "all",
    name: (0, import_i18n159._x)("All", "font categories")
  };
  var LOCAL_STORAGE_ITEM = "wp-font-library-google-fonts-permission";
  var MIN_WINDOW_HEIGHT = 500;
  function FontCollection({ slug }) {
    const requiresPermission = slug === "google-fonts";
    const getGoogleFontsPermissionFromStorage = () => {
      return window.localStorage.getItem(LOCAL_STORAGE_ITEM) === "true";
    };
    const [selectedFont, setSelectedFont] = (0, import_element181.useState)(
      null
    );
    const [lastSelectedFontSlug, setLastSelectedFontSlug] = (0, import_element181.useState)(void 0);
    const [notice, setNotice] = (0, import_element181.useState)(null);
    const [fontsToInstall, setFontsToInstall] = (0, import_element181.useState)(
      []
    );
    const [page, setPage] = (0, import_element181.useState)(1);
    const [filters, setFilters] = (0, import_element181.useState)({});
    const [renderConfirmDialog, setRenderConfirmDialog] = (0, import_element181.useState)(
      requiresPermission && !getGoogleFontsPermissionFromStorage()
    );
    const { installFonts, isInstalling } = (0, import_element181.useContext)(FontLibraryContext);
    const { record: selectedCollection, isResolving: isLoading } = (0, import_core_data38.useEntityRecord)("root", "fontCollection", slug);
    (0, import_element181.useEffect)(() => {
      const handleStorage = () => {
        setRenderConfirmDialog(
          requiresPermission && !getGoogleFontsPermissionFromStorage()
        );
      };
      handleStorage();
      window.addEventListener("storage", handleStorage);
      return () => window.removeEventListener("storage", handleStorage);
    }, [slug, requiresPermission]);
    const revokeAccess = () => {
      window.localStorage.setItem(LOCAL_STORAGE_ITEM, "false");
      window.dispatchEvent(new Event("storage"));
    };
    (0, import_element181.useEffect)(() => {
      setSelectedFont(null);
    }, [slug]);
    (0, import_element181.useEffect)(() => {
      setFontsToInstall([]);
    }, [selectedFont]);
    const collectionFonts = (0, import_element181.useMemo)(
      () => selectedCollection?.font_families ?? [],
      [selectedCollection]
    );
    const collectionCategories = selectedCollection?.categories ?? [];
    const categories = [DEFAULT_CATEGORY, ...collectionCategories];
    const fonts = (0, import_element181.useMemo)(
      () => filterFonts(collectionFonts, filters),
      [collectionFonts, filters]
    );
    const windowHeight = Math.max(window.innerHeight, MIN_WINDOW_HEIGHT);
    const pageSize = Math.floor((windowHeight - 417) / 61);
    const totalPages = Math.ceil(fonts.length / pageSize);
    const itemsStart = (page - 1) * pageSize;
    const itemsLimit = page * pageSize;
    const items = fonts.slice(itemsStart, itemsLimit);
    const handleCategoryFilter = (category) => {
      setFilters({ ...filters, category });
      setPage(1);
    };
    const handleUpdateSearchInput = (value) => {
      setFilters({ ...filters, search: value });
      setPage(1);
    };
    const debouncedUpdateSearchInput = (0, import_compose29.debounce)(handleUpdateSearchInput, 300);
    const handleToggleVariant = (font2, face) => {
      const newFontsToInstall = toggleFont(font2, face, fontsToInstall);
      setFontsToInstall(newFontsToInstall);
    };
    const fontToInstallOutline = getFontsOutline(fontsToInstall);
    const resetFontsToInstall = () => {
      setFontsToInstall([]);
    };
    const selectFontCount = fontsToInstall.length > 0 ? fontsToInstall[0]?.fontFace?.length ?? 0 : 0;
    const isIndeterminate = selectFontCount > 0 && selectFontCount !== selectedFont?.fontFace?.length;
    const isSelectAllChecked = selectFontCount === selectedFont?.fontFace?.length;
    const toggleSelectAll = () => {
      const newFonts = [];
      if (!isSelectAllChecked && selectedFont) {
        newFonts.push(selectedFont);
      }
      setFontsToInstall(newFonts);
    };
    const handleInstall = async () => {
      setNotice(null);
      const fontFamily = fontsToInstall[0];
      try {
        if (fontFamily?.fontFace) {
          await Promise.all(
            fontFamily.fontFace.map(async (fontFace) => {
              if (fontFace.src) {
                fontFace.file = await downloadFontFaceAssets(
                  fontFace.src
                );
              }
            })
          );
        }
      } catch {
        setNotice({
          type: "error",
          message: (0, import_i18n159.__)(
            "Error installing the fonts, could not be downloaded."
          )
        });
        return;
      }
      try {
        await installFonts([fontFamily]);
        setNotice({
          type: "success",
          message: (0, import_i18n159.__)("Fonts were installed successfully.")
        });
      } catch (error2) {
        setNotice({
          type: "error",
          message: error2.message
        });
      }
      resetFontsToInstall();
    };
    const getSortedFontFaces = (fontFamily) => {
      if (!fontFamily) {
        return [];
      }
      if (!fontFamily.fontFace || !fontFamily.fontFace.length) {
        return [
          {
            fontFamily: fontFamily.fontFamily,
            fontStyle: "normal",
            fontWeight: "400"
          }
        ];
      }
      return sortFontFaces(fontFamily.fontFace);
    };
    if (renderConfirmDialog) {
      return /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(google_fonts_confirm_dialog_default, {});
    }
    const showActions = slug === "google-fonts" && !renderConfirmDialog && !selectedFont;
    return /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)("div", { className: "font-library__tabpanel-layout", children: [
      isLoading && /* @__PURE__ */ (0, import_jsx_runtime315.jsx)("div", { className: "font-library__loading", children: /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.ProgressBar, {}) }),
      !isLoading && selectedCollection && /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(import_jsx_runtime315.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(
          import_components117.Navigator,
          {
            initialPath: "/",
            className: "font-library__tabpanel-layout",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(import_components117.Navigator.Screen, { path: "/", children: [
                /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(import_components117.__experimentalHStack, { justify: "space-between", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(import_components117.__experimentalVStack, { children: [
                    /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalHeading, { level: 2, size: 13, children: selectedCollection.name }),
                    /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalText, { children: selectedCollection.description })
                  ] }),
                  showActions && /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                    import_components117.DropdownMenu,
                    {
                      icon: more_vertical_default,
                      label: (0, import_i18n159.__)("Actions"),
                      popoverProps: {
                        position: "bottom left"
                      },
                      controls: [
                        {
                          title: (0, import_i18n159.__)(
                            "Revoke access to Google Fonts"
                          ),
                          onClick: revokeAccess
                        }
                      ]
                    }
                  )
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalSpacer, { margin: 4 }),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(import_components117.__experimentalHStack, { spacing: 4, justify: "space-between", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                    import_components117.SearchControl,
                    {
                      value: filters.search,
                      placeholder: (0, import_i18n159.__)("Font name\u2026"),
                      label: (0, import_i18n159.__)("Search"),
                      onChange: debouncedUpdateSearchInput,
                      hideLabelFromVision: false
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                    import_components117.SelectControl,
                    {
                      label: (0, import_i18n159.__)("Category"),
                      value: filters.category,
                      onChange: handleCategoryFilter,
                      children: categories && categories.map((category) => /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                        "option",
                        {
                          value: category.slug,
                          children: category.name
                        },
                        category.slug
                      ))
                    }
                  )
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalSpacer, { margin: 4 }),
                !!selectedCollection?.font_families?.length && !fonts.length && /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalText, { children: (0, import_i18n159.__)(
                  "No fonts found. Try with a different search term."
                ) }),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)("div", { className: "font-library__fonts-grid__main", children: /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                  "ul",
                  {
                    role: "list",
                    className: "font-library__fonts-list",
                    children: items.map((font2) => /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                      "li",
                      {
                        className: "font-library__fonts-list-item",
                        children: /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                          font_card_default,
                          {
                            font: font2.font_family_settings,
                            navigatorPath: "/fontFamily",
                            shouldFocus: font2.font_family_settings.slug === lastSelectedFontSlug,
                            onClick: () => {
                              setSelectedFont(
                                font2.font_family_settings
                              );
                            }
                          }
                        )
                      },
                      font2.font_family_settings.slug
                    ))
                  }
                ) })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(import_components117.Navigator.Screen, { path: "/fontFamily", children: [
                /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(import_components117.Flex, { justify: "flex-start", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                    import_components117.Navigator.BackButton,
                    {
                      icon: (0, import_i18n159.isRTL)() ? chevron_right_default : chevron_left_default,
                      size: "small",
                      onClick: () => {
                        setLastSelectedFontSlug(
                          selectedFont?.slug
                        );
                        setSelectedFont(null);
                        setNotice(null);
                      },
                      label: (0, import_i18n159.__)("Back")
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                    import_components117.__experimentalHeading,
                    {
                      level: 2,
                      size: 13,
                      className: "global-styles-ui-header",
                      children: selectedFont?.name
                    }
                  )
                ] }),
                notice && /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(import_jsx_runtime315.Fragment, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalSpacer, { margin: 1 }),
                  /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                    import_components117.Notice,
                    {
                      status: notice.type,
                      onRemove: () => setNotice(null),
                      children: notice.message
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalSpacer, { margin: 1 })
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalSpacer, { margin: 4 }),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalText, { children: (0, import_i18n159.__)("Select font variants to install.") }),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalSpacer, { margin: 4 }),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                  import_components117.CheckboxControl,
                  {
                    className: "font-library__select-all",
                    label: (0, import_i18n159.__)("Select all"),
                    checked: isSelectAllChecked,
                    onChange: toggleSelectAll,
                    indeterminate: isIndeterminate
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalVStack, { spacing: 0, children: /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                  "ul",
                  {
                    role: "list",
                    className: "font-library__fonts-list",
                    children: selectedFont && getSortedFontFaces(selectedFont).map(
                      (face, i3) => /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                        "li",
                        {
                          className: "font-library__fonts-list-item",
                          children: /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                            collection_font_variant_default,
                            {
                              font: selectedFont,
                              face,
                              handleToggleVariant,
                              selected: isFontFontFaceInOutline(
                                selectedFont.slug,
                                selectedFont.fontFace ? face : null,
                                // If the font has no fontFace, we want to check if the font is in the outline
                                fontToInstallOutline
                              )
                            }
                          )
                        },
                        `face${i3}`
                      )
                    )
                  }
                ) }),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(import_components117.__experimentalSpacer, { margin: 16 })
              ] })
            ]
          }
        ),
        selectedFont && /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
          import_components117.Flex,
          {
            justify: "flex-end",
            className: "font-library__footer",
            children: /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
              import_components117.Button,
              {
                __next40pxDefaultSize: true,
                variant: "primary",
                onClick: handleInstall,
                isBusy: isInstalling,
                disabled: fontsToInstall.length === 0 || isInstalling,
                accessibleWhenDisabled: true,
                children: (0, import_i18n159.__)("Install")
              }
            )
          }
        ),
        !selectedFont && /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(
          import_components117.__experimentalHStack,
          {
            expanded: false,
            className: "font-library__footer",
            justify: "end",
            spacing: 6,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                import_components117.__experimentalHStack,
                {
                  justify: "flex-start",
                  expanded: false,
                  spacing: 1,
                  className: "font-library__page-selection",
                  children: (0, import_element181.createInterpolateElement)(
                    (0, import_i18n159.sprintf)(
                      // translators: 1: Current page number, 2: Total number of pages.
                      (0, import_i18n159._x)(
                        "<div>Page</div>%1$s<div>of %2$d</div>",
                        "paging"
                      ),
                      "<CurrentPage />",
                      totalPages
                    ),
                    {
                      div: /* @__PURE__ */ (0, import_jsx_runtime315.jsx)("div", { "aria-hidden": true }),
                      // @ts-expect-error — Tag injected via sprintf argument, not visible in format string.
                      CurrentPage: /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                        import_components117.SelectControl,
                        {
                          "aria-label": (0, import_i18n159.__)(
                            "Current page"
                          ),
                          value: page.toString(),
                          options: [
                            ...Array(totalPages)
                          ].map((e3, i3) => {
                            return {
                              label: (i3 + 1).toString(),
                              value: (i3 + 1).toString()
                            };
                          }),
                          onChange: (newPage) => setPage(
                            parseInt(newPage)
                          ),
                          size: "small",
                          variant: "minimal"
                        }
                      )
                    }
                  )
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime315.jsxs)(import_components117.__experimentalHStack, { expanded: false, spacing: 1, children: [
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                  import_components117.Button,
                  {
                    onClick: () => setPage(page - 1),
                    disabled: page === 1,
                    accessibleWhenDisabled: true,
                    label: (0, import_i18n159.__)("Previous page"),
                    icon: (0, import_i18n159.isRTL)() ? next_default : previous_default,
                    showTooltip: true,
                    size: "compact",
                    tooltipPosition: "top"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime315.jsx)(
                  import_components117.Button,
                  {
                    onClick: () => setPage(page + 1),
                    disabled: page === totalPages,
                    accessibleWhenDisabled: true,
                    label: (0, import_i18n159.__)("Next page"),
                    icon: (0, import_i18n159.isRTL)() ? previous_default : next_default,
                    showTooltip: true,
                    size: "compact",
                    tooltipPosition: "top"
                  }
                )
              ] })
            ]
          }
        )
      ] })
    ] });
  }
  var font_collection_default = FontCollection;

  // packages/global-styles-ui/build-module/font-library/upload-fonts.mjs
  var import_i18n160 = __toESM(require_i18n(), 1);
  var import_components119 = __toESM(require_components(), 1);
  var import_element182 = __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: (a3, b3) => (typeof __require !== "undefined" ? __require : a3)[b3]
  }) : 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 define2, module, exports;
    return (/* @__PURE__ */ (function() {
      function r4(e3, n3, t4) {
        function o4(i22, f3) {
          if (!n3[i22]) {
            if (!e3[i22]) {
              var c6 = "function" == typeof __require2 && __require2;
              if (!f3 && c6) return c6(i22, true);
              if (u3) return u3(i22, true);
              var a3 = new Error("Cannot find module '" + i22 + "'");
              throw a3.code = "MODULE_NOT_FOUND", a3;
            }
            var p4 = n3[i22] = { exports: {} };
            e3[i22][0].call(
              p4.exports,
              function(r22) {
                var n22 = e3[i22][1][r22];
                return o4(n22 || r22);
              },
              p4,
              p4.exports,
              r4,
              e3,
              n3,
              t4
            );
          }
          return n3[i22].exports;
        }
        for (var u3 = "function" == typeof __require2 && __require2, i3 = 0; i3 < t4.length; i3++)
          o4(t4[i3]);
        return o4;
      }
      return r4;
    })())(
      {
        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 i3 = 0; i3 < 4; i3++) {
                this.val_ |= this.buf_[this.pos_] << 8 * i3;
                ++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 p4 = 0; p4 < 32; p4++)
                    this.buf_[dst + bytes_read + p4] = 0;
                }
                if (dst === 0) {
                  for (var p4 = 0; p4 < 32; p4++)
                    this.buf_[(BROTLI_READ_SIZE << 1) + p4] = this.buf_[p4];
                  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 n3;
              if (br.readBits(1) === 0) {
                return 16;
              }
              n3 = br.readBits(3);
              if (n3 > 0) {
                return 17 + n3;
              }
              n3 = br.readBits(3);
              if (n3 > 0) {
                return 8 + n3;
              }
              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 i3;
              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 (i3 = 0; i3 < size_bytes; i3++) {
                  var next_byte = br.readBits(8);
                  if (i3 + 1 === size_bytes && size_bytes > 1 && next_byte === 0)
                    throw new Error("Invalid size byte");
                  out.meta_block_length |= next_byte << i3 * 8;
                }
              } else {
                for (i3 = 0; i3 < size_nibbles; ++i3) {
                  var next_nibble = br.readBits(4);
                  if (i3 + 1 === size_nibbles && size_nibbles > 4 && next_nibble === 0)
                    throw new Error("Invalid size nibble");
                  out.meta_block_length |= next_nibble << i3 * 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 i3 = 0; i3 < 32; i3++)
                table.push(new HuffmanCode(0, 0));
              BrotliBuildHuffmanTable(
                table,
                0,
                5,
                code_length_code_lengths,
                CODE_LENGTH_CODES
              );
              while (symbol3 < num_symbols && space > 0) {
                var p4 = 0;
                var code_len;
                br.readMoreInput();
                br.fillBitWindow();
                p4 += br.val_ >>> br.bit_pos_ & 31;
                br.bit_pos_ += table[p4].bits;
                code_len = table[p4].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 i3;
                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 (i3 = 0; i3 < num_symbols; ++i3) {
                  symbols[i3] = br.readBits(max_bits) % alphabet_size;
                  code_lengths[symbols[i3]] = 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 i3;
                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 (i3 = simple_code_or_skip; i3 < CODE_LENGTH_CODES && space > 0; ++i3) {
                  var code_len_idx = kCodeLengthCodeOrder[i3];
                  var p4 = 0;
                  var v3;
                  br.fillBitWindow();
                  p4 += br.val_ >>> br.bit_pos_ & 15;
                  br.bit_pos_ += huff[p4].bits;
                  v3 = huff[p4].value;
                  code_length_code_lengths[code_len_idx] = v3;
                  if (v3 !== 0) {
                    space -= 32 >> v3;
                    ++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(v3, index2) {
              var value = v3[index2];
              var i3 = index2;
              for (; i3; --i3) v3[i3] = v3[i3 - 1];
              v3[0] = value;
            }
            function InverseMoveToFrontTransform(v3, v_len) {
              var mtf = new Uint8Array(256);
              var i3;
              for (i3 = 0; i3 < 256; ++i3) {
                mtf[i3] = i3;
              }
              for (i3 = 0; i3 < v_len; ++i3) {
                var index2 = v3[i3];
                v3[i3] = 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 i3;
              var table_size;
              var next = 0;
              for (i3 = 0; i3 < this.num_htrees; ++i3) {
                this.htrees[i3] = 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 i3;
              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 (i3 = 0; i3 < HUFFMAN_MAX_TABLE_SIZE; i3++) {
                table[i3] = new HuffmanCode(0, 0);
              }
              ReadHuffmanCode(
                num_htrees + max_run_length_prefix,
                table,
                0,
                br
              );
              for (i3 = 0; i3 < context_map_size; ) {
                var code;
                br.readMoreInput();
                code = ReadSymbol(table, 0, br);
                if (code === 0) {
                  context_map[i3] = 0;
                  ++i3;
                } else if (code <= max_run_length_prefix) {
                  var reps = 1 + (1 << code) + br.readBits(code);
                  while (--reps) {
                    if (i3 >= context_map_size) {
                      throw new Error(
                        "[DecodeContextMap] i >= context_map_size"
                      );
                    }
                    context_map[i3] = 0;
                    ++i3;
                  }
                } else {
                  context_map[i3] = code - max_run_length_prefix;
                  ++i3;
                }
              }
              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, len2, 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 (len2 < 8 || br.bit_pos_ + (len2 << 3) < br.bit_end_pos_) {
                while (len2-- > 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;
                --len2;
              }
              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;
                len2 -= tail;
                br_pos = 0;
              }
              for (var x2 = 0; x2 < nbytes; x2++)
                ringbuffer[rb_pos + x2] = br.buf_[br_pos + x2];
              rb_pos += nbytes;
              len2 -= 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 + len2 >= 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);
                len2 -= nbytes;
                rb_pos = 0;
              }
              if (br.input_.read(ringbuffer, rb_pos, len2) < len2) {
                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 i3;
              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 (i3 = 0; i3 < 3; ++i3) {
                  hgroup[i3].codes = null;
                  hgroup[i3].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 (i3 = 0; i3 < 3; ++i3) {
                  num_block_types[i3] = DecodeVarLenUint8(br) + 1;
                  if (num_block_types[i3] >= 2) {
                    ReadHuffmanCode(
                      num_block_types[i3] + 2,
                      block_type_trees,
                      i3 * HUFFMAN_MAX_TABLE_SIZE,
                      br
                    );
                    ReadHuffmanCode(
                      kNumBlockLengthCodes,
                      block_len_trees,
                      i3 * HUFFMAN_MAX_TABLE_SIZE,
                      br
                    );
                    block_length[i3] = ReadBlockLength(
                      block_len_trees,
                      i3 * HUFFMAN_MAX_TABLE_SIZE,
                      br
                    );
                    block_type_rb_index[i3] = 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 (i3 = 0; i3 < num_block_types[0]; ++i3) {
                  br.readMoreInput();
                  context_modes[i3] = 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 (i3 = 0; i3 < 3; ++i3) {
                  hgroup[i3].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 distance2;
                  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;
                    }
                  }
                  distance2 = TranslateShortCodes(
                    distance_code,
                    dist_rb,
                    dist_rb_idx
                  );
                  if (distance2 < 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 (distance2 > max_distance) {
                    if (copy_length >= BrotliDictionary.minDictionaryWordLength && copy_length <= BrotliDictionary.maxDictionaryWordLength) {
                      var offset4 = BrotliDictionary.offsetsByLength[copy_length];
                      var word_id = distance2 - 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 len2 = Transform.transformDictionaryWord(
                          ringbuffer,
                          copy_dst,
                          offset4,
                          copy_length,
                          transform_idx
                        );
                        copy_dst += len2;
                        pos += len2;
                        meta_block_remaining_len -= len2;
                        if (copy_dst >= ringbuffer_end) {
                          output.write(
                            ringbuffer,
                            ringbuffer_size
                          );
                          for (var _x50 = 0; _x50 < copy_dst - ringbuffer_end; _x50++)
                            ringbuffer[_x50] = ringbuffer[ringbuffer_end + _x50];
                        }
                      } else {
                        throw new Error(
                          "Invalid backward reference. pos: " + pos + " distance: " + distance2 + " len: " + copy_length + " bytes left: " + meta_block_remaining_len
                        );
                      }
                    } else {
                      throw new Error(
                        "Invalid backward reference. pos: " + pos + " distance: " + distance2 + " len: " + copy_length + " bytes left: " + meta_block_remaining_len
                      );
                    }
                  } else {
                    if (distance_code > 0) {
                      dist_rb[dist_rb_idx & 3] = distance2;
                      ++dist_rb_idx;
                    }
                    if (copy_length > meta_block_remaining_len) {
                      throw new Error(
                        "Invalid backward reference. pos: " + pos + " distance: " + distance2 + " len: " + copy_length + " bytes left: " + meta_block_remaining_len
                      );
                    }
                    for (j2 = 0; j2 < copy_length; ++j2) {
                      ringbuffer[pos & ringbuffer_mask] = ringbuffer[pos - distance2 & 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, len2) {
              var step = 1 << len2 - 1;
              while (key & step) {
                step >>= 1;
              }
              return (key & step - 1) + step;
            }
            function ReplicateValue(table, i3, step, end, code) {
              do {
                end -= step;
                table[i3 + end] = new HuffmanCode(
                  code.bits,
                  code.value
                );
              } while (end > 0);
            }
            function NextTableBitSize(count, len2, root_bits) {
              var left = 1 << len2 - root_bits;
              while (len2 < MAX_LENGTH) {
                left -= count[len2];
                if (left <= 0) break;
                ++len2;
                left <<= 1;
              }
              return len2 - root_bits;
            }
            exports2.BrotliBuildHuffmanTable = function(root_table, table, root_bits, code_lengths, code_lengths_size) {
              var start_table = table;
              var code;
              var len2;
              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 (len2 = 1; len2 < MAX_LENGTH; len2++) {
                offset4[len2 + 1] = offset4[len2] + count[len2];
              }
              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 (len2 = 1, step = 2; len2 <= root_bits; ++len2, step <<= 1) {
                for (; count[len2] > 0; --count[len2]) {
                  code = new HuffmanCode(
                    len2 & 255,
                    sorted[symbol3++] & 65535
                  );
                  ReplicateValue(
                    root_table,
                    table + key,
                    step,
                    table_size,
                    code
                  );
                  key = GetNextKey(key, len2);
                }
              }
              mask = total_size - 1;
              low = -1;
              for (len2 = root_bits + 1, step = 2; len2 <= MAX_LENGTH; ++len2, step <<= 1) {
                for (; count[len2] > 0; --count[len2]) {
                  if ((key & mask) !== low) {
                    table += table_size;
                    table_bits = NextTableBitSize(
                      count,
                      len2,
                      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(
                    len2 - root_bits & 255,
                    sorted[symbol3++] & 65535
                  );
                  ReplicateValue(
                    root_table,
                    table + (key >> root_bits),
                    step,
                    table_size,
                    code
                  );
                  key = GetNextKey(key, len2);
                }
              }
              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 i3 = 0, len2 = code.length; i3 < len2; ++i3) {
              lookup[i3] = code[i3];
              revLookup[code.charCodeAt(i3)] = i3;
            }
            revLookup["-".charCodeAt(0)] = 62;
            revLookup["_".charCodeAt(0)] = 63;
            function getLens(b64) {
              var len22 = b64.length;
              if (len22 % 4 > 0) {
                throw new Error(
                  "Invalid string. Length must be a multiple of 4"
                );
              }
              var validLen = b64.indexOf("=");
              if (validLen === -1) validLen = len22;
              var placeHoldersLen = validLen === len22 ? 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 len22 = placeHoldersLen > 0 ? validLen - 4 : validLen;
              for (var i22 = 0; i22 < len22; 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 len22 = uint8.length;
              var extraBytes = len22 % 3;
              var parts = [];
              var maxChunkLength = 16383;
              for (var i22 = 0, len222 = len22 - extraBytes; i22 < len222; i22 += maxChunkLength) {
                parts.push(
                  encodeChunk(
                    uint8,
                    i22,
                    i22 + maxChunkLength > len222 ? len222 : i22 + maxChunkLength
                  )
                );
              }
              if (extraBytes === 1) {
                tmp = uint8[len22 - 1];
                parts.push(
                  lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
                );
              } else if (extraBytes === 2) {
                tmp = (uint8[len22 - 2] << 8) + uint8[len22 - 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, i3, count) {
              if (this.pos + count > this.buffer.length) {
                count = this.buffer.length - this.pos;
              }
              for (var p4 = 0; p4 < count; p4++)
                buf[i3 + p4] = this.buffer[this.pos + p4];
              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 i3 = 0; i3 < prefix2.length; i3++)
                this.prefix[i3] = prefix2.charCodeAt(i3);
              for (var i3 = 0; i3 < suffix.length; i3++)
                this.suffix[i3] = suffix.charCodeAt(i3);
            }
            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(p4, i3) {
              if (p4[i3] < 192) {
                if (p4[i3] >= 97 && p4[i3] <= 122) {
                  p4[i3] ^= 32;
                }
                return 1;
              }
              if (p4[i3] < 224) {
                p4[i3 + 1] ^= 32;
                return 2;
              }
              p4[i3 + 2] ^= 5;
              return 3;
            }
            exports2.transformDictionaryWord = function(dst, idx, word, len2, transform) {
              var prefix2 = kTransforms[transform].prefix;
              var suffix = kTransforms[transform].suffix;
              var t4 = kTransforms[transform].transform;
              var skip = t4 < kOmitFirst1 ? 0 : t4 - (kOmitFirst1 - 1);
              var i3 = 0;
              var start_idx = idx;
              var uppercase;
              if (skip > len2) {
                skip = len2;
              }
              var prefix_pos = 0;
              while (prefix_pos < prefix2.length) {
                dst[idx++] = prefix2[prefix_pos++];
              }
              word += skip;
              len2 -= skip;
              if (t4 <= kOmitLast9) {
                len2 -= t4;
              }
              for (i3 = 0; i3 < len2; i3++) {
                dst[idx++] = BrotliDictionary.dictionary[word + i3];
              }
              uppercase = idx - len2;
              if (t4 === kUppercaseFirst) {
                ToUpperCase(dst, uppercase);
              } else if (t4 === kUppercaseAll) {
                while (len2 > 0) {
                  var step = ToUpperCase(dst, uppercase);
                  uppercase += step;
                  len2 -= 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: (a3, b3) => (typeof __require !== "undefined" ? __require : a3)[b3]
  }) : 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 define2, module, exports;
    return (/* @__PURE__ */ (function() {
      function r4(e3, n3, t4) {
        function o4(i22, f3) {
          if (!n3[i22]) {
            if (!e3[i22]) {
              var c6 = "function" == typeof __require3 && __require3;
              if (!f3 && c6) return c6(i22, true);
              if (u3) return u3(i22, true);
              var a3 = new Error("Cannot find module '" + i22 + "'");
              throw a3.code = "MODULE_NOT_FOUND", a3;
            }
            var p4 = n3[i22] = { exports: {} };
            e3[i22][0].call(
              p4.exports,
              function(r22) {
                var n22 = e3[i22][1][r22];
                return o4(n22 || r22);
              },
              p4,
              p4.exports,
              r4,
              e3,
              n3,
              t4
            );
          }
          return n3[i22].exports;
        }
        for (var u3 = "function" == typeof __require3 && __require3, i3 = 0; i3 < t4.length; i3++)
          o4(t4[i3]);
        return o4;
      }
      return r4;
    })())(
      {
        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 p4 in source) {
                  if (_has(source, p4)) {
                    obj[p4] = source[p4];
                  }
                }
              }
              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, len2, dest_offs) {
                if (src.subarray && dest.subarray) {
                  dest.set(
                    src.subarray(src_offs, src_offs + len2),
                    dest_offs
                  );
                  return;
                }
                for (var i3 = 0; i3 < len2; i3++) {
                  dest[dest_offs + i3] = src[src_offs + i3];
                }
              },
              // Join array of chunks to single array.
              flattenChunks: function(chunks) {
                var i3, l3, len2, pos, chunk2, result;
                len2 = 0;
                for (i3 = 0, l3 = chunks.length; i3 < l3; i3++) {
                  len2 += chunks[i3].length;
                }
                result = new Uint8Array(len2);
                pos = 0;
                for (i3 = 0, l3 = chunks.length; i3 < l3; i3++) {
                  chunk2 = chunks[i3];
                  result.set(chunk2, pos);
                  pos += chunk2.length;
                }
                return result;
              }
            };
            var fnUntyped = {
              arraySet: function(dest, src, src_offs, len2, dest_offs) {
                for (var i3 = 0; i3 < len2; i3++) {
                  dest[dest_offs + i3] = src[src_offs + i3];
                }
              },
              // 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 (__337) {
              STR_APPLY_OK = false;
            }
            try {
              String.fromCharCode.apply(null, new Uint8Array(1));
            } catch (__337) {
              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(str3) {
              var buf, c6, c22, m_pos, i3, str_len = str3.length, buf_len = 0;
              for (m_pos = 0; m_pos < str_len; m_pos++) {
                c6 = str3.charCodeAt(m_pos);
                if ((c6 & 64512) === 55296 && m_pos + 1 < str_len) {
                  c22 = str3.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 (i3 = 0, m_pos = 0; i3 < buf_len; m_pos++) {
                c6 = str3.charCodeAt(m_pos);
                if ((c6 & 64512) === 55296 && m_pos + 1 < str_len) {
                  c22 = str3.charCodeAt(m_pos + 1);
                  if ((c22 & 64512) === 56320) {
                    c6 = 65536 + (c6 - 55296 << 10) + (c22 - 56320);
                    m_pos++;
                  }
                }
                if (c6 < 128) {
                  buf[i3++] = c6;
                } else if (c6 < 2048) {
                  buf[i3++] = 192 | c6 >>> 6;
                  buf[i3++] = 128 | c6 & 63;
                } else if (c6 < 65536) {
                  buf[i3++] = 224 | c6 >>> 12;
                  buf[i3++] = 128 | c6 >>> 6 & 63;
                  buf[i3++] = 128 | c6 & 63;
                } else {
                  buf[i3++] = 240 | c6 >>> 18;
                  buf[i3++] = 128 | c6 >>> 12 & 63;
                  buf[i3++] = 128 | c6 >>> 6 & 63;
                  buf[i3++] = 128 | c6 & 63;
                }
              }
              return buf;
            };
            function buf2binstring(buf, len2) {
              if (len2 < 65534) {
                if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {
                  return String.fromCharCode.apply(
                    null,
                    utils.shrinkBuf(buf, len2)
                  );
                }
              }
              var result = "";
              for (var i3 = 0; i3 < len2; i3++) {
                result += String.fromCharCode(buf[i3]);
              }
              return result;
            }
            exports2.buf2binstring = function(buf) {
              return buf2binstring(buf, buf.length);
            };
            exports2.binstring2buf = function(str3) {
              var buf = new utils.Buf8(str3.length);
              for (var i3 = 0, len2 = buf.length; i3 < len2; i3++) {
                buf[i3] = str3.charCodeAt(i3);
              }
              return buf;
            };
            exports2.buf2string = function(buf, max3) {
              var i3, out, c6, c_len;
              var len2 = max3 || buf.length;
              var utf16buf = new Array(len2 * 2);
              for (out = 0, i3 = 0; i3 < len2; ) {
                c6 = buf[i3++];
                if (c6 < 128) {
                  utf16buf[out++] = c6;
                  continue;
                }
                c_len = _utf8len[c6];
                if (c_len > 4) {
                  utf16buf[out++] = 65533;
                  i3 += c_len - 1;
                  continue;
                }
                c6 &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7;
                while (c_len > 1 && i3 < len2) {
                  c6 = c6 << 6 | buf[i3++] & 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, max3) {
              var pos;
              max3 = max3 || buf.length;
              if (max3 > buf.length) {
                max3 = buf.length;
              }
              pos = max3 - 1;
              while (pos >= 0 && (buf[pos] & 192) === 128) {
                pos--;
              }
              if (pos < 0) {
                return max3;
              }
              if (pos === 0) {
                return max3;
              }
              return pos + _utf8len[buf[pos]] > max3 ? pos : max3;
            };
          },
          { "./common": 1 }
        ],
        3: [
          function(require2, module2, exports2) {
            "use strict";
            function adler32(adler, buf, len2, pos) {
              var s1 = adler & 65535 | 0, s22 = adler >>> 16 & 65535 | 0, n3 = 0;
              while (len2 !== 0) {
                n3 = len2 > 2e3 ? 2e3 : len2;
                len2 -= n3;
                do {
                  s1 = s1 + buf[pos++] | 0;
                  s22 = s22 + s1 | 0;
                } while (--n3);
                s1 %= 65521;
                s22 %= 65521;
              }
              return s1 | s22 << 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 n3 = 0; n3 < 256; n3++) {
                c6 = n3;
                for (var k2 = 0; k2 < 8; k2++) {
                  c6 = c6 & 1 ? 3988292384 ^ c6 >>> 1 : c6 >>> 1;
                }
                table[n3] = c6;
              }
              return table;
            }
            var crcTable = makeTable();
            function crc32(crc, buf, len2, pos) {
              var t4 = crcTable, end = pos + len2;
              crc ^= -1;
              for (var i3 = pos; i3 < end; i3++) {
                crc = crc >>> 8 ^ t4[(crc ^ buf[i3]) & 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 state2;
              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 len2;
              var dist2;
              var from;
              var from_source;
              var input, output;
              state2 = 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 = state2.dmax;
              wsize = state2.wsize;
              whave = state2.whave;
              wnext = state2.wnext;
              s_window = state2.window;
              hold = state2.hold;
              bits = state2.bits;
              lcode = state2.lencode;
              dcode = state2.distcode;
              lmask = (1 << state2.lenbits) - 1;
              dmask = (1 << state2.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) {
                    len2 = here & 65535;
                    op &= 15;
                    if (op) {
                      if (bits < op) {
                        hold += input[_in++] << bits;
                        bits += 8;
                      }
                      len2 += 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) {
                        dist2 = here & 65535;
                        op &= 15;
                        if (bits < op) {
                          hold += input[_in++] << bits;
                          bits += 8;
                          if (bits < op) {
                            hold += input[_in++] << bits;
                            bits += 8;
                          }
                        }
                        dist2 += hold & (1 << op) - 1;
                        if (dist2 > dmax) {
                          strm.msg = "invalid distance too far back";
                          state2.mode = BAD;
                          break top;
                        }
                        hold >>>= op;
                        bits -= op;
                        op = _out - beg;
                        if (dist2 > op) {
                          op = dist2 - op;
                          if (op > whave) {
                            if (state2.sane) {
                              strm.msg = "invalid distance too far back";
                              state2.mode = BAD;
                              break top;
                            }
                          }
                          from = 0;
                          from_source = s_window;
                          if (wnext === 0) {
                            from += wsize - op;
                            if (op < len2) {
                              len2 -= op;
                              do {
                                output[_out++] = s_window[from++];
                              } while (--op);
                              from = _out - dist2;
                              from_source = output;
                            }
                          } else if (wnext < op) {
                            from += wsize + wnext - op;
                            op -= wnext;
                            if (op < len2) {
                              len2 -= op;
                              do {
                                output[_out++] = s_window[from++];
                              } while (--op);
                              from = 0;
                              if (wnext < len2) {
                                op = wnext;
                                len2 -= op;
                                do {
                                  output[_out++] = s_window[from++];
                                } while (--op);
                                from = _out - dist2;
                                from_source = output;
                              }
                            }
                          } else {
                            from += wnext - op;
                            if (op < len2) {
                              len2 -= op;
                              do {
                                output[_out++] = s_window[from++];
                              } while (--op);
                              from = _out - dist2;
                              from_source = output;
                            }
                          }
                          while (len2 > 2) {
                            output[_out++] = from_source[from++];
                            output[_out++] = from_source[from++];
                            output[_out++] = from_source[from++];
                            len2 -= 3;
                          }
                          if (len2) {
                            output[_out++] = from_source[from++];
                            if (len2 > 1) {
                              output[_out++] = from_source[from++];
                            }
                          }
                        } else {
                          from = _out - dist2;
                          do {
                            output[_out++] = output[from++];
                            output[_out++] = output[from++];
                            output[_out++] = output[from++];
                            len2 -= 3;
                          } while (len2 > 2);
                          if (len2) {
                            output[_out++] = output[from++];
                            if (len2 > 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";
                        state2.mode = BAD;
                        break top;
                      }
                      break;
                    }
                  } else if ((op & 64) === 0) {
                    here = lcode[(here & 65535) + (hold & (1 << op) - 1)];
                    continue dolen;
                  } else if (op & 32) {
                    state2.mode = TYPE;
                    break top;
                  } else {
                    strm.msg = "invalid literal/length code";
                    state2.mode = BAD;
                    break top;
                  }
                  break;
                }
              } while (_in < last && _out < end);
              len2 = bits >> 3;
              _in -= len2;
              bits -= len2 << 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);
              state2.hold = hold;
              state2.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 state2;
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              state2 = strm.state;
              strm.total_in = strm.total_out = state2.total = 0;
              strm.msg = "";
              if (state2.wrap) {
                strm.adler = state2.wrap & 1;
              }
              state2.mode = HEAD;
              state2.last = 0;
              state2.havedict = 0;
              state2.dmax = 32768;
              state2.head = null;
              state2.hold = 0;
              state2.bits = 0;
              state2.lencode = state2.lendyn = new utils.Buf32(
                ENOUGH_LENS
              );
              state2.distcode = state2.distdyn = new utils.Buf32(
                ENOUGH_DISTS
              );
              state2.sane = 1;
              state2.back = -1;
              return Z_OK;
            }
            function inflateReset(strm) {
              var state2;
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              state2 = strm.state;
              state2.wsize = 0;
              state2.whave = 0;
              state2.wnext = 0;
              return inflateResetKeep(strm);
            }
            function inflateReset2(strm, windowBits) {
              var wrap;
              var state2;
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              state2 = 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 (state2.window !== null && state2.wbits !== windowBits) {
                state2.window = null;
              }
              state2.wrap = wrap;
              state2.wbits = windowBits;
              return inflateReset(strm);
            }
            function inflateInit2(strm, windowBits) {
              var ret;
              var state2;
              if (!strm) {
                return Z_STREAM_ERROR;
              }
              state2 = new InflateState();
              strm.state = state2;
              state2.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(state2) {
              if (virgin) {
                var sym;
                lenfix = new utils.Buf32(512);
                distfix = new utils.Buf32(32);
                sym = 0;
                while (sym < 144) {
                  state2.lens[sym++] = 8;
                }
                while (sym < 256) {
                  state2.lens[sym++] = 9;
                }
                while (sym < 280) {
                  state2.lens[sym++] = 7;
                }
                while (sym < 288) {
                  state2.lens[sym++] = 8;
                }
                inflate_table(
                  LENS,
                  state2.lens,
                  0,
                  288,
                  lenfix,
                  0,
                  state2.work,
                  { bits: 9 }
                );
                sym = 0;
                while (sym < 32) {
                  state2.lens[sym++] = 5;
                }
                inflate_table(
                  DISTS,
                  state2.lens,
                  0,
                  32,
                  distfix,
                  0,
                  state2.work,
                  { bits: 5 }
                );
                virgin = false;
              }
              state2.lencode = lenfix;
              state2.lenbits = 9;
              state2.distcode = distfix;
              state2.distbits = 5;
            }
            function updatewindow(strm, src, end, copy3) {
              var dist2;
              var state2 = strm.state;
              if (state2.window === null) {
                state2.wsize = 1 << state2.wbits;
                state2.wnext = 0;
                state2.whave = 0;
                state2.window = new utils.Buf8(state2.wsize);
              }
              if (copy3 >= state2.wsize) {
                utils.arraySet(
                  state2.window,
                  src,
                  end - state2.wsize,
                  state2.wsize,
                  0
                );
                state2.wnext = 0;
                state2.whave = state2.wsize;
              } else {
                dist2 = state2.wsize - state2.wnext;
                if (dist2 > copy3) {
                  dist2 = copy3;
                }
                utils.arraySet(
                  state2.window,
                  src,
                  end - copy3,
                  dist2,
                  state2.wnext
                );
                copy3 -= dist2;
                if (copy3) {
                  utils.arraySet(
                    state2.window,
                    src,
                    end - copy3,
                    copy3,
                    0
                  );
                  state2.wnext = copy3;
                  state2.whave = state2.wsize;
                } else {
                  state2.wnext += dist2;
                  if (state2.wnext === state2.wsize) {
                    state2.wnext = 0;
                  }
                  if (state2.whave < state2.wsize) {
                    state2.whave += dist2;
                  }
                }
              }
              return 0;
            }
            function inflate(strm, flush2) {
              var state2;
              var input, output;
              var next;
              var put;
              var have, left;
              var hold;
              var bits;
              var _in, _out;
              var copy3;
              var from;
              var from_source;
              var here = 0;
              var here_bits, here_op, here_val;
              var last_bits, last_op, last_val;
              var len2;
              var ret;
              var hbuf = new utils.Buf8(
                4
              );
              var opts;
              var n3;
              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;
              }
              state2 = strm.state;
              if (state2.mode === TYPE) {
                state2.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 = state2.hold;
              bits = state2.bits;
              _in = have;
              _out = left;
              ret = Z_OK;
              inf_leave: for (; ; ) {
                switch (state2.mode) {
                  case HEAD:
                    if (state2.wrap === 0) {
                      state2.mode = TYPEDO;
                      break;
                    }
                    while (bits < 16) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    if (state2.wrap & 2 && hold === 35615) {
                      state2.check = 0;
                      hbuf[0] = hold & 255;
                      hbuf[1] = hold >>> 8 & 255;
                      state2.check = crc32(
                        state2.check,
                        hbuf,
                        2,
                        0
                      );
                      hold = 0;
                      bits = 0;
                      state2.mode = FLAGS;
                      break;
                    }
                    state2.flags = 0;
                    if (state2.head) {
                      state2.head.done = false;
                    }
                    if (!(state2.wrap & 1) || (((hold & 255) << 8) + (hold >> 8)) % 31) {
                      strm.msg = "incorrect header check";
                      state2.mode = BAD;
                      break;
                    }
                    if ((hold & 15) !== Z_DEFLATED) {
                      strm.msg = "unknown compression method";
                      state2.mode = BAD;
                      break;
                    }
                    hold >>>= 4;
                    bits -= 4;
                    len2 = (hold & 15) + 8;
                    if (state2.wbits === 0) {
                      state2.wbits = len2;
                    } else if (len2 > state2.wbits) {
                      strm.msg = "invalid window size";
                      state2.mode = BAD;
                      break;
                    }
                    state2.dmax = 1 << len2;
                    strm.adler = state2.check = 1;
                    state2.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;
                    }
                    state2.flags = hold;
                    if ((state2.flags & 255) !== Z_DEFLATED) {
                      strm.msg = "unknown compression method";
                      state2.mode = BAD;
                      break;
                    }
                    if (state2.flags & 57344) {
                      strm.msg = "unknown header flags set";
                      state2.mode = BAD;
                      break;
                    }
                    if (state2.head) {
                      state2.head.text = hold >> 8 & 1;
                    }
                    if (state2.flags & 512) {
                      hbuf[0] = hold & 255;
                      hbuf[1] = hold >>> 8 & 255;
                      state2.check = crc32(
                        state2.check,
                        hbuf,
                        2,
                        0
                      );
                    }
                    hold = 0;
                    bits = 0;
                    state2.mode = TIME;
                  /* falls through */
                  case TIME:
                    while (bits < 32) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    if (state2.head) {
                      state2.head.time = hold;
                    }
                    if (state2.flags & 512) {
                      hbuf[0] = hold & 255;
                      hbuf[1] = hold >>> 8 & 255;
                      hbuf[2] = hold >>> 16 & 255;
                      hbuf[3] = hold >>> 24 & 255;
                      state2.check = crc32(
                        state2.check,
                        hbuf,
                        4,
                        0
                      );
                    }
                    hold = 0;
                    bits = 0;
                    state2.mode = OS;
                  /* falls through */
                  case OS:
                    while (bits < 16) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    if (state2.head) {
                      state2.head.xflags = hold & 255;
                      state2.head.os = hold >> 8;
                    }
                    if (state2.flags & 512) {
                      hbuf[0] = hold & 255;
                      hbuf[1] = hold >>> 8 & 255;
                      state2.check = crc32(
                        state2.check,
                        hbuf,
                        2,
                        0
                      );
                    }
                    hold = 0;
                    bits = 0;
                    state2.mode = EXLEN;
                  /* falls through */
                  case EXLEN:
                    if (state2.flags & 1024) {
                      while (bits < 16) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      state2.length = hold;
                      if (state2.head) {
                        state2.head.extra_len = hold;
                      }
                      if (state2.flags & 512) {
                        hbuf[0] = hold & 255;
                        hbuf[1] = hold >>> 8 & 255;
                        state2.check = crc32(
                          state2.check,
                          hbuf,
                          2,
                          0
                        );
                      }
                      hold = 0;
                      bits = 0;
                    } else if (state2.head) {
                      state2.head.extra = null;
                    }
                    state2.mode = EXTRA;
                  /* falls through */
                  case EXTRA:
                    if (state2.flags & 1024) {
                      copy3 = state2.length;
                      if (copy3 > have) {
                        copy3 = have;
                      }
                      if (copy3) {
                        if (state2.head) {
                          len2 = state2.head.extra_len - state2.length;
                          if (!state2.head.extra) {
                            state2.head.extra = new Array(
                              state2.head.extra_len
                            );
                          }
                          utils.arraySet(
                            state2.head.extra,
                            input,
                            next,
                            // extra field is limited to 65536 bytes
                            // - no need for additional size check
                            copy3,
                            /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                            len2
                          );
                        }
                        if (state2.flags & 512) {
                          state2.check = crc32(
                            state2.check,
                            input,
                            copy3,
                            next
                          );
                        }
                        have -= copy3;
                        next += copy3;
                        state2.length -= copy3;
                      }
                      if (state2.length) {
                        break inf_leave;
                      }
                    }
                    state2.length = 0;
                    state2.mode = NAME;
                  /* falls through */
                  case NAME:
                    if (state2.flags & 2048) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      copy3 = 0;
                      do {
                        len2 = input[next + copy3++];
                        if (state2.head && len2 && state2.length < 65536) {
                          state2.head.name += String.fromCharCode(len2);
                        }
                      } while (len2 && copy3 < have);
                      if (state2.flags & 512) {
                        state2.check = crc32(
                          state2.check,
                          input,
                          copy3,
                          next
                        );
                      }
                      have -= copy3;
                      next += copy3;
                      if (len2) {
                        break inf_leave;
                      }
                    } else if (state2.head) {
                      state2.head.name = null;
                    }
                    state2.length = 0;
                    state2.mode = COMMENT;
                  /* falls through */
                  case COMMENT:
                    if (state2.flags & 4096) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      copy3 = 0;
                      do {
                        len2 = input[next + copy3++];
                        if (state2.head && len2 && state2.length < 65536) {
                          state2.head.comment += String.fromCharCode(len2);
                        }
                      } while (len2 && copy3 < have);
                      if (state2.flags & 512) {
                        state2.check = crc32(
                          state2.check,
                          input,
                          copy3,
                          next
                        );
                      }
                      have -= copy3;
                      next += copy3;
                      if (len2) {
                        break inf_leave;
                      }
                    } else if (state2.head) {
                      state2.head.comment = null;
                    }
                    state2.mode = HCRC;
                  /* falls through */
                  case HCRC:
                    if (state2.flags & 512) {
                      while (bits < 16) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      if (hold !== (state2.check & 65535)) {
                        strm.msg = "header crc mismatch";
                        state2.mode = BAD;
                        break;
                      }
                      hold = 0;
                      bits = 0;
                    }
                    if (state2.head) {
                      state2.head.hcrc = state2.flags >> 9 & 1;
                      state2.head.done = true;
                    }
                    strm.adler = state2.check = 0;
                    state2.mode = TYPE;
                    break;
                  case DICTID:
                    while (bits < 32) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    strm.adler = state2.check = zswap32(hold);
                    hold = 0;
                    bits = 0;
                    state2.mode = DICT;
                  /* falls through */
                  case DICT:
                    if (state2.havedict === 0) {
                      strm.next_out = put;
                      strm.avail_out = left;
                      strm.next_in = next;
                      strm.avail_in = have;
                      state2.hold = hold;
                      state2.bits = bits;
                      return Z_NEED_DICT;
                    }
                    strm.adler = state2.check = 1;
                    state2.mode = TYPE;
                  /* falls through */
                  case TYPE:
                    if (flush2 === Z_BLOCK || flush2 === Z_TREES) {
                      break inf_leave;
                    }
                  /* falls through */
                  case TYPEDO:
                    if (state2.last) {
                      hold >>>= bits & 7;
                      bits -= bits & 7;
                      state2.mode = CHECK;
                      break;
                    }
                    while (bits < 3) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    state2.last = hold & 1;
                    hold >>>= 1;
                    bits -= 1;
                    switch (hold & 3) {
                      case 0:
                        state2.mode = STORED;
                        break;
                      case 1:
                        fixedtables(state2);
                        state2.mode = LEN_;
                        if (flush2 === Z_TREES) {
                          hold >>>= 2;
                          bits -= 2;
                          break inf_leave;
                        }
                        break;
                      case 2:
                        state2.mode = TABLE;
                        break;
                      case 3:
                        strm.msg = "invalid block type";
                        state2.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";
                      state2.mode = BAD;
                      break;
                    }
                    state2.length = hold & 65535;
                    hold = 0;
                    bits = 0;
                    state2.mode = COPY_;
                    if (flush2 === Z_TREES) {
                      break inf_leave;
                    }
                  /* falls through */
                  case COPY_:
                    state2.mode = COPY;
                  /* falls through */
                  case COPY:
                    copy3 = state2.length;
                    if (copy3) {
                      if (copy3 > have) {
                        copy3 = have;
                      }
                      if (copy3 > left) {
                        copy3 = left;
                      }
                      if (copy3 === 0) {
                        break inf_leave;
                      }
                      utils.arraySet(
                        output,
                        input,
                        next,
                        copy3,
                        put
                      );
                      have -= copy3;
                      next += copy3;
                      left -= copy3;
                      put += copy3;
                      state2.length -= copy3;
                      break;
                    }
                    state2.mode = TYPE;
                    break;
                  case TABLE:
                    while (bits < 14) {
                      if (have === 0) {
                        break inf_leave;
                      }
                      have--;
                      hold += input[next++] << bits;
                      bits += 8;
                    }
                    state2.nlen = (hold & 31) + 257;
                    hold >>>= 5;
                    bits -= 5;
                    state2.ndist = (hold & 31) + 1;
                    hold >>>= 5;
                    bits -= 5;
                    state2.ncode = (hold & 15) + 4;
                    hold >>>= 4;
                    bits -= 4;
                    if (state2.nlen > 286 || state2.ndist > 30) {
                      strm.msg = "too many length or distance symbols";
                      state2.mode = BAD;
                      break;
                    }
                    state2.have = 0;
                    state2.mode = LENLENS;
                  /* falls through */
                  case LENLENS:
                    while (state2.have < state2.ncode) {
                      while (bits < 3) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      state2.lens[order[state2.have++]] = hold & 7;
                      hold >>>= 3;
                      bits -= 3;
                    }
                    while (state2.have < 19) {
                      state2.lens[order[state2.have++]] = 0;
                    }
                    state2.lencode = state2.lendyn;
                    state2.lenbits = 7;
                    opts = { bits: state2.lenbits };
                    ret = inflate_table(
                      CODES,
                      state2.lens,
                      0,
                      19,
                      state2.lencode,
                      0,
                      state2.work,
                      opts
                    );
                    state2.lenbits = opts.bits;
                    if (ret) {
                      strm.msg = "invalid code lengths set";
                      state2.mode = BAD;
                      break;
                    }
                    state2.have = 0;
                    state2.mode = CODELENS;
                  /* falls through */
                  case CODELENS:
                    while (state2.have < state2.nlen + state2.ndist) {
                      for (; ; ) {
                        here = state2.lencode[hold & (1 << state2.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;
                        state2.lens[state2.have++] = here_val;
                      } else {
                        if (here_val === 16) {
                          n3 = here_bits + 2;
                          while (bits < n3) {
                            if (have === 0) {
                              break inf_leave;
                            }
                            have--;
                            hold += input[next++] << bits;
                            bits += 8;
                          }
                          hold >>>= here_bits;
                          bits -= here_bits;
                          if (state2.have === 0) {
                            strm.msg = "invalid bit length repeat";
                            state2.mode = BAD;
                            break;
                          }
                          len2 = state2.lens[state2.have - 1];
                          copy3 = 3 + (hold & 3);
                          hold >>>= 2;
                          bits -= 2;
                        } else if (here_val === 17) {
                          n3 = here_bits + 3;
                          while (bits < n3) {
                            if (have === 0) {
                              break inf_leave;
                            }
                            have--;
                            hold += input[next++] << bits;
                            bits += 8;
                          }
                          hold >>>= here_bits;
                          bits -= here_bits;
                          len2 = 0;
                          copy3 = 3 + (hold & 7);
                          hold >>>= 3;
                          bits -= 3;
                        } else {
                          n3 = here_bits + 7;
                          while (bits < n3) {
                            if (have === 0) {
                              break inf_leave;
                            }
                            have--;
                            hold += input[next++] << bits;
                            bits += 8;
                          }
                          hold >>>= here_bits;
                          bits -= here_bits;
                          len2 = 0;
                          copy3 = 11 + (hold & 127);
                          hold >>>= 7;
                          bits -= 7;
                        }
                        if (state2.have + copy3 > state2.nlen + state2.ndist) {
                          strm.msg = "invalid bit length repeat";
                          state2.mode = BAD;
                          break;
                        }
                        while (copy3--) {
                          state2.lens[state2.have++] = len2;
                        }
                      }
                    }
                    if (state2.mode === BAD) {
                      break;
                    }
                    if (state2.lens[256] === 0) {
                      strm.msg = "invalid code -- missing end-of-block";
                      state2.mode = BAD;
                      break;
                    }
                    state2.lenbits = 9;
                    opts = { bits: state2.lenbits };
                    ret = inflate_table(
                      LENS,
                      state2.lens,
                      0,
                      state2.nlen,
                      state2.lencode,
                      0,
                      state2.work,
                      opts
                    );
                    state2.lenbits = opts.bits;
                    if (ret) {
                      strm.msg = "invalid literal/lengths set";
                      state2.mode = BAD;
                      break;
                    }
                    state2.distbits = 6;
                    state2.distcode = state2.distdyn;
                    opts = { bits: state2.distbits };
                    ret = inflate_table(
                      DISTS,
                      state2.lens,
                      state2.nlen,
                      state2.ndist,
                      state2.distcode,
                      0,
                      state2.work,
                      opts
                    );
                    state2.distbits = opts.bits;
                    if (ret) {
                      strm.msg = "invalid distances set";
                      state2.mode = BAD;
                      break;
                    }
                    state2.mode = LEN_;
                    if (flush2 === Z_TREES) {
                      break inf_leave;
                    }
                  /* falls through */
                  case LEN_:
                    state2.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;
                      state2.hold = hold;
                      state2.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 = state2.hold;
                      bits = state2.bits;
                      if (state2.mode === TYPE) {
                        state2.back = -1;
                      }
                      break;
                    }
                    state2.back = 0;
                    for (; ; ) {
                      here = state2.lencode[hold & (1 << state2.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 = state2.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;
                      state2.back += last_bits;
                    }
                    hold >>>= here_bits;
                    bits -= here_bits;
                    state2.back += here_bits;
                    state2.length = here_val;
                    if (here_op === 0) {
                      state2.mode = LIT;
                      break;
                    }
                    if (here_op & 32) {
                      state2.back = -1;
                      state2.mode = TYPE;
                      break;
                    }
                    if (here_op & 64) {
                      strm.msg = "invalid literal/length code";
                      state2.mode = BAD;
                      break;
                    }
                    state2.extra = here_op & 15;
                    state2.mode = LENEXT;
                  /* falls through */
                  case LENEXT:
                    if (state2.extra) {
                      n3 = state2.extra;
                      while (bits < n3) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      state2.length += hold & (1 << state2.extra) - 1;
                      hold >>>= state2.extra;
                      bits -= state2.extra;
                      state2.back += state2.extra;
                    }
                    state2.was = state2.length;
                    state2.mode = DIST;
                  /* falls through */
                  case DIST:
                    for (; ; ) {
                      here = state2.distcode[hold & (1 << state2.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 = state2.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;
                      state2.back += last_bits;
                    }
                    hold >>>= here_bits;
                    bits -= here_bits;
                    state2.back += here_bits;
                    if (here_op & 64) {
                      strm.msg = "invalid distance code";
                      state2.mode = BAD;
                      break;
                    }
                    state2.offset = here_val;
                    state2.extra = here_op & 15;
                    state2.mode = DISTEXT;
                  /* falls through */
                  case DISTEXT:
                    if (state2.extra) {
                      n3 = state2.extra;
                      while (bits < n3) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      state2.offset += hold & (1 << state2.extra) - 1;
                      hold >>>= state2.extra;
                      bits -= state2.extra;
                      state2.back += state2.extra;
                    }
                    if (state2.offset > state2.dmax) {
                      strm.msg = "invalid distance too far back";
                      state2.mode = BAD;
                      break;
                    }
                    state2.mode = MATCH;
                  /* falls through */
                  case MATCH:
                    if (left === 0) {
                      break inf_leave;
                    }
                    copy3 = _out - left;
                    if (state2.offset > copy3) {
                      copy3 = state2.offset - copy3;
                      if (copy3 > state2.whave) {
                        if (state2.sane) {
                          strm.msg = "invalid distance too far back";
                          state2.mode = BAD;
                          break;
                        }
                      }
                      if (copy3 > state2.wnext) {
                        copy3 -= state2.wnext;
                        from = state2.wsize - copy3;
                      } else {
                        from = state2.wnext - copy3;
                      }
                      if (copy3 > state2.length) {
                        copy3 = state2.length;
                      }
                      from_source = state2.window;
                    } else {
                      from_source = output;
                      from = put - state2.offset;
                      copy3 = state2.length;
                    }
                    if (copy3 > left) {
                      copy3 = left;
                    }
                    left -= copy3;
                    state2.length -= copy3;
                    do {
                      output[put++] = from_source[from++];
                    } while (--copy3);
                    if (state2.length === 0) {
                      state2.mode = LEN;
                    }
                    break;
                  case LIT:
                    if (left === 0) {
                      break inf_leave;
                    }
                    output[put++] = state2.length;
                    left--;
                    state2.mode = LEN;
                    break;
                  case CHECK:
                    if (state2.wrap) {
                      while (bits < 32) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold |= input[next++] << bits;
                        bits += 8;
                      }
                      _out -= left;
                      strm.total_out += _out;
                      state2.total += _out;
                      if (_out) {
                        strm.adler = state2.check = /*UPDATE(state.check, put - _out, _out);*/
                        state2.flags ? crc32(
                          state2.check,
                          output,
                          _out,
                          put - _out
                        ) : adler32(
                          state2.check,
                          output,
                          _out,
                          put - _out
                        );
                      }
                      _out = left;
                      if ((state2.flags ? hold : zswap32(hold)) !== state2.check) {
                        strm.msg = "incorrect data check";
                        state2.mode = BAD;
                        break;
                      }
                      hold = 0;
                      bits = 0;
                    }
                    state2.mode = LENGTH;
                  /* falls through */
                  case LENGTH:
                    if (state2.wrap && state2.flags) {
                      while (bits < 32) {
                        if (have === 0) {
                          break inf_leave;
                        }
                        have--;
                        hold += input[next++] << bits;
                        bits += 8;
                      }
                      if (hold !== (state2.total & 4294967295)) {
                        strm.msg = "incorrect length check";
                        state2.mode = BAD;
                        break;
                      }
                      hold = 0;
                      bits = 0;
                    }
                    state2.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;
              state2.hold = hold;
              state2.bits = bits;
              if (state2.wsize || _out !== strm.avail_out && state2.mode < BAD && (state2.mode < CHECK || flush2 !== Z_FINISH)) {
                if (updatewindow(
                  strm,
                  strm.output,
                  strm.next_out,
                  _out - strm.avail_out
                )) {
                  state2.mode = MEM;
                  return Z_MEM_ERROR;
                }
              }
              _in -= strm.avail_in;
              _out -= strm.avail_out;
              strm.total_in += _in;
              strm.total_out += _out;
              state2.total += _out;
              if (state2.wrap && _out) {
                strm.adler = state2.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
                state2.flags ? crc32(
                  state2.check,
                  output,
                  _out,
                  strm.next_out - _out
                ) : adler32(
                  state2.check,
                  output,
                  _out,
                  strm.next_out - _out
                );
              }
              strm.data_type = state2.bits + (state2.last ? 64 : 0) + (state2.mode === TYPE ? 128 : 0) + (state2.mode === LEN_ || state2.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 state2 = strm.state;
              if (state2.window) {
                state2.window = null;
              }
              strm.state = null;
              return Z_OK;
            }
            function inflateGetHeader(strm, head2) {
              var state2;
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              state2 = strm.state;
              if ((state2.wrap & 2) === 0) {
                return Z_STREAM_ERROR;
              }
              state2.head = head2;
              head2.done = false;
              return Z_OK;
            }
            function inflateSetDictionary(strm, dictionary) {
              var dictLength = dictionary.length;
              var state2;
              var dictid;
              var ret;
              if (!strm || !strm.state) {
                return Z_STREAM_ERROR;
              }
              state2 = strm.state;
              if (state2.wrap !== 0 && state2.mode !== DICT) {
                return Z_STREAM_ERROR;
              }
              if (state2.mode === DICT) {
                dictid = 1;
                dictid = adler32(
                  dictid,
                  dictionary,
                  dictLength,
                  0
                );
                if (dictid !== state2.check) {
                  return Z_DATA_ERROR;
                }
              }
              ret = updatewindow(
                strm,
                dictionary,
                dictLength,
                dictLength
              );
              if (ret) {
                state2.mode = MEM;
                return Z_MEM_ERROR;
              }
              state2.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 len2 = 0;
              var sym = 0;
              var min3 = 0, max3 = 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 (len2 = 0; len2 <= MAXBITS; len2++) {
                count[len2] = 0;
              }
              for (sym = 0; sym < codes; sym++) {
                count[lens[lens_index + sym]]++;
              }
              root = bits;
              for (max3 = MAXBITS; max3 >= 1; max3--) {
                if (count[max3] !== 0) {
                  break;
                }
              }
              if (root > max3) {
                root = max3;
              }
              if (max3 === 0) {
                table[table_index++] = 1 << 24 | 64 << 16 | 0;
                table[table_index++] = 1 << 24 | 64 << 16 | 0;
                opts.bits = 1;
                return 0;
              }
              for (min3 = 1; min3 < max3; min3++) {
                if (count[min3] !== 0) {
                  break;
                }
              }
              if (root < min3) {
                root = min3;
              }
              left = 1;
              for (len2 = 1; len2 <= MAXBITS; len2++) {
                left <<= 1;
                left -= count[len2];
                if (left < 0) {
                  return -1;
                }
              }
              if (left > 0 && (type === CODES || max3 !== 1)) {
                return -1;
              }
              offs[1] = 0;
              for (len2 = 1; len2 < MAXBITS; len2++) {
                offs[len2 + 1] = offs[len2] + count[len2];
              }
              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;
              len2 = min3;
              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 = len2 - 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 << len2 - drop;
                fill = 1 << curr;
                min3 = fill;
                do {
                  fill -= incr;
                  table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0;
                } while (fill !== 0);
                incr = 1 << len2 - 1;
                while (huff & incr) {
                  incr >>= 1;
                }
                if (incr !== 0) {
                  huff &= incr - 1;
                  huff += incr;
                } else {
                  huff = 0;
                }
                sym++;
                if (--count[len2] === 0) {
                  if (len2 === max3) {
                    break;
                  }
                  len2 = lens[lens_index + work[sym]];
                }
                if (len2 > root && (huff & mask) !== low) {
                  if (drop === 0) {
                    drop = root;
                  }
                  next += min3;
                  curr = len2 - drop;
                  left = 1 << curr;
                  while (curr + drop < max3) {
                    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] = len2 - 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((e3) => e3 === listener);
      if (pos > -1) {
        bin.splice(pos, 1);
        this.listeners[type] = bin;
      }
    }
    dispatch(event) {
      let bin = this.listeners[event.type];
      if (bin) {
        for (let l3 = 0, e3 = bin.length; l3 < e3; l3++) {
          if (!event.__mayPropagate) break;
          bin[l3](event);
        }
      }
    }
  };
  var startDate = (/* @__PURE__ */ new Date(`1904-01-01T00:00:00+0000`)).getTime();
  function asText(data) {
    return Array.from(data).map((v3) => String.fromCharCode(v3)).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(n3 = 0, bits = 8) {
      this.offset += n3 * bits / 8;
    }
    getValue(type, increment) {
      let pos = this.start + this.offset;
      this.offset += increment;
      try {
        return this.data[type](pos);
      } catch (e3) {
        console.error(`parser`, type, increment, this);
        console.error(`parser`, this.start, this.offset);
        throw e3;
      }
    }
    flags(n3) {
      if (n3 === 8 || n3 === 16 || n3 === 32 || n3 === 64) {
        return this[`uint${n3}`].toString(2).padStart(n3, 0).split(``).map((v3) => v3 === "1");
      }
      console.error(
        `Error parsing flags: flag types can only be 1, 2, 4, or 8 bytes long`
      );
      console.trace();
    }
    get tag() {
      const t4 = this.uint32;
      return asText([
        t4 >> 24 & 255,
        t4 >> 16 & 255,
        t4 >> 8 & 255,
        t4 & 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 i3 = 0; i3 < 5; i3++) {
        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(n3 = 0, position = 0, bits = 8, signed = false) {
      n3 = n3 || this.length;
      if (n3 === 0) return [];
      if (position) this.currentPosition = position;
      const fn = `${signed ? `` : `u`}int${bits}`, slice2 = [];
      while (n3--) slice2.push(this[fn]);
      return slice2;
    }
  };
  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((e3, i3) => {
        let next = this.directory[i3 + 1];
        if (next) {
          next.offset = e3.offset + (e3.transformLength !== void 0 ? e3.transformLength : e3.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 (e3) {
          console.error(e3);
        }
      });
    });
  }
  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((e3) => {
      let name2 = Object.keys(e3)[0];
      tableClasses[name2] = e3[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 i3 = 0; i3 < ar1.length; i3++) {
      if (ar1[i3] !== ar2[i3]) 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 d3 = document.createElement("div");
      d3.textContent = text;
      d3.style.fontFamily = this.name;
      d3.style.fontSize = `${size4}px`;
      d3.style.color = `transparent`;
      d3.style.background = `transparent`;
      d3.style.top = `0`;
      d3.style.left = `0`;
      d3.style.position = `absolute`;
      document.body.appendChild(d3);
      let bbox = d3.getBoundingClientRect();
      document.body.removeChild(d3);
      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((h3) => ({
          firstCode: h3.firstCode,
          lastCode: h3.lastCode
        }));
      }
      return this.subHeaders.map((h3) => ({
        start: h3.firstCode,
        end: h3.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 = (_, i3) => {
        let startCode = this.startCode[i3], endCode = this.endCode[i3], idDelta = this.idDelta[i3], idRangeOffset = this.idRangeOffset[i3], idRangeOffsetPointer = idRangePosition + 2 * i3, glyphIDs = [];
        if (idRangeOffset === 0) {
          for (let i22 = startCode + idDelta, e3 = endCode + idDelta; i22 <= e3; i22++) {
            glyphIDs.push(i22);
          }
        } else {
          for (let i22 = 0, e3 = endCode - startCode; i22 <= e3; 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 s3 = this.segments.find((v3) => v3.glyphIDs.includes(glyphID));
      if (!s3) return {};
      const code = s3.startCode + s3.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 segment2 = this.segments.find(
        (s3) => s3.startCode <= charCode && charCode <= s3.endCode
      );
      if (!segment2) return 0;
      return segment2.glyphIDs[charCode - segment2.startCode];
    }
    supports(charCode) {
      return this.getGlyphId(charCode) !== 0;
    }
    getSupportedCharCodes(preservePropNames = false) {
      if (preservePropNames) return this.segments;
      return this.segments.map((v3) => ({
        start: v3.startCode,
        end: v3.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(
        (s3) => s3.startcharCode <= charCode && charCode <= s3.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((v3) => ({
        start: v3.startcharCode,
        end: v3.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(
        (s3) => s3.startCharCode <= charCode && charCode <= s3.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((v3) => ({
        start: v3.startCharCode,
        end: v3.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(
        (s3) => s3.startCharCode <= charCode && charCode <= s3.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((v3) => ({
        start: v3.startCharCode,
        end: v3.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 v3 = this.varSelector.find(
        (uvs) => uvs.varSelector === variation
      );
      return v3 ? v3 : false;
    }
    getSupportedVariations() {
      return this.varSelectors.map((v3) => v3.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((r4) => ({
        platformID: r4.platformID,
        encodingId: r4.encodingID
      }));
    }
    getSupportedCharCodes(platformID, encodingID) {
      const recordID = this.encodingRecords.findIndex(
        (r4) => r4.platformID === platformID && r4.encodingID === encodingID
      );
      if (recordID === -1) return false;
      const subtable = this.getSubTable(recordID);
      return subtable.getSupportedCharCodes();
    }
    reverse(glyphid) {
      for (let i3 = 0; i3 < this.numTables; i3++) {
        let code = this.getSubTable(i3).reverse(glyphid);
        if (code) return code;
      }
    }
    getGlyphId(char) {
      let last = 0;
      this.encodingRecords.some((_, tableID) => {
        let t4 = this.getSubTable(tableID);
        if (!t4.getGlyphId) return false;
        last = t4.getGlyphId(char);
        return last !== 0;
      });
      return last;
    }
    supports(char) {
      return this.encodingRecords.some((_, tableID) => {
        const t4 = this.getSubTable(tableID);
        return t4.supports && t4.supports(char) !== false;
      });
    }
    supportsVariation(variation) {
      return this.encodingRecords.some((_, tableID) => {
        const t4 = this.getSubTable(tableID);
        return t4.supportsVariation && t4.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(w3, b3) {
      this.advanceWidth = w3;
      this.lsb = b3;
    }
  };
  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(length2, offset4) {
      this.length = length2;
      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: length2 } = record;
    if (length2 === 0) return ``;
    if (platformID === 0 || platformID === 3) {
      const str22 = [];
      for (let i3 = 0, e3 = length2 / 2; i3 < e3; i3++)
        str22[i3] = String.fromCharCode(p22.uint16);
      return str22.join(``);
    }
    const bytes = p22.readBytes(length2);
    const str3 = [];
    bytes.forEach(function(b3, i3) {
      str3[i3] = String.fromCharCode(b3);
    });
    return str3.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 i3 = 0; i3 < this.numGlyphs; i3++) {
          let index2 = this.glyphNameIndex[i3];
          if (index2 < macStrings.length) {
            this.glyphNameOffsets.push(this.glyphNameOffsets[i3]);
            continue;
          }
          let bytelength = p22.int8;
          p22.skip(bytelength);
          this.glyphNameOffsets.push(
            this.glyphNameOffsets[i3] + 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 len2 = next - offset4 - 1;
      if (len2 === 0) return `.notdef.`;
      this.parser.currentPosition = this.namesOffset + offset4;
      const data = this.parser.readBytes(
        len2,
        this.namesOffset + offset4,
        8,
        true
      );
      return data.map((b3) => String.fromCharCode(b3)).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((r4) => r4.scriptTag);
    }
    getScriptTable(scriptTag) {
      let record = this.scriptList.scriptRecords.find(
        (r4) => r4.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(
        (l3) => l3.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(
        (l3) => l3.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(
          (f3) => f3.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 SVG95 = 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(
        (d3) => d3.startGlyphID <= glyphID && glyphID <= d3.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: SVG95 });
  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 i3 = 0; i3 < this.instanceCount; i3++) {
          p22.currentPosition = instanceStart + i3 * this.instanceSize;
          instances.push(
            new InstanceRecord(p22, this.axisCount, this.instanceSize)
          );
        }
        return instances;
      });
    }
    getSupportedAxes() {
      return this.axes.map((a3) => a3.tag);
    }
    getAxis(name2) {
      return this.axes.find((a3) => a3.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 n3 = dict.length / 2;
      lazy$1(
        this,
        `items`,
        () => [...new Array(n3)].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, length2) {
      this.parser.currentPosition = this.tableStart + offset4;
      return this.parser.readBytes(length2);
    }
  };
  var glyf$1 = Object.freeze({ __proto__: null, glyf });
  var loca = class extends SimpleTable {
    constructor(dict, dataview, tables) {
      const { p: p22 } = super(dict, dataview);
      const n3 = tables.maxp.numGlyphs + 1;
      if (tables.head.indexToLocFormat === 0) {
        this.x2 = true;
        lazy$1(
          this,
          `offsets`,
          () => [...new Array(n3)].map((_) => p22.Offset16)
        );
      } else {
        lazy$1(
          this,
          `offsets`,
          () => [...new Array(n3)].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 i3 = 0; i3 < this.nTables; i3++) {
          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(h3, b3) {
      this.advanceHeight = h3;
      this.topSideBearing = b3;
    }
  };
  var vmtx$1 = Object.freeze({ __proto__: null, vmtx });

  // packages/global-styles-ui/build-module/font-library/utils/make-families-from-faces.mjs
  var import_components118 = __toESM(require_components(), 1);
  var { kebabCase: kebabCase4 } = unlock7(import_components118.privateApis);
  function makeFamiliesFromFaces(fontFaces) {
    const fontFamiliesObject = fontFaces.reduce(
      (acc, item) => {
        if (!acc[item.fontFamily]) {
          acc[item.fontFamily] = {
            name: item.fontFamily,
            fontFamily: item.fontFamily,
            slug: kebabCase4(item.fontFamily.toLowerCase()),
            fontFace: []
          };
        }
        acc[item.fontFamily].fontFace.push(item);
        return acc;
      },
      {}
    );
    return Object.values(fontFamiliesObject);
  }

  // packages/global-styles-ui/build-module/font-library/upload-fonts.mjs
  var import_jsx_runtime316 = __toESM(require_jsx_runtime(), 1);
  function UploadFonts() {
    const { installFonts } = (0, import_element182.useContext)(FontLibraryContext);
    const [isUploading, setIsUploading] = (0, import_element182.useState)(false);
    const [notice, setNotice] = (0, import_element182.useState)(null);
    const handleDropZone = (files) => {
      handleFilesUpload(files);
    };
    const onFilesUpload = (event) => {
      handleFilesUpload(event.target.files);
    };
    const handleFilesUpload = async (files) => {
      if (!files) {
        return;
      }
      setNotice(null);
      setIsUploading(true);
      const uniqueFilenames = /* @__PURE__ */ new Set();
      const selectedFiles = [...files];
      let hasInvalidFiles = false;
      const checkFilesPromises = selectedFiles.map(async (file) => {
        const isFont = await isFontFile(file);
        if (!isFont) {
          hasInvalidFiles = true;
          return null;
        }
        if (uniqueFilenames.has(file.name)) {
          return null;
        }
        const fileExtension = (((file.name ?? "").split(".") ?? []).pop() ?? "").toLowerCase();
        if (ALLOWED_FILE_EXTENSIONS.includes(fileExtension)) {
          uniqueFilenames.add(file.name);
          return file;
        }
        return null;
      });
      const allowedFiles = (await Promise.all(checkFilesPromises)).filter((file) => null !== file);
      if (allowedFiles.length > 0) {
        loadFiles(allowedFiles);
      } else {
        const message2 = hasInvalidFiles ? (0, import_i18n160.__)("Sorry, you are not allowed to upload this file type.") : (0, import_i18n160.__)("No fonts found to install.");
        setNotice({
          type: "error",
          message: message2
        });
        setIsUploading(false);
      }
    };
    const loadFiles = async (files) => {
      const fontFacesLoaded = await Promise.all(
        files.map(async (fontFile) => {
          const fontFaceData = await getFontFaceMetadata(fontFile);
          await loadFontFaceInBrowser(
            fontFaceData,
            fontFaceData.file,
            "all"
          );
          return fontFaceData;
        })
      );
      handleInstall(fontFacesLoaded);
    };
    async function isFontFile(file) {
      const font2 = new Font("Uploaded Font");
      try {
        const buffer = await readFileAsArrayBuffer(file);
        await font2.fromDataBuffer(buffer, "font");
        return true;
      } catch {
        return false;
      }
    }
    async function readFileAsArrayBuffer(file) {
      return new Promise((resolve, reject) => {
        const reader = new window.FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
      });
    }
    const getFontFaceMetadata = async (fontFile) => {
      const buffer = await readFileAsArrayBuffer(fontFile);
      const fontObj = new Font("Uploaded Font");
      fontObj.fromDataBuffer(buffer, fontFile.name);
      const onloadEvent = await new Promise(
        (resolve) => fontObj.onload = resolve
      );
      const font2 = onloadEvent.detail.font;
      const { name: name2 } = font2.opentype.tables;
      const fontName = name2.get(16) || name2.get(1);
      const isItalic = name2.get(2).toLowerCase().includes("italic");
      const fontWeight = font2.opentype.tables["OS/2"].usWeightClass || "normal";
      const isVariable = !!font2.opentype.tables.fvar;
      const weightAxis = isVariable && font2.opentype.tables.fvar.axes.find(
        ({ tag }) => tag === "wght"
      );
      const weightRange = weightAxis ? `${weightAxis.minValue} ${weightAxis.maxValue}` : null;
      return {
        file: fontFile,
        fontFamily: fontName,
        fontStyle: isItalic ? "italic" : "normal",
        fontWeight: weightRange || fontWeight
      };
    };
    const handleInstall = async (fontFaces) => {
      const fontFamilies = makeFamiliesFromFaces(fontFaces);
      try {
        await installFonts(fontFamilies);
        setNotice({
          type: "success",
          message: (0, import_i18n160.__)("Fonts were installed successfully.")
        });
      } catch (error2) {
        const typedError = error2;
        setNotice({
          type: "error",
          message: typedError.message,
          errors: typedError?.installationErrors
        });
      }
      setIsUploading(false);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)("div", { className: "font-library__tabpanel-layout", children: [
      /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(import_components119.DropZone, { onFilesDrop: handleDropZone }),
      /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(import_components119.__experimentalVStack, { className: "font-library__local-fonts", justify: "start", children: [
        notice && /* @__PURE__ */ (0, import_jsx_runtime316.jsxs)(
          import_components119.Notice,
          {
            status: notice.type,
            __unstableHTML: true,
            onRemove: () => setNotice(null),
            children: [
              notice.message,
              notice.errors && /* @__PURE__ */ (0, import_jsx_runtime316.jsx)("ul", { children: notice.errors.map((error2, index2) => /* @__PURE__ */ (0, import_jsx_runtime316.jsx)("li", { children: error2 }, index2)) })
            ]
          }
        ),
        isUploading && /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(import_components119.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime316.jsx)("div", { className: "font-library__upload-area", children: /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(import_components119.ProgressBar, {}) }) }),
        !isUploading && /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
          import_components119.FormFileUpload,
          {
            accept: ALLOWED_FILE_EXTENSIONS.map(
              (ext) => `.${ext}`
            ).join(","),
            multiple: true,
            onChange: onFilesUpload,
            render: ({ openFileDialog }) => /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(
              import_components119.Button,
              {
                __next40pxDefaultSize: true,
                className: "font-library__upload-area",
                onClick: openFileDialog,
                children: (0, import_i18n160.__)("Upload font")
              }
            )
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime316.jsx)(import_components119.__experimentalText, { className: "font-library__upload-area__text", children: (0, import_i18n160.__)(
          "Uploaded fonts appear in your library and can be used in your theme. Supported formats: .ttf, .otf, .woff, and .woff2."
        ) })
      ] })
    ] });
  }
  var upload_fonts_default = UploadFonts;

  // packages/global-styles-ui/build-module/font-library/modal.mjs
  var import_jsx_runtime317 = __toESM(require_jsx_runtime(), 1);
  var { Tabs } = unlock7(import_components120.privateApis);
  var DEFAULT_TAB = {
    id: "installed-fonts",
    title: (0, import_i18n161._x)("Library", "Font library")
  };
  var UPLOAD_TAB = {
    id: "upload-fonts",
    title: (0, import_i18n161._x)("Upload", "noun")
  };
  var tabsFromCollections = (collections) => collections.map(({ slug, name: name2 }) => ({
    id: slug,
    title: collections.length === 1 && slug === "google-fonts" ? (0, import_i18n161.__)("Install Fonts") : name2
  }));
  function FontLibraryModal({
    onRequestClose,
    defaultTabId = "installed-fonts"
  }) {
    const { records: collections = [] } = (0, import_core_data39.useEntityRecords)("root", "fontCollection", {
      _fields: "slug,name,description"
    });
    const canUserCreate = (0, import_data57.useSelect)((select9) => {
      return select9(import_core_data39.store).canUser("create", {
        kind: "postType",
        name: "wp_font_family"
      });
    }, []);
    const tabs = [DEFAULT_TAB];
    if (canUserCreate) {
      tabs.push(UPLOAD_TAB);
      tabs.push(...tabsFromCollections(collections || []));
    }
    return /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(
      import_components120.Modal,
      {
        title: (0, import_i18n161.__)("Fonts"),
        onRequestClose,
        isFullScreen: true,
        className: "font-library-modal",
        children: /* @__PURE__ */ (0, import_jsx_runtime317.jsxs)(Tabs, { defaultTabId, children: [
          /* @__PURE__ */ (0, import_jsx_runtime317.jsx)("div", { className: "font-library-modal__tablist-container", children: /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(Tabs.TabList, { children: tabs.map(({ id, title }) => /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(Tabs.Tab, { tabId: id, children: title }, id)) }) }),
          tabs.map(({ id }) => {
            let contents;
            switch (id) {
              case "upload-fonts":
                contents = /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(upload_fonts_default, {});
                break;
              case "installed-fonts":
                contents = /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(installed_fonts_default, {});
                break;
              default:
                contents = /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(font_collection_default, { slug: id });
            }
            return /* @__PURE__ */ (0, import_jsx_runtime317.jsx)(
              Tabs.TabPanel,
              {
                tabId: id,
                focusable: false,
                className: "font-library-modal__tab-panel",
                children: contents
              },
              id
            );
          })
        ] })
      }
    );
  }
  var modal_default2 = FontLibraryModal;

  // packages/global-styles-ui/build-module/font-family-item.mjs
  var import_i18n162 = __toESM(require_i18n(), 1);
  var import_components121 = __toESM(require_components(), 1);
  var import_element183 = __toESM(require_element(), 1);
  var import_jsx_runtime318 = __toESM(require_jsx_runtime(), 1);
  function FontFamilyItem({ font: font2 }) {
    const { handleSetLibraryFontSelected, setModalTabOpen } = (0, import_element183.useContext)(FontLibraryContext);
    const variantsCount = font2?.fontFace?.length || 1;
    const handleClick = () => {
      handleSetLibraryFontSelected?.(font2);
      setModalTabOpen?.("installed-fonts");
    };
    const previewStyle = getFamilyPreviewStyle(font2);
    return /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(import_components121.__experimentalItem, { onClick: handleClick, children: /* @__PURE__ */ (0, import_jsx_runtime318.jsxs)(import_components121.__experimentalHStack, { justify: "space-between", children: [
      /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(import_components121.FlexItem, { style: previewStyle, children: font2.name }),
      /* @__PURE__ */ (0, import_jsx_runtime318.jsx)(import_components121.FlexItem, { className: "global-styles-ui-screen-typography__font-variants-count", children: (0, import_i18n162.sprintf)(
        /* translators: %d: Number of font variants. */
        (0, import_i18n162._n)("%d variant", "%d variants", variantsCount),
        variantsCount
      ) })
    ] }) });
  }
  var font_family_item_default = FontFamilyItem;

  // packages/global-styles-ui/build-module/font-families.mjs
  var import_jsx_runtime319 = __toESM(require_jsx_runtime(), 1);
  function mapFontsWithSource(fonts, source) {
    return fonts ? fonts.map((f3) => setUIValuesNeeded(f3, { source })) : [];
  }
  function FontFamiliesInner() {
    const { baseCustomFonts, modalTabOpen, setModalTabOpen } = (0, import_element184.useContext)(FontLibraryContext);
    const [fontFamilies] = useSetting("typography.fontFamilies");
    const [baseFontFamilies] = useSetting(
      "typography.fontFamilies",
      void 0,
      "base"
    );
    const themeFonts = mapFontsWithSource(fontFamilies?.theme, "theme");
    const customFonts = mapFontsWithSource(fontFamilies?.custom, "custom");
    const activeFonts = [...themeFonts, ...customFonts].sort(
      (a3, b3) => a3.name.localeCompare(b3.name)
    );
    const hasFonts = 0 < activeFonts.length;
    const hasInstalledFonts = hasFonts || baseFontFamilies?.theme?.length > 0 || (baseCustomFonts?.length ?? 0) > 0;
    return /* @__PURE__ */ (0, import_jsx_runtime319.jsxs)(import_jsx_runtime319.Fragment, { children: [
      !!modalTabOpen && /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(
        modal_default2,
        {
          onRequestClose: () => setModalTabOpen?.(""),
          defaultTabId: modalTabOpen
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime319.jsxs)(import_components122.__experimentalVStack, { spacing: 2, children: [
        /* @__PURE__ */ (0, import_jsx_runtime319.jsxs)(import_components122.__experimentalHStack, { justify: "space-between", children: [
          /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(Subtitle, { level: 3, children: (0, import_i18n163.__)("Fonts") }),
          /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(
            import_components122.Button,
            {
              onClick: () => setModalTabOpen?.("installed-fonts"),
              label: (0, import_i18n163.__)("Manage fonts"),
              icon: settings_default,
              size: "small"
            }
          )
        ] }),
        activeFonts.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(import_jsx_runtime319.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(import_components122.__experimentalItemGroup, { size: "large", isBordered: true, isSeparated: true, children: activeFonts.map((font2) => /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(
          font_family_item_default,
          {
            font: font2
          },
          font2.slug
        )) }) }),
        !hasFonts && /* @__PURE__ */ (0, import_jsx_runtime319.jsxs)(import_jsx_runtime319.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(import_components122.__experimentalText, { as: "p", children: hasInstalledFonts ? (0, import_i18n163.__)("No fonts activated.") : (0, import_i18n163.__)("No fonts installed.") }),
          /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(
            import_components122.Button,
            {
              className: "global-styles-ui-font-families__manage-fonts",
              variant: "secondary",
              __next40pxDefaultSize: true,
              onClick: () => {
                setModalTabOpen?.(
                  hasInstalledFonts ? "installed-fonts" : "upload-fonts"
                );
              },
              children: hasInstalledFonts ? (0, import_i18n163.__)("Manage fonts") : (0, import_i18n163.__)("Add fonts")
            }
          )
        ] })
      ] })
    ] });
  }
  function FontFamilies({ ...props }) {
    return /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(context_default, { children: /* @__PURE__ */ (0, import_jsx_runtime319.jsx)(FontFamiliesInner, { ...props }) });
  }

  // packages/global-styles-ui/build-module/font-sizes/font-sizes-count.mjs
  var import_i18n164 = __toESM(require_i18n(), 1);
  var import_components123 = __toESM(require_components(), 1);
  var import_jsx_runtime320 = __toESM(require_jsx_runtime(), 1);
  function FontSizes() {
    return /* @__PURE__ */ (0, import_jsx_runtime320.jsxs)(import_components123.__experimentalVStack, { spacing: 2, children: [
      /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(import_components123.__experimentalHStack, { justify: "space-between", children: /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(Subtitle, { level: 3, children: (0, import_i18n164.__)("Font Sizes") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(import_components123.__experimentalItemGroup, { isBordered: true, isSeparated: true, children: /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(NavigationButtonAsItem, { path: "/typography/font-sizes", children: /* @__PURE__ */ (0, import_jsx_runtime320.jsxs)(import_components123.__experimentalHStack, { direction: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(import_components123.FlexItem, { children: (0, import_i18n164.__)("Font size presets") }),
        /* @__PURE__ */ (0, import_jsx_runtime320.jsx)(icon_default, { icon: (0, import_i18n164.isRTL)() ? chevron_left_default : chevron_right_default })
      ] }) }) })
    ] });
  }
  var font_sizes_count_default = FontSizes;

  // packages/global-styles-ui/build-module/screen-typography.mjs
  var import_jsx_runtime321 = __toESM(require_jsx_runtime(), 1);
  function ScreenTypography() {
    const { fontLibraryEnabled } = (0, import_element185.useContext)(GlobalStylesContext);
    return /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(import_jsx_runtime321.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(
        ScreenHeader,
        {
          title: (0, import_i18n165.__)("Typography"),
          description: (0, import_i18n165.__)(
            "Available fonts, typographic styles, and the application of those styles."
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(ScreenBody, { children: /* @__PURE__ */ (0, import_jsx_runtime321.jsxs)(import_components124.__experimentalVStack, { spacing: 7, children: [
        /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(TypographyVariations, { title: (0, import_i18n165.__)("Typesets") }),
        fontLibraryEnabled && /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(FontFamilies, {}),
        /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(typography_elements_default, {}),
        /* @__PURE__ */ (0, import_jsx_runtime321.jsx)(font_sizes_count_default, {})
      ] }) })
    ] });
  }
  var screen_typography_default = ScreenTypography;

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

  // packages/global-styles-ui/build-module/typography-panel.mjs
  var import_block_editor10 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime322 = __toESM(require_jsx_runtime(), 1);
  var { useSettingsForBlockElement: useSettingsForBlockElement4, TypographyPanel: StylesTypographyPanel2 } = unlock7(import_block_editor10.privateApis);
  function TypographyPanel({
    element,
    headingLevel
  }) {
    let prefixParts = [];
    if (element === "heading") {
      prefixParts = prefixParts.concat(["elements", headingLevel]);
    } else if (element && element !== "text") {
      prefixParts = prefixParts.concat(["elements", element]);
    }
    const prefix2 = prefixParts.join(".");
    const [style] = useStyle(prefix2, "", "user", false);
    const [inheritedStyle, setStyle2] = useStyle(
      prefix2,
      "",
      "merged",
      false
    );
    const [rawSettings] = useSetting("");
    const usedElement = element === "heading" ? headingLevel : element;
    const settings = useSettingsForBlockElement4(
      rawSettings,
      void 0,
      usedElement
    );
    return /* @__PURE__ */ (0, import_jsx_runtime322.jsx)(
      StylesTypographyPanel2,
      {
        inheritedValue: inheritedStyle,
        value: style,
        onChange: setStyle2,
        settings,
        showInheritanceLabelIndicators: false
      }
    );
  }

  // packages/global-styles-ui/build-module/typography-preview.mjs
  var import_jsx_runtime323 = __toESM(require_jsx_runtime(), 1);
  function TypographyPreview({
    name: name2,
    element,
    headingLevel
  }) {
    let prefix2 = "";
    if (element === "heading") {
      prefix2 = `elements.${headingLevel}.`;
    } else if (element && element !== "text") {
      prefix2 = `elements.${element}.`;
    }
    const [fontFamily] = useStyle(prefix2 + "typography.fontFamily", name2);
    const [gradientValue] = useStyle(prefix2 + "color.gradient", name2);
    const [backgroundColor] = useStyle(prefix2 + "color.background", name2);
    const [fallbackBackgroundColor] = useStyle("color.background");
    const [color] = useStyle(prefix2 + "color.text", name2);
    const [fontSize] = useStyle(prefix2 + "typography.fontSize", name2);
    const [fontStyle] = useStyle(prefix2 + "typography.fontStyle", name2);
    const [fontWeight] = useStyle(prefix2 + "typography.fontWeight", name2);
    const [letterSpacing] = useStyle(
      prefix2 + "typography.letterSpacing",
      name2
    );
    const extraStyles = element === "link" ? {
      textDecoration: "underline"
    } : {};
    return /* @__PURE__ */ (0, import_jsx_runtime323.jsx)(
      "div",
      {
        className: "global-styles-ui-typography-preview",
        style: {
          fontFamily: fontFamily ?? "serif",
          background: gradientValue ?? backgroundColor ?? fallbackBackgroundColor,
          color,
          fontSize,
          fontStyle,
          fontWeight,
          letterSpacing,
          ...extraStyles
        },
        children: "Aa"
      }
    );
  }

  // packages/global-styles-ui/build-module/screen-typography-element.mjs
  var import_jsx_runtime324 = __toESM(require_jsx_runtime(), 1);
  var elements = {
    text: {
      description: (0, import_i18n166.__)("Manage the fonts used on the site."),
      title: (0, import_i18n166.__)("Text")
    },
    link: {
      description: (0, import_i18n166.__)("Manage the fonts and typography used on the links."),
      title: (0, import_i18n166.__)("Links")
    },
    heading: {
      description: (0, import_i18n166.__)("Manage the fonts and typography used on headings."),
      title: (0, import_i18n166.__)("Headings")
    },
    caption: {
      description: (0, import_i18n166.__)("Manage the fonts and typography used on captions."),
      title: (0, import_i18n166.__)("Captions")
    },
    button: {
      description: (0, import_i18n166.__)("Manage the fonts and typography used on buttons."),
      title: (0, import_i18n166.__)("Buttons")
    }
  };
  function ScreenTypographyElement({ element }) {
    const [headingLevel, setHeadingLevel] = (0, import_element186.useState)("heading");
    return /* @__PURE__ */ (0, import_jsx_runtime324.jsxs)(import_jsx_runtime324.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
        ScreenHeader,
        {
          title: elements[element].title,
          description: elements[element].description
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(import_components125.__experimentalSpacer, { marginX: 4, children: /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
        TypographyPreview,
        {
          element,
          headingLevel
        }
      ) }),
      element === "heading" && /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(import_components125.__experimentalSpacer, { marginX: 4, marginBottom: "1em", children: /* @__PURE__ */ (0, import_jsx_runtime324.jsxs)(
        import_components125.__experimentalToggleGroupControl,
        {
          label: (0, import_i18n166.__)("Select heading level"),
          hideLabelFromVision: true,
          value: headingLevel,
          onChange: (value) => setHeadingLevel(value),
          isBlock: true,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
              import_components125.__experimentalToggleGroupControlOption,
              {
                value: "heading",
                showTooltip: true,
                "aria-label": (0, import_i18n166.__)("All headings"),
                label: (0, import_i18n166._x)("All", "heading levels")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
              import_components125.__experimentalToggleGroupControlOption,
              {
                value: "h1",
                showTooltip: true,
                "aria-label": (0, import_i18n166.__)("Heading 1"),
                label: (0, import_i18n166.__)("H1")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
              import_components125.__experimentalToggleGroupControlOption,
              {
                value: "h2",
                showTooltip: true,
                "aria-label": (0, import_i18n166.__)("Heading 2"),
                label: (0, import_i18n166.__)("H2")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
              import_components125.__experimentalToggleGroupControlOption,
              {
                value: "h3",
                showTooltip: true,
                "aria-label": (0, import_i18n166.__)("Heading 3"),
                label: (0, import_i18n166.__)("H3")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
              import_components125.__experimentalToggleGroupControlOption,
              {
                value: "h4",
                showTooltip: true,
                "aria-label": (0, import_i18n166.__)("Heading 4"),
                label: (0, import_i18n166.__)("H4")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
              import_components125.__experimentalToggleGroupControlOption,
              {
                value: "h5",
                showTooltip: true,
                "aria-label": (0, import_i18n166.__)("Heading 5"),
                label: (0, import_i18n166.__)("H5")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
              import_components125.__experimentalToggleGroupControlOption,
              {
                value: "h6",
                showTooltip: true,
                "aria-label": (0, import_i18n166.__)("Heading 6"),
                label: (0, import_i18n166.__)("H6")
              }
            )
          ]
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime324.jsx)(
        TypographyPanel,
        {
          element,
          headingLevel
        }
      )
    ] });
  }
  var screen_typography_element_default = ScreenTypographyElement;

  // packages/global-styles-ui/build-module/screen-colors.mjs
  var import_i18n168 = __toESM(require_i18n(), 1);
  var import_components128 = __toESM(require_components(), 1);
  var import_block_editor11 = __toESM(require_block_editor(), 1);

  // packages/global-styles-ui/build-module/palette.mjs
  var import_components127 = __toESM(require_components(), 1);
  var import_i18n167 = __toESM(require_i18n(), 1);
  var import_element187 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/color-indicator-wrapper.mjs
  var import_components126 = __toESM(require_components(), 1);
  var import_jsx_runtime325 = __toESM(require_jsx_runtime(), 1);
  function ColorIndicatorWrapper({
    className,
    children,
    ...props
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime325.jsx)(
      import_components126.Flex,
      {
        className: clsx_default(
          "global-styles-ui__color-indicator-wrapper",
          className
        ),
        ...props,
        children
      }
    );
  }
  var color_indicator_wrapper_default = ColorIndicatorWrapper;

  // packages/global-styles-ui/build-module/palette.mjs
  var import_jsx_runtime326 = __toESM(require_jsx_runtime(), 1);
  var EMPTY_COLORS = [];
  function Palette({ name: name2 }) {
    const [customColors] = useSetting("color.palette.custom");
    const [themeColors] = useSetting("color.palette.theme");
    const [defaultColors] = useSetting("color.palette.default");
    const [defaultPaletteEnabled] = useSetting(
      "color.defaultPalette",
      name2
    );
    const safeCustomColors = customColors || EMPTY_COLORS;
    const safeThemeColors = themeColors || EMPTY_COLORS;
    const safeDefaultColors = defaultColors || EMPTY_COLORS;
    const safeDefaultPaletteEnabled = defaultPaletteEnabled ?? true;
    const colors2 = (0, import_element187.useMemo)(
      () => [
        ...safeCustomColors,
        ...safeThemeColors,
        ...safeDefaultColors && safeDefaultPaletteEnabled ? safeDefaultColors : EMPTY_COLORS
      ],
      [
        safeCustomColors,
        safeThemeColors,
        safeDefaultColors,
        safeDefaultPaletteEnabled
      ]
    );
    const screenPath = !name2 ? "/colors/palette" : "/blocks/" + encodeURIComponent(name2) + "/colors/palette";
    return /* @__PURE__ */ (0, import_jsx_runtime326.jsxs)(import_components127.__experimentalVStack, { spacing: 3, children: [
      /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(Subtitle, { level: 3, children: (0, import_i18n167.__)("Palette") }),
      /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(import_components127.__experimentalItemGroup, { isBordered: true, isSeparated: true, children: /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(NavigationButtonAsItem, { path: screenPath, children: /* @__PURE__ */ (0, import_jsx_runtime326.jsxs)(import_components127.__experimentalHStack, { direction: "row", children: [
        colors2.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime326.jsxs)(import_jsx_runtime326.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(import_components127.__experimentalZStack, { isLayered: false, offset: -8, children: colors2.slice(0, 5).map(({ color }, index2) => /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(
            color_indicator_wrapper_default,
            {
              children: /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(
                import_components127.ColorIndicator,
                {
                  colorValue: color
                }
              )
            },
            `${color}-${index2}`
          )) }),
          /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(import_components127.FlexItem, { isBlock: true, children: (0, import_i18n167.__)("Edit palette") })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(import_components127.FlexItem, { children: (0, import_i18n167.__)("Add colors") }),
        /* @__PURE__ */ (0, import_jsx_runtime326.jsx)(icon_default, { icon: (0, import_i18n167.isRTL)() ? chevron_left_default : chevron_right_default })
      ] }) }) })
    ] });
  }
  var palette_default = Palette;

  // packages/global-styles-ui/build-module/screen-colors.mjs
  var import_jsx_runtime327 = __toESM(require_jsx_runtime(), 1);
  var { useSettingsForBlockElement: useSettingsForBlockElement5, ColorPanel: StylesColorPanel2 } = unlock7(
    import_block_editor11.privateApis
  );
  function ScreenColors() {
    const [style, setStyle2] = useStyle(
      "",
      void 0,
      "user",
      false
    );
    const [inheritedStyle] = useStyle(
      "",
      void 0,
      "merged",
      false
    );
    const [rawSettings] = useSetting("");
    const settings = useSettingsForBlockElement5(rawSettings);
    return /* @__PURE__ */ (0, import_jsx_runtime327.jsxs)(import_jsx_runtime327.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
        ScreenHeader,
        {
          title: (0, import_i18n168.__)("Colors"),
          description: (0, import_i18n168.__)(
            "Palette colors and the application of those colors on site elements."
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(ScreenBody, { children: /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(import_components128.__experimentalVStack, { spacing: 7, children: /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(palette_default, {}) }) }),
      /* @__PURE__ */ (0, import_jsx_runtime327.jsx)(
        StylesColorPanel2,
        {
          inheritedValue: inheritedStyle,
          value: style,
          onChange: setStyle2,
          settings,
          showInheritanceLabelIndicators: false
        }
      )
    ] });
  }
  var screen_colors_default = ScreenColors;

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

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

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

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

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

  // packages/global-styles-ui/build-module/preview-colors.mjs
  var import_jsx_runtime329 = __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_runtime329.jsx)(
      preview_wrapper_default,
      {
        label,
        isFocused,
        withHoverView,
        children: ({ key }) => /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
          import_components129.__unstableMotion.div,
          {
            variants: firstFrameVariants2,
            style: {
              height: "100%",
              overflow: "hidden"
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(
              import_components129.__experimentalHStack,
              {
                spacing: 0,
                justify: "center",
                style: {
                  height: "100%",
                  overflow: "hidden"
                },
                children: /* @__PURE__ */ (0, import_jsx_runtime329.jsx)(PresetColors, {})
              }
            )
          },
          key
        )
      }
    );
  };
  var preview_colors_default = StylesPreviewColors;

  // packages/global-styles-ui/build-module/variations/variations-color.mjs
  var import_jsx_runtime330 = __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_runtime330.jsxs)(import_components130.__experimentalVStack, { spacing: 3, children: [
      title && /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(Subtitle, { level: 3, children: title }),
      /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(import_components130.__experimentalGrid, { gap, children: colorVariations.map((variation, index2) => /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(
        Variation,
        {
          variation,
          isPill: true,
          properties: propertiesToFilter2,
          showTooltip: true,
          children: () => /* @__PURE__ */ (0, import_jsx_runtime330.jsx)(preview_colors_default, {})
        },
        index2
      )) })
    ] });
  }

  // packages/global-styles-ui/build-module/color-palette-panel.mjs
  var import_jsx_runtime331 = __toESM(require_jsx_runtime(), 1);
  var mobilePopoverProps = { placement: "bottom-start", offset: 8 };
  function ColorPalettePanel({ name: name2 }) {
    const [themeColors, setThemeColors] = useSetting(
      "color.palette.theme",
      name2
    );
    const [baseThemeColors] = useSetting(
      "color.palette.theme",
      name2,
      "base"
    );
    const [defaultColors, setDefaultColors] = useSetting(
      "color.palette.default",
      name2
    );
    const [baseDefaultColors] = useSetting(
      "color.palette.default",
      name2,
      "base"
    );
    const [customColors, setCustomColors] = useSetting(
      "color.palette.custom",
      name2
    );
    const [defaultPaletteEnabled] = useSetting(
      "color.defaultPalette",
      name2
    );
    const isMobileViewport = (0, import_compose30.useViewportMatch)("small", "<");
    const popoverProps = isMobileViewport ? mobilePopoverProps : void 0;
    const [randomizeThemeColors] = useColorRandomizer(name2);
    return /* @__PURE__ */ (0, import_jsx_runtime331.jsxs)(import_components131.__experimentalVStack, { className: "global-styles-ui-color-palette-panel", spacing: 8, children: [
      /* @__PURE__ */ (0, import_jsx_runtime331.jsxs)(import_components131.__experimentalVStack, { spacing: 4, children: [
        !!themeColors && !!themeColors.length && /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
          import_components131.__experimentalPaletteEdit,
          {
            canReset: themeColors !== baseThemeColors,
            canOnlyChangeValues: true,
            colors: themeColors,
            onChange: setThemeColors,
            paletteLabel: (0, import_i18n169.__)("Theme"),
            paletteLabelHeadingLevel: 3,
            popoverProps
          }
        ),
        window.__experimentalEnableColorRandomizer && themeColors?.length > 0 && randomizeThemeColors && /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
          import_components131.Button,
          {
            __next40pxDefaultSize: true,
            variant: "secondary",
            icon: shuffle_default,
            onClick: randomizeThemeColors,
            children: (0, import_i18n169.__)("Randomize colors")
          }
        )
      ] }),
      !!defaultColors && !!defaultColors.length && !!defaultPaletteEnabled && /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
        import_components131.__experimentalPaletteEdit,
        {
          canReset: defaultColors !== baseDefaultColors,
          canOnlyChangeValues: true,
          colors: defaultColors,
          onChange: setDefaultColors,
          paletteLabel: (0, import_i18n169.__)("Default"),
          paletteLabelHeadingLevel: 3,
          popoverProps
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(
        import_components131.__experimentalPaletteEdit,
        {
          colors: customColors,
          onChange: setCustomColors,
          paletteLabel: (0, import_i18n169.__)("Custom"),
          paletteLabelHeadingLevel: 3,
          slugPrefix: "custom-",
          popoverProps
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime331.jsx)(ColorVariations, { title: (0, import_i18n169.__)("Palettes") })
    ] });
  }

  // packages/global-styles-ui/build-module/gradients-palette-panel.mjs
  var import_compose31 = __toESM(require_compose(), 1);
  var import_components132 = __toESM(require_components(), 1);
  var import_i18n170 = __toESM(require_i18n(), 1);
  var import_jsx_runtime332 = __toESM(require_jsx_runtime(), 1);
  var mobilePopoverProps2 = { placement: "bottom-start", offset: 8 };
  var noop9 = () => {
  };
  function GradientPalettePanel({
    name: name2
  }) {
    const [themeGradients, setThemeGradients] = useSetting(
      "color.gradients.theme",
      name2
    );
    const [baseThemeGradients] = useSetting(
      "color.gradients.theme",
      name2,
      "base"
    );
    const [defaultGradients, setDefaultGradients] = useSetting(
      "color.gradients.default",
      name2
    );
    const [baseDefaultGradients] = useSetting(
      "color.gradients.default",
      name2,
      "base"
    );
    const [customGradients, setCustomGradients] = useSetting(
      "color.gradients.custom",
      name2
    );
    const [defaultPaletteEnabled] = useSetting(
      "color.defaultGradients",
      name2
    );
    const [customDuotone] = useSetting("color.duotone.custom") || [];
    const [defaultDuotone] = useSetting("color.duotone.default") || [];
    const [themeDuotone] = useSetting("color.duotone.theme") || [];
    const [defaultDuotoneEnabled] = useSetting("color.defaultDuotone");
    const duotonePalette = [
      ...customDuotone || [],
      ...themeDuotone || [],
      ...defaultDuotone && defaultDuotoneEnabled ? defaultDuotone : []
    ];
    const isMobileViewport = (0, import_compose31.useViewportMatch)("small", "<");
    const popoverProps = isMobileViewport ? mobilePopoverProps2 : void 0;
    return /* @__PURE__ */ (0, import_jsx_runtime332.jsxs)(
      import_components132.__experimentalVStack,
      {
        className: "global-styles-ui-gradient-palette-panel",
        spacing: 8,
        children: [
          !!themeGradients && !!themeGradients.length && /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(
            import_components132.__experimentalPaletteEdit,
            {
              canReset: themeGradients !== baseThemeGradients,
              canOnlyChangeValues: true,
              gradients: themeGradients,
              onChange: setThemeGradients,
              paletteLabel: (0, import_i18n170.__)("Theme"),
              paletteLabelHeadingLevel: 3,
              popoverProps
            }
          ),
          !!defaultGradients && !!defaultGradients.length && !!defaultPaletteEnabled && /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(
            import_components132.__experimentalPaletteEdit,
            {
              canReset: defaultGradients !== baseDefaultGradients,
              canOnlyChangeValues: true,
              gradients: defaultGradients,
              onChange: setDefaultGradients,
              paletteLabel: (0, import_i18n170.__)("Default"),
              paletteLabelHeadingLevel: 3,
              popoverProps
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(
            import_components132.__experimentalPaletteEdit,
            {
              gradients: customGradients,
              onChange: setCustomGradients,
              paletteLabel: (0, import_i18n170.__)("Custom"),
              paletteLabelHeadingLevel: 3,
              slugPrefix: "custom-",
              popoverProps
            }
          ),
          !!duotonePalette && !!duotonePalette.length && /* @__PURE__ */ (0, import_jsx_runtime332.jsxs)("div", { children: [
            /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(Subtitle, { level: 3, children: (0, import_i18n170.__)("Duotone") }),
            /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(import_components132.__experimentalSpacer, { margin: 3 }),
            /* @__PURE__ */ (0, import_jsx_runtime332.jsx)(
              import_components132.DuotonePicker,
              {
                duotonePalette,
                disableCustomDuotone: true,
                disableCustomColors: true,
                clearable: false,
                onChange: noop9,
                colorPalette: []
              }
            )
          ] })
        ]
      }
    );
  }

  // packages/global-styles-ui/build-module/screen-color-palette.mjs
  var import_jsx_runtime333 = __toESM(require_jsx_runtime(), 1);
  function ScreenColorPalette({ name: name2 }) {
    return /* @__PURE__ */ (0, import_jsx_runtime333.jsxs)(import_jsx_runtime333.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(
        ScreenHeader,
        {
          title: (0, import_i18n171.__)("Edit palette"),
          description: (0, import_i18n171.__)(
            "The combination of colors used across the site and in color pickers."
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime333.jsxs)(tabs_exports.Root, { defaultValue: "color", children: [
        /* @__PURE__ */ (0, import_jsx_runtime333.jsx)("div", { className: "global-styles-ui-color-palette__tablist-container", children: /* @__PURE__ */ (0, import_jsx_runtime333.jsxs)(tabs_exports.List, { className: "global-styles-ui-color-palette__tablist", children: [
          /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(tabs_exports.Tab, { value: "color", children: (0, import_i18n171.__)("Color") }),
          /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(tabs_exports.Tab, { value: "gradient", children: (0, import_i18n171.__)("Gradient") })
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(tabs_exports.Panel, { value: "color", tabIndex: -1, children: /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(ColorPalettePanel, { name: name2 }) }),
        /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(tabs_exports.Panel, { value: "gradient", tabIndex: -1, children: /* @__PURE__ */ (0, import_jsx_runtime333.jsx)(GradientPalettePanel, { name: name2 }) })
      ] })
    ] });
  }
  var screen_color_palette_default = ScreenColorPalette;

  // packages/global-styles-ui/build-module/screen-background.mjs
  var import_i18n172 = __toESM(require_i18n(), 1);
  var import_block_editor13 = __toESM(require_block_editor(), 1);
  var import_components133 = __toESM(require_components(), 1);

  // packages/global-styles-ui/build-module/background-panel.mjs
  var import_block_editor12 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime334 = __toESM(require_jsx_runtime(), 1);
  var BACKGROUND_DEFAULT_VALUES = {
    backgroundSize: "auto"
  };
  var { BackgroundPanel: StylesBackgroundPanel2 } = unlock7(
    import_block_editor12.privateApis
  );
  function BackgroundPanel() {
    const [style] = useStyle("", void 0, "user", false);
    const [inheritedStyle, setStyle2] = useStyle(
      "",
      void 0,
      "merged",
      false
    );
    const [settings] = useSetting("");
    return /* @__PURE__ */ (0, import_jsx_runtime334.jsx)(
      StylesBackgroundPanel2,
      {
        inheritedValue: inheritedStyle,
        value: style,
        onChange: setStyle2,
        settings,
        defaultValues: BACKGROUND_DEFAULT_VALUES,
        showInheritanceLabelIndicators: false
      }
    );
  }

  // packages/global-styles-ui/build-module/screen-background.mjs
  var import_jsx_runtime335 = __toESM(require_jsx_runtime(), 1);
  var { useHasBackgroundPanel: useHasBackgroundPanel4 } = unlock7(import_block_editor13.privateApis);
  function ScreenBackground() {
    const [settings] = useSetting("");
    const hasBackgroundPanel = useHasBackgroundPanel4(settings);
    return /* @__PURE__ */ (0, import_jsx_runtime335.jsxs)(import_jsx_runtime335.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime335.jsx)(
        ScreenHeader,
        {
          title: (0, import_i18n172.__)("Background"),
          description: /* @__PURE__ */ (0, import_jsx_runtime335.jsx)(import_components133.__experimentalText, { children: (0, import_i18n172.__)("Set styles for the site's background.") })
        }
      ),
      hasBackgroundPanel && /* @__PURE__ */ (0, import_jsx_runtime335.jsx)(BackgroundPanel, {})
    ] });
  }
  var screen_background_default = ScreenBackground;

  // packages/global-styles-ui/build-module/shadows-panel.mjs
  var import_components135 = __toESM(require_components(), 1);
  var import_i18n174 = __toESM(require_i18n(), 1);
  var import_element188 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/confirm-reset-shadow-dialog.mjs
  var import_components134 = __toESM(require_components(), 1);
  var import_i18n173 = __toESM(require_i18n(), 1);
  var import_jsx_runtime336 = __toESM(require_jsx_runtime(), 1);
  function ConfirmResetShadowDialog({
    text,
    confirmButtonText,
    isOpen: isOpen2,
    toggleOpen,
    onConfirm
  }) {
    const handleConfirm = async () => {
      toggleOpen();
      onConfirm();
    };
    const handleCancel = () => {
      toggleOpen();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime336.jsx)(
      import_components134.__experimentalConfirmDialog,
      {
        isOpen: isOpen2,
        cancelButtonText: (0, import_i18n173.__)("Cancel"),
        confirmButtonText,
        onCancel: handleCancel,
        onConfirm: handleConfirm,
        size: "medium",
        children: text
      }
    );
  }
  var confirm_reset_shadow_dialog_default = ConfirmResetShadowDialog;

  // packages/global-styles-ui/build-module/shadows-panel.mjs
  var import_jsx_runtime337 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu6 } = unlock7(import_components135.privateApis);
  var defaultShadow = "6px 6px 9px rgba(0, 0, 0, 0.2)";
  function ShadowsPanel() {
    const [defaultShadows] = useSetting("shadow.presets.default");
    const [defaultShadowsEnabled] = useSetting("shadow.defaultPresets");
    const [themeShadows] = useSetting("shadow.presets.theme");
    const [customShadows, setCustomShadows] = useSetting(
      "shadow.presets.custom"
    );
    const onCreateShadow = (shadow) => {
      setCustomShadows([...customShadows || [], shadow]);
    };
    const handleResetShadows = () => {
      setCustomShadows([]);
    };
    const [isResetDialogOpen, setIsResetDialogOpen] = (0, import_element188.useState)(false);
    const toggleResetDialog = () => setIsResetDialogOpen(!isResetDialogOpen);
    return /* @__PURE__ */ (0, import_jsx_runtime337.jsxs)(import_jsx_runtime337.Fragment, { children: [
      isResetDialogOpen && /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
        confirm_reset_shadow_dialog_default,
        {
          text: (0, import_i18n174.__)(
            "Are you sure you want to remove all custom shadows?"
          ),
          confirmButtonText: (0, import_i18n174.__)("Remove"),
          isOpen: isResetDialogOpen,
          toggleOpen: toggleResetDialog,
          onConfirm: handleResetShadows
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
        ScreenHeader,
        {
          title: (0, import_i18n174.__)("Shadows"),
          description: (0, import_i18n174.__)(
            "Manage and create shadow styles for use across the site."
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(ScreenBody, { children: /* @__PURE__ */ (0, import_jsx_runtime337.jsxs)(
        import_components135.__experimentalVStack,
        {
          className: "global-styles-ui__shadows-panel",
          spacing: 7,
          children: [
            defaultShadowsEnabled && /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
              ShadowList,
              {
                label: (0, import_i18n174.__)("Default"),
                shadows: defaultShadows || [],
                category: "default"
              }
            ),
            themeShadows && themeShadows.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
              ShadowList,
              {
                label: (0, import_i18n174.__)("Theme"),
                shadows: themeShadows || [],
                category: "theme"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
              ShadowList,
              {
                label: (0, import_i18n174.__)("Custom"),
                shadows: customShadows || [],
                category: "custom",
                canCreate: true,
                onCreate: onCreateShadow,
                onReset: toggleResetDialog
              }
            )
          ]
        }
      ) })
    ] });
  }
  function ShadowList({
    label,
    shadows,
    category,
    canCreate,
    onCreate,
    onReset
  }) {
    const handleAddShadow = () => {
      const newIndex = getNewIndexFromPresets(shadows, "shadow-");
      onCreate?.({
        name: (0, import_i18n174.sprintf)(
          /* translators: %d: is an index for a preset */
          (0, import_i18n174.__)("Shadow %d"),
          newIndex
        ),
        shadow: defaultShadow,
        slug: `shadow-${newIndex}`
      });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime337.jsxs)(import_components135.__experimentalVStack, { spacing: 2, children: [
      /* @__PURE__ */ (0, import_jsx_runtime337.jsxs)(import_components135.__experimentalHStack, { justify: "space-between", children: [
        /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(Subtitle, { level: 3, children: label }),
        /* @__PURE__ */ (0, import_jsx_runtime337.jsxs)(import_components135.FlexItem, { className: "global-styles-ui__shadows-panel__options-container", children: [
          canCreate && /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
            import_components135.Button,
            {
              size: "small",
              icon: plus_default,
              label: (0, import_i18n174.__)("Add shadow"),
              onClick: () => {
                handleAddShadow();
              }
            }
          ),
          !!shadows?.length && category === "custom" && /* @__PURE__ */ (0, import_jsx_runtime337.jsxs)(Menu6, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
              Menu6.TriggerButton,
              {
                render: /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
                  import_components135.Button,
                  {
                    size: "small",
                    icon: more_vertical_default,
                    label: (0, import_i18n174.__)("Shadow options")
                  }
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(Menu6.Popover, { children: /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(Menu6.Item, { onClick: onReset, children: /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(Menu6.ItemLabel, { children: (0, import_i18n174.__)("Remove all custom shadows") }) }) })
          ] })
        ] })
      ] }),
      shadows.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(import_components135.__experimentalItemGroup, { isBordered: true, isSeparated: true, children: shadows.map((shadow) => /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
        ShadowItem,
        {
          shadow,
          category
        },
        shadow.slug
      )) })
    ] });
  }
  function ShadowItem({ shadow, category }) {
    return /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(
      NavigationButtonAsItem,
      {
        path: `/shadows/edit/${category}/${shadow.slug}`,
        children: /* @__PURE__ */ (0, import_jsx_runtime337.jsxs)(import_components135.__experimentalHStack, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(import_components135.FlexItem, { children: shadow.name }),
          /* @__PURE__ */ (0, import_jsx_runtime337.jsx)(icon_default, { icon: (0, import_i18n174.isRTL)() ? chevron_left_default : chevron_right_default })
        ] })
      }
    );
  }

  // packages/global-styles-ui/build-module/shadows-edit-panel.mjs
  var import_components136 = __toESM(require_components(), 1);
  var import_i18n175 = __toESM(require_i18n(), 1);
  var import_element189 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/shadow-utils.mjs
  function getShadowParts(shadow) {
    const shadowValues = shadow.match(/(?:[^,(]|\([^)]*\))+/g) || [];
    return shadowValues.map((value) => value.trim());
  }
  function shadowStringToObject(shadowValue) {
    const defaultShadow2 = {
      x: "0",
      y: "0",
      blur: "0",
      spread: "0",
      color: "#000",
      inset: false
    };
    if (!shadowValue) {
      return defaultShadow2;
    }
    if (shadowValue.includes("none")) {
      return defaultShadow2;
    }
    const lengthsRegex = /((?:^|\s+)(-?\d*\.?\d+(?:px|%|in|cm|mm|em|rem|ex|pt|pc|vh|vw|vmin|vmax|ch|lh)?)(?=\s|$)(?![^(]*\))){1,4}/g;
    const matches = shadowValue.match(lengthsRegex) || [];
    if (matches.length !== 1) {
      return defaultShadow2;
    }
    const lengths = matches[0].split(" ").map((value) => value.trim()).filter((value) => value);
    if (lengths.length < 2) {
      return defaultShadow2;
    }
    const insets = shadowValue.match(/inset/gi) || [];
    if (insets.length > 1) {
      return defaultShadow2;
    }
    const hasInset = insets.length === 1;
    let colorString = shadowValue.replace(lengthsRegex, "").trim();
    if (hasInset) {
      colorString = colorString.replace("inset", "").replace("INSET", "").trim();
    }
    const colorRegex2 = /^#([0-9a-f]{3}){1,2}$|^#([0-9a-f]{4}){1,2}$|^(?:rgb|hsl)a?\(?[\d*\.?\d+%?,?\/?\s]*\)$/gi;
    let colorMatches = (colorString.match(colorRegex2) || []).map((value) => value?.trim()).filter((value) => value);
    if (colorMatches.length > 1) {
      return defaultShadow2;
    } else if (colorMatches.length === 0) {
      colorMatches = colorString.trim().split(" ").filter((value) => value);
      if (colorMatches.length > 1) {
        return defaultShadow2;
      }
    }
    const [x2, y3, blur, spread] = lengths;
    return {
      x: x2,
      y: y3,
      blur: blur || defaultShadow2.blur,
      spread: spread || defaultShadow2.spread,
      inset: hasInset,
      color: colorString || defaultShadow2.color
    };
  }
  function shadowObjectToString(shadowObj) {
    const shadowString = `${shadowObj.x || "0px"} ${shadowObj.y || "0px"} ${shadowObj.blur || "0px"} ${shadowObj.spread || "0px"}`;
    return `${shadowObj.inset ? "inset" : ""} ${shadowString} ${shadowObj.color || ""}`.trim();
  }

  // packages/global-styles-ui/build-module/shadows-edit-panel.mjs
  var import_jsx_runtime338 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu7 } = unlock7(import_components136.privateApis);
  var customShadowMenuItems = [
    {
      label: (0, import_i18n175.__)("Rename"),
      action: "rename"
    },
    {
      label: (0, import_i18n175.__)("Delete"),
      action: "delete"
    }
  ];
  var presetShadowMenuItems = [
    {
      label: (0, import_i18n175.__)("Reset"),
      action: "reset"
    }
  ];
  function ShadowsEditPanel() {
    const { goBack, params } = (0, import_components136.useNavigator)();
    const { category, slug } = params;
    const [shadows, setShadows] = useSetting(
      `shadow.presets.${category}`
    );
    (0, import_element189.useEffect)(() => {
      const hasCurrentShadow = shadows?.some(
        (shadow) => shadow.slug === slug
      );
      if (!!slug && !hasCurrentShadow) {
        goBack();
      }
    }, [shadows, slug, goBack]);
    const [baseShadows] = useSetting(
      `shadow.presets.${category}`,
      void 0,
      "base"
    );
    const [selectedShadow, setSelectedShadow] = (0, import_element189.useState)(
      () => (shadows || []).find((shadow) => shadow.slug === slug)
    );
    const baseSelectedShadow = (0, import_element189.useMemo)(
      () => (baseShadows || []).find((b3) => b3.slug === slug),
      [baseShadows, slug]
    );
    const [isConfirmDialogVisible, setIsConfirmDialogVisible] = (0, import_element189.useState)(false);
    const [isRenameModalVisible, setIsRenameModalVisible] = (0, import_element189.useState)(false);
    const [shadowName, setShadowName] = (0, import_element189.useState)(
      selectedShadow?.name
    );
    if (!category || !slug) {
      return null;
    }
    const onShadowChange = (shadow) => {
      setSelectedShadow({ ...selectedShadow, shadow });
      const updatedShadows = shadows.map(
        (s3) => s3.slug === slug ? { ...selectedShadow, shadow } : s3
      );
      setShadows(updatedShadows);
    };
    const onMenuClick = (action) => {
      if (action === "reset") {
        const updatedShadows = shadows.map(
          (s3) => s3.slug === slug ? baseSelectedShadow : s3
        );
        setSelectedShadow(baseSelectedShadow);
        setShadows(updatedShadows);
      } else if (action === "delete") {
        setIsConfirmDialogVisible(true);
      } else if (action === "rename") {
        setIsRenameModalVisible(true);
      }
    };
    const handleShadowDelete = () => {
      setShadows(shadows.filter((s3) => s3.slug !== slug));
    };
    const handleShadowRename = (newName) => {
      if (!newName) {
        return;
      }
      const updatedShadows = shadows.map(
        (s3) => s3.slug === slug ? { ...selectedShadow, name: newName } : s3
      );
      setSelectedShadow({ ...selectedShadow, name: newName });
      setShadows(updatedShadows);
    };
    return !selectedShadow ? /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(ScreenHeader, { title: "" }) : /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(import_jsx_runtime338.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(import_components136.__experimentalHStack, { justify: "space-between", children: [
        /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(ScreenHeader, { title: selectedShadow.name }),
        /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_components136.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_components136.__experimentalSpacer, { marginTop: 2, marginBottom: 0, paddingX: 4, children: /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(Menu7, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
            Menu7.TriggerButton,
            {
              render: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
                import_components136.Button,
                {
                  size: "small",
                  icon: more_vertical_default,
                  label: (0, import_i18n175.__)("Menu")
                }
              )
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(Menu7.Popover, { children: (category === "custom" ? customShadowMenuItems : presetShadowMenuItems).map((item) => /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
            Menu7.Item,
            {
              onClick: () => onMenuClick(item.action),
              disabled: item.action === "reset" && selectedShadow.shadow === baseSelectedShadow?.shadow,
              children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(Menu7.ItemLabel, { children: item.label })
            },
            item.action
          )) })
        ] }) }) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(ScreenBody, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(ShadowsPreview, { shadow: selectedShadow.shadow }),
        /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
          ShadowEditor,
          {
            shadow: selectedShadow.shadow,
            onChange: onShadowChange
          }
        )
      ] }),
      isConfirmDialogVisible && /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
        import_components136.__experimentalConfirmDialog,
        {
          isOpen: true,
          onConfirm: () => {
            handleShadowDelete();
            setIsConfirmDialogVisible(false);
          },
          onCancel: () => {
            setIsConfirmDialogVisible(false);
          },
          confirmButtonText: (0, import_i18n175.__)("Delete"),
          size: "medium",
          children: (0, import_i18n175.sprintf)(
            /* translators: %s: Name of the shadow preset. */
            (0, import_i18n175.__)(
              'Are you sure you want to delete "%s" shadow preset?'
            ),
            selectedShadow.name
          )
        }
      ),
      isRenameModalVisible && /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
        import_components136.Modal,
        {
          title: (0, import_i18n175.__)("Rename"),
          onRequestClose: () => setIsRenameModalVisible(false),
          size: "small",
          children: /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(
            "form",
            {
              onSubmit: (event) => {
                event.preventDefault();
                handleShadowRename(shadowName);
                setIsRenameModalVisible(false);
              },
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
                  import_components136.__experimentalInputControl,
                  {
                    autoComplete: "off",
                    label: (0, import_i18n175.__)("Name"),
                    placeholder: (0, import_i18n175.__)("Shadow name"),
                    value: shadowName ?? "",
                    onChange: setShadowName
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_components136.__experimentalSpacer, { marginBottom: 6 }),
                /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(
                  import_components136.Flex,
                  {
                    className: "block-editor-shadow-edit-modal__actions",
                    justify: "flex-end",
                    expanded: false,
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_components136.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
                        import_components136.Button,
                        {
                          __next40pxDefaultSize: true,
                          variant: "tertiary",
                          onClick: () => setIsRenameModalVisible(false),
                          children: (0, import_i18n175.__)("Cancel")
                        }
                      ) }),
                      /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_components136.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
                        import_components136.Button,
                        {
                          __next40pxDefaultSize: true,
                          variant: "primary",
                          type: "submit",
                          children: (0, import_i18n175.__)("Save")
                        }
                      ) })
                    ]
                  }
                )
              ]
            }
          )
        }
      )
    ] });
  }
  function ShadowsPreview({ shadow }) {
    const shadowStyle = {
      boxShadow: shadow
    };
    return /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_components136.__experimentalSpacer, { marginBottom: 4, marginTop: -2, children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
      import_components136.__experimentalHStack,
      {
        alignment: "center",
        justify: "center",
        className: "global-styles-ui__shadow-preview-panel",
        children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
          "div",
          {
            className: "global-styles-ui__shadow-preview-block",
            style: shadowStyle
          }
        )
      }
    ) });
  }
  function ShadowEditor({ shadow, onChange }) {
    const addShadowButtonRef = (0, import_element189.useRef)(null);
    const shadowParts = (0, import_element189.useMemo)(() => getShadowParts(shadow), [shadow]);
    const onChangeShadowPart = (index2, part) => {
      const newShadowParts = [...shadowParts];
      newShadowParts[index2] = part;
      onChange(newShadowParts.join(", "));
    };
    const onAddShadowPart = () => {
      onChange([...shadowParts, defaultShadow].join(", "));
    };
    const onRemoveShadowPart = (index2) => {
      onChange(shadowParts.filter((p4, i3) => i3 !== index2).join(", "));
      addShadowButtonRef.current?.focus();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(import_jsx_runtime338.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_components136.__experimentalVStack, { spacing: 2, children: /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(import_components136.__experimentalHStack, { justify: "space-between", children: [
        /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(Subtitle, { level: 3, children: (0, import_i18n175.__)("Shadows") }),
        /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_components136.FlexItem, { className: "global-styles-ui__shadows-panel__options-container", children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
          import_components136.Button,
          {
            size: "small",
            icon: plus_default,
            label: (0, import_i18n175.__)("Add shadow"),
            onClick: () => {
              onAddShadowPart();
            },
            ref: addShadowButtonRef
          }
        ) })
      ] }) }),
      /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_components136.__experimentalSpacer, {}),
      /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(import_components136.__experimentalItemGroup, { isBordered: true, isSeparated: true, children: shadowParts.map((part, index2) => /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
        ShadowItem2,
        {
          shadow: part,
          onChange: (value) => onChangeShadowPart(index2, value),
          canRemove: shadowParts.length > 1,
          onRemove: () => onRemoveShadowPart(index2)
        },
        index2
      )) })
    ] });
  }
  function ShadowItem2({
    shadow,
    onChange,
    canRemove,
    onRemove
  }) {
    const popoverProps = {
      placement: "left-start",
      offset: 36,
      shift: true
    };
    const shadowObj = (0, import_element189.useMemo)(
      () => shadowStringToObject(shadow),
      [shadow]
    );
    const onShadowChange = (newShadow) => {
      onChange(shadowObjectToString(newShadow));
    };
    return /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
      import_components136.Dropdown,
      {
        popoverProps,
        className: "global-styles-ui__shadow-editor__dropdown",
        renderToggle: ({ onToggle, isOpen: isOpen2 }) => {
          const toggleProps = {
            onClick: onToggle,
            className: clsx_default(
              "global-styles-ui__shadow-editor__dropdown-toggle",
              { "is-open": isOpen2 }
            ),
            "aria-expanded": isOpen2
          };
          const removeButtonProps = {
            onClick: () => {
              if (isOpen2) {
                onToggle();
              }
              onRemove();
            },
            className: clsx_default(
              "global-styles-ui__shadow-editor__remove-button",
              { "is-open": isOpen2 }
            ),
            label: (0, import_i18n175.__)("Remove shadow")
          };
          return /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(import_jsx_runtime338.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
              import_components136.Button,
              {
                __next40pxDefaultSize: true,
                icon: shadow_default,
                ...toggleProps,
                children: shadowObj.inset ? (0, import_i18n175.__)("Inner shadow") : (0, import_i18n175.__)("Drop shadow")
              }
            ),
            canRemove && /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
              import_components136.Button,
              {
                size: "small",
                icon: reset_default,
                ...removeButtonProps
              }
            )
          ] });
        },
        renderContent: () => /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
          import_components136.__experimentalDropdownContentWrapper,
          {
            paddingSize: "medium",
            className: "global-styles-ui__shadow-editor__dropdown-content",
            children: /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
              ShadowPopover,
              {
                shadowObj,
                onChange: onShadowChange
              }
            )
          }
        )
      }
    );
  }
  function ShadowPopover({ shadowObj, onChange }) {
    const __experimentalIsRenderedInSidebar = true;
    const enableAlpha = true;
    const onShadowChange = (key, value) => {
      const newShadow = {
        ...shadowObj,
        [key]: value
      };
      onChange(newShadow);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(import_components136.__experimentalVStack, { spacing: 4, className: "global-styles-ui__shadow-editor-panel", children: [
      /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
        import_components136.ColorPalette,
        {
          clearable: false,
          enableAlpha,
          __experimentalIsRenderedInSidebar,
          value: shadowObj.color,
          onChange: (value) => onShadowChange("color", value)
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(
        import_components136.__experimentalToggleGroupControl,
        {
          label: (0, import_i18n175.__)("Shadow Type"),
          value: shadowObj.inset ? "inset" : "outset",
          isBlock: true,
          onChange: (value) => onShadowChange("inset", value === "inset"),
          hideLabelFromVision: true,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
              import_components136.__experimentalToggleGroupControlOption,
              {
                value: "outset",
                label: (0, import_i18n175.__)("Outset")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
              import_components136.__experimentalToggleGroupControlOption,
              {
                value: "inset",
                label: (0, import_i18n175.__)("Inset")
              }
            )
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime338.jsxs)(import_components136.__experimentalGrid, { columns: 2, gap: 4, children: [
        /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
          ShadowInputControl,
          {
            label: (0, import_i18n175.__)("X Position"),
            value: shadowObj.x,
            onChange: (value) => onShadowChange("x", value)
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
          ShadowInputControl,
          {
            label: (0, import_i18n175.__)("Y Position"),
            value: shadowObj.y,
            onChange: (value) => onShadowChange("y", value)
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
          ShadowInputControl,
          {
            label: (0, import_i18n175.__)("Blur"),
            value: shadowObj.blur,
            onChange: (value) => onShadowChange("blur", value)
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
          ShadowInputControl,
          {
            label: (0, import_i18n175.__)("Spread"),
            value: shadowObj.spread,
            onChange: (value) => onShadowChange("spread", value)
          }
        )
      ] })
    ] });
  }
  function ShadowInputControl({
    label,
    value,
    onChange
  }) {
    const onValueChange = (next) => {
      const isNumeric = next !== void 0 && !isNaN(parseFloat(next));
      const nextValue = isNumeric ? next : "0px";
      onChange(nextValue);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime338.jsx)(
      import_components136.__experimentalUnitControl,
      {
        label,
        value,
        onChange: onValueChange
      }
    );
  }

  // packages/global-styles-ui/build-module/screen-shadows.mjs
  var import_jsx_runtime339 = __toESM(require_jsx_runtime(), 1);
  function ScreenShadows() {
    return /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(ShadowsPanel, {});
  }
  function ScreenShadowsEdit() {
    return /* @__PURE__ */ (0, import_jsx_runtime339.jsx)(ShadowsEditPanel, {});
  }

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

  // packages/global-styles-ui/build-module/dimensions-panel.mjs
  var import_block_editor14 = __toESM(require_block_editor(), 1);
  var import_element190 = __toESM(require_element(), 1);
  var import_jsx_runtime340 = __toESM(require_jsx_runtime(), 1);
  var { useSettingsForBlockElement: useSettingsForBlockElement6, DimensionsPanel: StylesDimensionsPanel2 } = unlock7(import_block_editor14.privateApis);
  var DEFAULT_CONTROLS = {
    contentSize: true,
    wideSize: true,
    padding: true,
    margin: true,
    blockGap: true,
    height: true,
    minHeight: true,
    minWidth: true,
    width: true,
    childLayout: false
  };
  function DimensionsPanel() {
    const [style] = useStyle("", void 0, "user", false);
    const [inheritedStyle, setStyle2] = useStyle(
      "",
      void 0,
      "merged",
      false
    );
    const [userSettings] = useSetting("", void 0, "user");
    const [rawSettings, setSettings] = useSetting("");
    const settings = useSettingsForBlockElement6(rawSettings);
    const inheritedStyleWithLayout = (0, import_element190.useMemo)(() => {
      return {
        ...inheritedStyle,
        layout: settings.layout
      };
    }, [inheritedStyle, settings.layout]);
    const styleWithLayout = (0, import_element190.useMemo)(() => {
      return {
        ...style,
        layout: userSettings.layout
      };
    }, [style, userSettings.layout]);
    const onChange = (newStyle) => {
      const updatedStyle = { ...newStyle };
      delete updatedStyle.layout;
      setStyle2(updatedStyle);
      if (newStyle.layout !== userSettings.layout) {
        const updatedSettings = {
          ...userSettings,
          layout: newStyle.layout
        };
        if (updatedSettings.layout?.definitions) {
          delete updatedSettings.layout.definitions;
        }
        setSettings(updatedSettings);
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime340.jsx)(
      StylesDimensionsPanel2,
      {
        inheritedValue: inheritedStyleWithLayout,
        value: styleWithLayout,
        onChange,
        settings,
        includeLayoutControls: true,
        defaultControls: DEFAULT_CONTROLS,
        showInheritanceLabelIndicators: false
      }
    );
  }

  // packages/global-styles-ui/build-module/screen-layout.mjs
  var import_jsx_runtime341 = __toESM(require_jsx_runtime(), 1);
  var { useHasDimensionsPanel: useHasDimensionsPanel4, useSettingsForBlockElement: useSettingsForBlockElement7 } = unlock7(
    import_block_editor15.privateApis
  );
  function ScreenLayout() {
    const [rawSettings] = useSetting("");
    const settings = useSettingsForBlockElement7(rawSettings);
    const hasDimensionsPanel = useHasDimensionsPanel4(settings);
    return /* @__PURE__ */ (0, import_jsx_runtime341.jsxs)(import_jsx_runtime341.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime341.jsx)(ScreenHeader, { title: (0, import_i18n176.__)("Layout") }),
      hasDimensionsPanel && /* @__PURE__ */ (0, import_jsx_runtime341.jsx)(DimensionsPanel, {})
    ] });
  }
  var screen_layout_default = ScreenLayout;

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

  // packages/global-styles-ui/build-module/style-variations-content.mjs
  var import_i18n178 = __toESM(require_i18n(), 1);
  var import_components138 = __toESM(require_components(), 1);

  // packages/global-styles-ui/build-module/style-variations-container.mjs
  var import_core_data40 = __toESM(require_core_data(), 1);
  var import_data58 = __toESM(require_data(), 1);
  var import_element191 = __toESM(require_element(), 1);
  var import_components137 = __toESM(require_components(), 1);
  var import_i18n177 = __toESM(require_i18n(), 1);
  var import_jsx_runtime342 = __toESM(require_jsx_runtime(), 1);
  function StyleVariationsContainer({
    gap = 2
  }) {
    const { user } = (0, import_element191.useContext)(GlobalStylesContext);
    const userStyles = user?.styles;
    const variations = (0, import_data58.useSelect)((select9) => {
      const result = select9(
        import_core_data40.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_element191.useMemo)(() => {
      const withEmptyVariation = [
        {
          title: (0, import_i18n177.__)("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_runtime342.jsx)(
      import_components137.__experimentalGrid,
      {
        columns: 2,
        className: "global-styles-ui-style-variations-container",
        gap,
        children: themeVariations.map(
          (variation, index2) => /* @__PURE__ */ (0, import_jsx_runtime342.jsx)(Variation, { variation, children: (isFocused) => /* @__PURE__ */ (0, import_jsx_runtime342.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_runtime343 = __toESM(require_jsx_runtime(), 1);
  function StyleVariationsContent() {
    const gap = 3;
    return /* @__PURE__ */ (0, import_jsx_runtime343.jsxs)(import_components138.__experimentalVStack, { spacing: 10, className: "global-styles-ui-variation-container", children: [
      /* @__PURE__ */ (0, import_jsx_runtime343.jsx)(style_variations_container_default, { gap }),
      /* @__PURE__ */ (0, import_jsx_runtime343.jsx)(ColorVariations, { title: (0, import_i18n178.__)("Color Variations"), gap }),
      /* @__PURE__ */ (0, import_jsx_runtime343.jsx)(TypographyVariations, { title: (0, import_i18n178.__)("Typography"), gap })
    ] });
  }

  // packages/global-styles-ui/build-module/screen-style-variations.mjs
  var import_jsx_runtime344 = __toESM(require_jsx_runtime(), 1);
  function ScreenStyleVariations() {
    return /* @__PURE__ */ (0, import_jsx_runtime344.jsxs)(import_jsx_runtime344.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime344.jsx)(
        ScreenHeader,
        {
          title: (0, import_i18n179.__)("Browse styles"),
          description: (0, import_i18n179.__)(
            "Choose a variation to change the look of the site."
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime344.jsx)(
        import_components139.Card,
        {
          size: "small",
          isBorderless: true,
          className: "global-styles-ui-screen-style-variations",
          children: /* @__PURE__ */ (0, import_jsx_runtime344.jsx)(import_components139.CardBody, { children: /* @__PURE__ */ (0, import_jsx_runtime344.jsx)(StyleVariationsContent, {}) })
        }
      )
    ] });
  }
  var screen_style_variations_default = ScreenStyleVariations;

  // packages/global-styles-ui/build-module/screen-css.mjs
  var import_i18n180 = __toESM(require_i18n(), 1);
  var import_components140 = __toESM(require_components(), 1);
  var import_block_editor16 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime345 = __toESM(require_jsx_runtime(), 1);
  var { AdvancedPanel: StylesAdvancedPanel2 } = unlock7(import_block_editor16.privateApis);
  function ScreenCSS() {
    const [style] = useStyle("", void 0, "user", false);
    const [inheritedStyle, setStyle2] = useStyle(
      "",
      void 0,
      "merged",
      false
    );
    return /* @__PURE__ */ (0, import_jsx_runtime345.jsxs)(import_jsx_runtime345.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime345.jsx)(
        ScreenHeader,
        {
          title: (0, import_i18n180.__)("Additional CSS"),
          description: /* @__PURE__ */ (0, import_jsx_runtime345.jsxs)(import_jsx_runtime345.Fragment, { children: [
            (0, import_i18n180.__)(
              "You can add custom CSS to further customize the appearance and layout of your site."
            ),
            /* @__PURE__ */ (0, import_jsx_runtime345.jsx)("br", {}),
            /* @__PURE__ */ (0, import_jsx_runtime345.jsx)(
              import_components140.ExternalLink,
              {
                href: (0, import_i18n180.__)(
                  "https://developer.wordpress.org/advanced-administration/wordpress/css/"
                ),
                className: "global-styles-ui-screen-css-help-link",
                children: (0, import_i18n180.__)("Learn more about CSS")
              }
            )
          ] })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime345.jsx)("div", { className: "global-styles-ui-screen-css", children: /* @__PURE__ */ (0, import_jsx_runtime345.jsx)(
        StylesAdvancedPanel2,
        {
          value: style,
          onChange: setStyle2,
          inheritedValue: inheritedStyle
        }
      ) })
    ] });
  }
  var screen_css_default = ScreenCSS;

  // packages/global-styles-ui/build-module/screen-revisions/index.mjs
  var import_i18n183 = __toESM(require_i18n(), 1);
  var import_components143 = __toESM(require_components(), 1);
  var import_element193 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/screen-revisions/use-global-styles-revisions.mjs
  var import_data59 = __toESM(require_data(), 1);
  var import_core_data41 = __toESM(require_core_data(), 1);
  var import_element192 = __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_ARRAY13 = [];
  function useGlobalStylesRevisions({
    query
  } = {}) {
    const { user: userConfig } = (0, import_element192.useContext)(GlobalStylesContext);
    const _query = (0, import_element192.useMemo)(
      () => ({ ...DEFAULT_QUERY, ...query }),
      [query]
    );
    const {
      authors,
      currentUser,
      isDirty,
      revisions,
      isLoadingGlobalStylesRevisions,
      revisionsCount
    } = (0, import_data59.useSelect)(
      (select9) => {
        const {
          __experimentalGetDirtyEntityRecords,
          getCurrentUser,
          getUsers,
          getRevisions,
          __experimentalGetCurrentGlobalStylesId,
          getEntityRecord,
          isResolving
        } = select9(import_core_data41.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_ARRAY13 : EMPTY_ARRAY13;
        const _authors = getUsers(SITE_EDITOR_AUTHORS_QUERY) || EMPTY_ARRAY13;
        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_element192.useMemo)(() => {
      if (!authors.length || isLoadingGlobalStylesRevisions) {
        return {
          revisions: EMPTY_ARRAY13,
          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_i18n181 = __toESM(require_i18n(), 1);
  var import_components141 = __toESM(require_components(), 1);
  var import_date15 = __toESM(require_date(), 1);
  var import_core_data42 = __toESM(require_core_data(), 1);
  var import_data60 = __toESM(require_data(), 1);
  var import_keycodes6 = __toESM(require_keycodes(), 1);
  var import_jsx_runtime346 = __toESM(require_jsx_runtime(), 1);
  var { Badge: WCBadge4 } = unlock7(import_components141.privateApis);
  var DAY_IN_MILLISECONDS = 60 * 60 * 1e3 * 24;
  function ChangesSummary({ revision, previousRevision }) {
    const changes = getGlobalStylesChanges(
      revision,
      previousRevision,
      {
        maxResults: 7
      }
    );
    if (!changes.length) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime346.jsx)(
      "ul",
      {
        "data-testid": "global-styles-revision-changes",
        className: "global-styles-ui-screen-revisions__changes",
        children: changes.map((change) => /* @__PURE__ */ (0, import_jsx_runtime346.jsx)("li", { children: change }, change))
      }
    );
  }
  function getRevisionLabel(id, authorDisplayName, formattedModifiedDate, areStylesEqual) {
    if ("parent" === id) {
      return (0, import_i18n181.__)("Reset the styles to the theme defaults");
    }
    if ("unsaved" === id) {
      return (0, import_i18n181.sprintf)(
        /* translators: %s: author display name */
        (0, import_i18n181.__)("Unsaved changes by %s"),
        authorDisplayName
      );
    }
    return areStylesEqual ? (0, import_i18n181.sprintf)(
      // translators: 1: author display name. 2: revision creation date.
      (0, import_i18n181.__)(
        "Changes saved by %1$s on %2$s. This revision matches current editor styles."
      ),
      authorDisplayName,
      formattedModifiedDate
    ) : (0, import_i18n181.sprintf)(
      // translators: 1: author display name. 2: revision creation date.
      (0, import_i18n181.__)("Changes saved by %1$s on %2$s"),
      authorDisplayName,
      formattedModifiedDate
    );
  }
  function RevisionsButtons({
    userRevisions,
    selectedRevisionId,
    onChange,
    canApplyRevision,
    onApplyRevision
  }) {
    const { currentThemeName, currentUser } = (0, import_data60.useSelect)((select9) => {
      const { getCurrentTheme, getCurrentUser } = select9(import_core_data42.store);
      const currentTheme = getCurrentTheme();
      return {
        currentThemeName: currentTheme?.name?.rendered || currentTheme?.stylesheet,
        currentUser: getCurrentUser()
      };
    }, []);
    const dateNowInMs = (0, import_date15.getDate)(null).getTime();
    const { datetimeAbbreviated } = (0, import_date15.getSettings)().formats;
    return /* @__PURE__ */ (0, import_jsx_runtime346.jsx)(
      import_components141.Composite,
      {
        orientation: "vertical",
        className: "global-styles-ui-screen-revisions__revisions-list",
        "aria-label": (0, import_i18n181.__)("Global styles revisions list"),
        role: "listbox",
        children: userRevisions.map((revision, index2) => {
          const { id, author, modified } = revision;
          const isUnsaved = "unsaved" === id;
          const revisionAuthor = isUnsaved ? currentUser : author;
          const authorDisplayName = revisionAuthor?.name || (0, import_i18n181.__)("User");
          const authorAvatar = revisionAuthor?.avatar_urls?.["48"];
          const isFirstItem = index2 === 0;
          const isSelected2 = selectedRevisionId ? selectedRevisionId === id : isFirstItem;
          const areStylesEqual = !canApplyRevision && isSelected2;
          const isReset = "parent" === id;
          const modifiedString = modified instanceof Date ? modified.toISOString() : modified;
          const modifiedDate = (0, import_date15.getDate)(modifiedString ?? null);
          const displayDate = modifiedString && dateNowInMs - modifiedDate.getTime() > DAY_IN_MILLISECONDS ? (0, import_date15.dateI18n)(datetimeAbbreviated, modifiedDate) : (0, import_date15.humanTimeDiff)(
            modifiedString ?? modifiedDate,
            void 0
          );
          const revisionLabel = getRevisionLabel(
            id,
            authorDisplayName,
            (0, import_date15.dateI18n)(datetimeAbbreviated, modifiedDate),
            areStylesEqual
          );
          return /* @__PURE__ */ (0, import_jsx_runtime346.jsxs)(
            import_components141.Composite.Item,
            {
              className: "global-styles-ui-screen-revisions__revision-item",
              "aria-current": isSelected2,
              role: "option",
              onKeyDown: (event) => {
                const { keyCode } = event;
                if (keyCode === import_keycodes6.ENTER || keyCode === import_keycodes6.SPACE) {
                  onChange(revision);
                }
              },
              onClick: (event) => {
                event.preventDefault();
                onChange(revision);
              },
              "aria-selected": isSelected2,
              "aria-label": revisionLabel,
              render: /* @__PURE__ */ (0, import_jsx_runtime346.jsx)("div", {}),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime346.jsx)("span", { className: "global-styles-ui-screen-revisions__revision-item-wrapper", children: isReset ? /* @__PURE__ */ (0, import_jsx_runtime346.jsxs)("span", { className: "global-styles-ui-screen-revisions__description", children: [
                  (0, import_i18n181.__)("Default styles"),
                  /* @__PURE__ */ (0, import_jsx_runtime346.jsx)("span", { className: "global-styles-ui-screen-revisions__meta", children: currentThemeName })
                ] }) : /* @__PURE__ */ (0, import_jsx_runtime346.jsxs)("span", { className: "global-styles-ui-screen-revisions__description", children: [
                  isUnsaved ? /* @__PURE__ */ (0, import_jsx_runtime346.jsx)("span", { className: "global-styles-ui-screen-revisions__date", children: (0, import_i18n181.__)("(Unsaved)") }) : /* @__PURE__ */ (0, import_jsx_runtime346.jsx)(
                    "time",
                    {
                      className: "global-styles-ui-screen-revisions__date",
                      dateTime: modifiedString,
                      children: displayDate
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime346.jsxs)("span", { className: "global-styles-ui-screen-revisions__meta", children: [
                    /* @__PURE__ */ (0, import_jsx_runtime346.jsx)(
                      "img",
                      {
                        alt: authorDisplayName,
                        src: authorAvatar
                      }
                    ),
                    authorDisplayName
                  ] }),
                  isSelected2 && /* @__PURE__ */ (0, import_jsx_runtime346.jsx)(
                    ChangesSummary,
                    {
                      revision,
                      previousRevision: index2 < userRevisions.length ? userRevisions[index2 + 1] : void 0
                    }
                  )
                ] }) }),
                isSelected2 && (areStylesEqual ? /* @__PURE__ */ (0, import_jsx_runtime346.jsx)(
                  WCBadge4,
                  {
                    className: "global-styles-ui-screen-revisions__active-badge",
                    intent: "info",
                    children: (0, import_i18n181.__)("Active")
                  }
                ) : /* @__PURE__ */ (0, import_jsx_runtime346.jsx)(
                  import_components141.Button,
                  {
                    size: "compact",
                    variant: "primary",
                    className: "global-styles-ui-screen-revisions__apply-button",
                    onClick: onApplyRevision,
                    "aria-label": (0, import_i18n181.__)(
                      "Apply the selected revision to your site."
                    ),
                    children: isReset ? (0, import_i18n181.__)("Reset to defaults") : (0, import_i18n181.__)("Apply")
                  }
                ))
              ]
            },
            id
          );
        })
      }
    );
  }
  var revisions_buttons_default = RevisionsButtons;

  // packages/global-styles-ui/build-module/pagination/index.mjs
  var import_components142 = __toESM(require_components(), 1);
  var import_i18n182 = __toESM(require_i18n(), 1);
  var import_jsx_runtime347 = __toESM(require_jsx_runtime(), 1);
  function Pagination({
    currentPage,
    numPages,
    changePage,
    totalItems,
    className,
    disabled: disabled2 = false,
    buttonVariant = "tertiary",
    label = (0, import_i18n182.__)("Pagination")
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime347.jsxs)(
      import_components142.__experimentalHStack,
      {
        expanded: false,
        as: "nav",
        "aria-label": label,
        spacing: 3,
        justify: "flex-start",
        className: clsx_default("global-styles-ui-pagination", className),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
            import_components142.__experimentalText,
            {
              variant: "muted",
              className: "global-styles-ui-pagination__total",
              children: (0, import_i18n182.sprintf)(
                // translators: %d: Total number of patterns.
                (0, import_i18n182._n)("%d item", "%d items", totalItems),
                totalItems
              )
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime347.jsxs)(import_components142.__experimentalHStack, { expanded: false, spacing: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
              import_components142.Button,
              {
                variant: buttonVariant,
                onClick: () => changePage(1),
                accessibleWhenDisabled: true,
                disabled: disabled2 || currentPage === 1,
                label: (0, import_i18n182.__)("First page"),
                icon: (0, import_i18n182.isRTL)() ? next_default : previous_default,
                size: "compact"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
              import_components142.Button,
              {
                variant: buttonVariant,
                onClick: () => changePage(currentPage - 1),
                accessibleWhenDisabled: true,
                disabled: disabled2 || currentPage === 1,
                label: (0, import_i18n182.__)("Previous page"),
                icon: (0, import_i18n182.isRTL)() ? chevron_right_default : chevron_left_default,
                size: "compact"
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(import_components142.__experimentalText, { variant: "muted", children: (0, import_i18n182.sprintf)(
            // translators: 1: Current page number. 2: Total number of pages.
            (0, import_i18n182._x)("%1$d of %2$d", "paging"),
            currentPage,
            numPages
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime347.jsxs)(import_components142.__experimentalHStack, { expanded: false, spacing: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
              import_components142.Button,
              {
                variant: buttonVariant,
                onClick: () => changePage(currentPage + 1),
                accessibleWhenDisabled: true,
                disabled: disabled2 || currentPage === numPages,
                label: (0, import_i18n182.__)("Next page"),
                icon: (0, import_i18n182.isRTL)() ? chevron_left_default : chevron_right_default,
                size: "compact"
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime347.jsx)(
              import_components142.Button,
              {
                variant: buttonVariant,
                onClick: () => changePage(numPages),
                accessibleWhenDisabled: true,
                disabled: disabled2 || currentPage === numPages,
                label: (0, import_i18n182.__)("Last page"),
                icon: (0, import_i18n182.isRTL)() ? previous_default : next_default,
                size: "compact"
              }
            )
          ] })
        ]
      }
    );
  }

  // packages/global-styles-ui/build-module/screen-revisions/index.mjs
  var import_jsx_runtime348 = __toESM(require_jsx_runtime(), 1);
  var PAGE_SIZE = 10;
  function ScreenRevisions({ onClose } = {}) {
    const { user: currentEditorGlobalStyles, onChange: setUserConfig } = (0, import_element193.useContext)(GlobalStylesContext);
    const { params, goTo } = (0, import_components143.useNavigator)();
    const { revisionId: revisionId2 } = params;
    const [currentPage, setCurrentPage] = (0, import_element193.useState)(1);
    const { revisions, isLoading, hasUnsavedChanges, revisionsCount } = useGlobalStylesRevisions({
      query: {
        per_page: PAGE_SIZE,
        page: currentPage
      }
    });
    const numPages = Math.ceil(revisionsCount / PAGE_SIZE);
    const [
      isLoadingRevisionWithUnsavedChanges,
      setIsLoadingRevisionWithUnsavedChanges
    ] = (0, import_element193.useState)(false);
    const currentlySelectedRevision = (0, import_element193.useMemo)(() => {
      if (!revisionId2) {
        return currentEditorGlobalStyles;
      }
      const revision = revisions.find(
        (rev) => String(rev.id) === String(revisionId2)
      );
      return revision || currentEditorGlobalStyles;
    }, [revisionId2, revisions, currentEditorGlobalStyles]);
    const selectedRevisionMatchesEditorStyles = areGlobalStylesEqual(
      currentlySelectedRevision,
      currentEditorGlobalStyles
    );
    const onCloseRevisions = () => {
      if (onClose) {
        onClose();
      }
    };
    const restoreRevision2 = (revision) => {
      setUserConfig(revision);
      setIsLoadingRevisionWithUnsavedChanges(false);
      onCloseRevisions();
    };
    const handleRevisionSelect = (revision) => {
      goTo(`/revisions/${revision.id}`);
    };
    const currentlySelectedRevisionId = (
      // @ts-expect-error: revision id is not present in the fallback (default object).
      currentlySelectedRevision?.id ?? revisions[0]?.id
    );
    const isLoadButtonEnabled = !!currentlySelectedRevisionId && currentlySelectedRevisionId !== "unsaved" && !selectedRevisionMatchesEditorStyles;
    const hasRevisions = !!revisions.length;
    return /* @__PURE__ */ (0, import_jsx_runtime348.jsxs)(import_jsx_runtime348.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
        ScreenHeader,
        {
          title: revisionsCount ? (0, import_i18n183.sprintf)(
            // translators: %d: number of revisions.
            (0, import_i18n183.__)("Revisions (%d)"),
            revisionsCount
          ) : (0, import_i18n183.__)("Revisions"),
          description: (0, import_i18n183.__)(
            `Click on previously saved styles to preview them. To restore a selected version to the editor, hit "Apply." When you're ready, use the Save button to save your changes.`
          ),
          onBack: onCloseRevisions
        }
      ),
      !hasRevisions && /* @__PURE__ */ (0, import_jsx_runtime348.jsx)(import_components143.Spinner, { className: "global-styles-ui-screen-revisions__loading" }),
      /* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
        revisions_buttons_default,
        {
          onChange: handleRevisionSelect,
          selectedRevisionId: currentlySelectedRevisionId,
          userRevisions: revisions,
          canApplyRevision: isLoadButtonEnabled,
          onApplyRevision: () => hasUnsavedChanges ? setIsLoadingRevisionWithUnsavedChanges(true) : restoreRevision2(currentlySelectedRevision)
        }
      ),
      numPages > 1 && /* @__PURE__ */ (0, import_jsx_runtime348.jsx)("div", { className: "global-styles-ui-screen-revisions__footer", children: /* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
        Pagination,
        {
          className: "global-styles-ui-screen-revisions__pagination",
          currentPage,
          numPages,
          changePage: setCurrentPage,
          totalItems: revisionsCount,
          disabled: isLoading,
          label: (0, import_i18n183.__)("Global Styles pagination")
        }
      ) }),
      isLoadingRevisionWithUnsavedChanges && /* @__PURE__ */ (0, import_jsx_runtime348.jsx)(
        import_components143.__experimentalConfirmDialog,
        {
          isOpen: isLoadingRevisionWithUnsavedChanges,
          confirmButtonText: (0, import_i18n183.__)("Apply"),
          onConfirm: () => restoreRevision2(currentlySelectedRevision),
          onCancel: () => setIsLoadingRevisionWithUnsavedChanges(false),
          size: "medium",
          children: (0, import_i18n183.__)(
            "Are you sure you want to apply this revision? Any unsaved changes will be lost."
          )
        }
      )
    ] });
  }
  var screen_revisions_default = ScreenRevisions;

  // packages/global-styles-ui/build-module/font-sizes/font-sizes.mjs
  var import_i18n185 = __toESM(require_i18n(), 1);
  var import_components145 = __toESM(require_components(), 1);
  var import_element194 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/font-sizes/confirm-reset-font-sizes-dialog.mjs
  var import_components144 = __toESM(require_components(), 1);
  var import_i18n184 = __toESM(require_i18n(), 1);
  var import_jsx_runtime349 = __toESM(require_jsx_runtime(), 1);
  function ConfirmResetFontSizesDialog({
    text,
    confirmButtonText,
    isOpen: isOpen2,
    toggleOpen,
    onConfirm
  }) {
    const handleConfirm = async () => {
      toggleOpen();
      onConfirm();
    };
    const handleCancel = () => {
      toggleOpen();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime349.jsx)(
      import_components144.__experimentalConfirmDialog,
      {
        isOpen: isOpen2,
        cancelButtonText: (0, import_i18n184.__)("Cancel"),
        confirmButtonText,
        onCancel: handleCancel,
        onConfirm: handleConfirm,
        size: "medium",
        children: text
      }
    );
  }
  var confirm_reset_font_sizes_dialog_default = ConfirmResetFontSizesDialog;

  // packages/global-styles-ui/build-module/font-sizes/font-sizes.mjs
  var import_jsx_runtime350 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu8 } = unlock7(import_components145.privateApis);
  function FontSizeGroup({
    label,
    origin,
    sizes,
    handleAddFontSize,
    handleResetFontSizes
  }) {
    const [isResetDialogOpen, setIsResetDialogOpen] = (0, import_element194.useState)(false);
    const toggleResetDialog = () => setIsResetDialogOpen(!isResetDialogOpen);
    const resetDialogText = origin === "custom" ? (0, import_i18n185.__)(
      "Are you sure you want to remove all custom font size presets?"
    ) : (0, import_i18n185.__)(
      "Are you sure you want to reset all font size presets to their default values?"
    );
    return /* @__PURE__ */ (0, import_jsx_runtime350.jsxs)(import_jsx_runtime350.Fragment, { children: [
      handleResetFontSizes && isResetDialogOpen && /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
        confirm_reset_font_sizes_dialog_default,
        {
          text: resetDialogText,
          confirmButtonText: origin === "custom" ? (0, import_i18n185.__)("Remove") : (0, import_i18n185.__)("Reset"),
          isOpen: isResetDialogOpen,
          toggleOpen: toggleResetDialog,
          onConfirm: handleResetFontSizes
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime350.jsxs)(import_components145.__experimentalVStack, { spacing: 4, children: [
        /* @__PURE__ */ (0, import_jsx_runtime350.jsxs)(import_components145.__experimentalHStack, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(Subtitle, { level: 3, children: label }),
          /* @__PURE__ */ (0, import_jsx_runtime350.jsxs)(import_components145.FlexItem, { className: "global-styles-ui__typography-panel__options-container", children: [
            origin === "custom" && /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
              import_components145.Button,
              {
                label: (0, import_i18n185.__)("Add font size"),
                icon: plus_default,
                size: "small",
                onClick: handleAddFontSize
              }
            ),
            !!handleResetFontSizes && /* @__PURE__ */ (0, import_jsx_runtime350.jsxs)(Menu8, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
                Menu8.TriggerButton,
                {
                  render: /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
                    import_components145.Button,
                    {
                      size: "small",
                      icon: more_vertical_default,
                      label: (0, import_i18n185.__)(
                        "Font size presets options"
                      )
                    }
                  )
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(Menu8.Popover, { children: /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(Menu8.Item, { onClick: toggleResetDialog, children: /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(Menu8.ItemLabel, { children: origin === "custom" ? (0, import_i18n185.__)(
                "Remove font size presets"
              ) : (0, import_i18n185.__)(
                "Reset font size presets"
              ) }) }) })
            ] })
          ] })
        ] }),
        !!sizes.length && /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(import_components145.__experimentalItemGroup, { isBordered: true, isSeparated: true, children: sizes.map((size4) => /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
          NavigationButtonAsItem,
          {
            path: `/typography/font-sizes/${origin}/${size4.slug}`,
            children: /* @__PURE__ */ (0, import_jsx_runtime350.jsxs)(import_components145.__experimentalHStack, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(import_components145.FlexItem, { className: "global-styles-ui-font-size__item", children: size4.name }),
              /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(import_components145.FlexItem, { display: "flex", children: /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
                icon_default,
                {
                  icon: (0, import_i18n185.isRTL)() ? chevron_left_default : chevron_right_default
                }
              ) })
            ] })
          },
          size4.slug
        )) })
      ] })
    ] });
  }
  function FontSizes2() {
    const [themeFontSizes, setThemeFontSizes] = useSetting(
      "typography.fontSizes.theme"
    );
    const [baseThemeFontSizes] = useSetting(
      "typography.fontSizes.theme",
      "base"
    );
    const [defaultFontSizes, setDefaultFontSizes] = useSetting(
      "typography.fontSizes.default"
    );
    const [baseDefaultFontSizes] = useSetting(
      "typography.fontSizes.default",
      "base"
    );
    const [customFontSizes = [], setCustomFontSizes] = useSetting(
      "typography.fontSizes.custom"
    );
    const [defaultFontSizesEnabled] = useSetting(
      "typography.defaultFontSizes"
    );
    const handleAddFontSize = () => {
      const index2 = getNewIndexFromPresets(customFontSizes, "custom-");
      const newFontSize = {
        /* translators: %d: font size index */
        name: (0, import_i18n185.sprintf)((0, import_i18n185.__)("New Font Size %d"), index2),
        size: "16px",
        slug: `custom-${index2}`
      };
      setCustomFontSizes([...customFontSizes, newFontSize]);
    };
    const hasSameSizeValues = (arr1, arr2) => arr1.map((item) => item.size).join("") === arr2.map((item) => item.size).join("");
    return /* @__PURE__ */ (0, import_jsx_runtime350.jsxs)(import_components145.__experimentalVStack, { spacing: 2, children: [
      /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
        ScreenHeader,
        {
          title: (0, import_i18n185.__)("Font size presets"),
          description: (0, import_i18n185.__)(
            "Create and edit the presets used for font sizes across the site."
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(import_components145.__experimentalView, { children: /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(import_components145.__experimentalSpacer, { paddingX: 4, children: /* @__PURE__ */ (0, import_jsx_runtime350.jsxs)(import_components145.__experimentalVStack, { spacing: 8, children: [
        !!themeFontSizes?.length && /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
          FontSizeGroup,
          {
            label: (0, import_i18n185.__)("Theme"),
            origin: "theme",
            sizes: themeFontSizes,
            handleAddFontSize,
            handleResetFontSizes: hasSameSizeValues(
              themeFontSizes,
              baseThemeFontSizes
            ) ? void 0 : () => setThemeFontSizes(
              baseThemeFontSizes
            )
          }
        ),
        defaultFontSizesEnabled && !!defaultFontSizes?.length && /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
          FontSizeGroup,
          {
            label: (0, import_i18n185.__)("Default"),
            origin: "default",
            sizes: defaultFontSizes,
            handleAddFontSize,
            handleResetFontSizes: hasSameSizeValues(
              defaultFontSizes,
              baseDefaultFontSizes
            ) ? void 0 : () => setDefaultFontSizes(
              baseDefaultFontSizes
            )
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime350.jsx)(
          FontSizeGroup,
          {
            label: (0, import_i18n185.__)("Custom"),
            origin: "custom",
            sizes: customFontSizes,
            handleAddFontSize,
            handleResetFontSizes: customFontSizes.length > 0 ? () => setCustomFontSizes([]) : void 0
          }
        )
      ] }) }) })
    ] });
  }
  var font_sizes_default = FontSizes2;

  // packages/global-styles-ui/build-module/font-sizes/font-size.mjs
  var import_i18n189 = __toESM(require_i18n(), 1);
  var import_components149 = __toESM(require_components(), 1);
  var import_element196 = __toESM(require_element(), 1);

  // packages/global-styles-ui/build-module/font-sizes/font-size-preview.mjs
  var import_block_editor17 = __toESM(require_block_editor(), 1);
  var import_i18n186 = __toESM(require_i18n(), 1);
  var import_jsx_runtime351 = __toESM(require_jsx_runtime(), 1);
  function FontSizePreview({ fontSize }) {
    const [font2] = useStyle("typography");
    const input = typeof fontSize?.fluid === "object" && fontSize?.fluid?.min && fontSize?.fluid?.max ? {
      minimumFontSize: fontSize.fluid.min,
      maximumFontSize: fontSize.fluid.max
    } : {
      fontSize: fontSize.size
    };
    const computedFontSize = (0, import_block_editor17.getComputedFluidTypographyValue)(input);
    return /* @__PURE__ */ (0, import_jsx_runtime351.jsx)(
      "div",
      {
        className: "global-styles-ui-typography-preview",
        style: {
          fontSize: computedFontSize,
          fontFamily: font2?.fontFamily ?? "serif"
        },
        children: (0, import_i18n186.__)("Aa")
      }
    );
  }
  var font_size_preview_default = FontSizePreview;

  // packages/global-styles-ui/build-module/font-sizes/confirm-delete-font-size-dialog.mjs
  var import_components146 = __toESM(require_components(), 1);
  var import_i18n187 = __toESM(require_i18n(), 1);
  var import_jsx_runtime352 = __toESM(require_jsx_runtime(), 1);
  function ConfirmDeleteFontSizeDialog({
    fontSize,
    isOpen: isOpen2,
    toggleOpen,
    handleRemoveFontSize
  }) {
    const handleConfirm = async () => {
      toggleOpen();
      handleRemoveFontSize(fontSize);
    };
    const handleCancel = () => {
      toggleOpen();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime352.jsx)(
      import_components146.__experimentalConfirmDialog,
      {
        isOpen: isOpen2,
        cancelButtonText: (0, import_i18n187.__)("Cancel"),
        confirmButtonText: (0, import_i18n187.__)("Delete"),
        onCancel: handleCancel,
        onConfirm: handleConfirm,
        size: "medium",
        children: fontSize && (0, import_i18n187.sprintf)(
          /* translators: %s: Name of the font size preset. */
          (0, import_i18n187.__)(
            'Are you sure you want to delete "%s" font size preset?'
          ),
          fontSize.name
        )
      }
    );
  }
  var confirm_delete_font_size_dialog_default = ConfirmDeleteFontSizeDialog;

  // packages/global-styles-ui/build-module/font-sizes/rename-font-size-dialog.mjs
  var import_components147 = __toESM(require_components(), 1);
  var import_i18n188 = __toESM(require_i18n(), 1);
  var import_element195 = __toESM(require_element(), 1);
  var import_jsx_runtime353 = __toESM(require_jsx_runtime(), 1);
  function RenameFontSizeDialog({
    fontSize,
    toggleOpen,
    handleRename
  }) {
    const [newName, setNewName] = (0, import_element195.useState)(
      fontSize.name
    );
    const handleConfirm = () => {
      if (newName && newName.trim()) {
        handleRename(newName);
      }
      toggleOpen();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime353.jsx)(
      import_components147.Modal,
      {
        onRequestClose: toggleOpen,
        focusOnMount: "firstContentElement",
        title: (0, import_i18n188.__)("Rename"),
        size: "small",
        children: /* @__PURE__ */ (0, import_jsx_runtime353.jsx)(
          "form",
          {
            onSubmit: (event) => {
              event.preventDefault();
              handleConfirm();
              toggleOpen();
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime353.jsxs)(import_components147.__experimentalVStack, { spacing: "3", children: [
              /* @__PURE__ */ (0, import_jsx_runtime353.jsx)(
                import_components147.__experimentalInputControl,
                {
                  autoComplete: "off",
                  value: newName,
                  onChange: setNewName,
                  label: (0, import_i18n188.__)("Name"),
                  placeholder: (0, import_i18n188.__)("Font size preset name")
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime353.jsxs)(import_components147.__experimentalHStack, { justify: "right", children: [
                /* @__PURE__ */ (0, import_jsx_runtime353.jsx)(
                  import_components147.Button,
                  {
                    __next40pxDefaultSize: true,
                    variant: "tertiary",
                    onClick: toggleOpen,
                    children: (0, import_i18n188.__)("Cancel")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime353.jsx)(
                  import_components147.Button,
                  {
                    __next40pxDefaultSize: true,
                    variant: "primary",
                    type: "submit",
                    children: (0, import_i18n188.__)("Save")
                  }
                )
              ] })
            ] })
          }
        )
      }
    );
  }
  var rename_font_size_dialog_default = RenameFontSizeDialog;

  // packages/global-styles-ui/build-module/size-control/index.mjs
  var import_components148 = __toESM(require_components(), 1);
  var import_jsx_runtime354 = __toESM(require_jsx_runtime(), 1);
  var DEFAULT_UNITS = ["px", "em", "rem", "vw", "vh"];
  function SizeControl(props) {
    const { baseControlProps } = (0, import_components148.useBaseControlProps)(props);
    const { value, onChange, fallbackValue, disabled: disabled2, label } = props;
    const units = (0, import_components148.__experimentalUseCustomUnits)({
      availableUnits: DEFAULT_UNITS
    });
    const [valueQuantity, valueUnit = "px"] = (0, import_components148.__experimentalParseQuantityAndUnitFromRawValue)(value, units);
    const isValueUnitRelative = !!valueUnit && ["em", "rem", "vw", "vh"].includes(valueUnit);
    const handleUnitControlChange = (newValue) => {
      onChange?.(newValue);
    };
    const handleRangeControlChange = (newValue) => {
      if (newValue !== void 0) {
        onChange?.(newValue + valueUnit);
      } else {
        onChange?.(void 0);
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(import_components148.BaseControl, { ...baseControlProps, children: /* @__PURE__ */ (0, import_jsx_runtime354.jsxs)(import_components148.Flex, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(import_components148.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(
        import_components148.__experimentalUnitControl,
        {
          label,
          hideLabelFromVision: true,
          value,
          onChange: handleUnitControlChange,
          units,
          min: 0,
          disabled: disabled2
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(import_components148.FlexItem, { isBlock: true, children: /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(import_components148.__experimentalSpacer, { marginX: 2, marginBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime354.jsx)(
        import_components148.RangeControl,
        {
          label,
          hideLabelFromVision: true,
          value: valueQuantity,
          initialPosition: fallbackValue,
          withInputField: false,
          onChange: handleRangeControlChange,
          min: 0,
          max: isValueUnitRelative ? 10 : 100,
          step: isValueUnitRelative ? 0.1 : 1,
          disabled: disabled2
        }
      ) }) })
    ] }) });
  }

  // packages/global-styles-ui/build-module/font-sizes/font-size.mjs
  var import_jsx_runtime355 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu9 } = unlock7(import_components149.privateApis);
  function FontSize() {
    const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = (0, import_element196.useState)(false);
    const [isRenameDialogOpen, setIsRenameDialogOpen] = (0, import_element196.useState)(false);
    const {
      params: { origin, slug },
      goBack
    } = (0, import_components149.useNavigator)();
    const [fontSizes, setFontSizes] = useSetting("typography.fontSizes");
    const [globalFluid] = useSetting("typography.fluid");
    const sizes = fontSizes?.[origin] ?? [];
    const fontSize = sizes.find(
      (size4) => size4.slug === slug
    );
    (0, import_element196.useEffect)(() => {
      if (!!slug && !fontSize) {
        goBack();
      }
    }, [slug, fontSize, goBack]);
    if (!origin || !slug || !fontSize) {
      return null;
    }
    const isFluid = fontSize?.fluid !== void 0 ? !!fontSize.fluid : !!globalFluid;
    const isCustomFluid = typeof fontSize?.fluid === "object";
    const handleNameChange = (value) => {
      updateFontSize("name", value);
    };
    const handleFontSizeChange = (value) => {
      updateFontSize("size", value);
    };
    const handleFluidChange = (value) => {
      updateFontSize("fluid", value);
    };
    const handleCustomFluidValues = (value) => {
      if (value) {
        updateFontSize("fluid", {
          min: fontSize.size,
          max: fontSize.size
        });
      } else {
        updateFontSize("fluid", true);
      }
    };
    const handleMinChange = (value) => {
      const fluid = typeof fontSize.fluid === "object" ? fontSize.fluid : {};
      updateFontSize("fluid", { ...fluid, min: value });
    };
    const handleMaxChange = (value) => {
      const fluid = typeof fontSize.fluid === "object" ? fontSize.fluid : {};
      updateFontSize("fluid", { ...fluid, max: value });
    };
    const updateFontSize = (key, value) => {
      const newFontSizes = sizes.map((size4) => {
        if (size4.slug === slug) {
          return { ...size4, [key]: value };
        }
        return size4;
      });
      setFontSizes({
        ...fontSizes,
        [origin]: newFontSizes
      });
    };
    const handleRemoveFontSize = () => {
      const newFontSizes = sizes.filter((size4) => size4.slug !== slug);
      setFontSizes({
        ...fontSizes,
        [origin]: newFontSizes
      });
    };
    const toggleDeleteConfirm = () => {
      setIsDeleteConfirmOpen(!isDeleteConfirmOpen);
    };
    const toggleRenameDialog = () => {
      setIsRenameDialogOpen(!isRenameDialogOpen);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime355.jsxs)(import_jsx_runtime355.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
        confirm_delete_font_size_dialog_default,
        {
          fontSize,
          isOpen: isDeleteConfirmOpen,
          toggleOpen: toggleDeleteConfirm,
          handleRemoveFontSize
        }
      ),
      isRenameDialogOpen && /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
        rename_font_size_dialog_default,
        {
          fontSize,
          toggleOpen: toggleRenameDialog,
          handleRename: handleNameChange
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime355.jsxs)(import_components149.__experimentalVStack, { spacing: 4, children: [
        /* @__PURE__ */ (0, import_jsx_runtime355.jsxs)(import_components149.__experimentalHStack, { justify: "space-between", alignment: "flex-start", children: [
          /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
            ScreenHeader,
            {
              title: fontSize.name,
              description: (0, import_i18n189.sprintf)(
                /* translators: %s: font size preset name. */
                (0, import_i18n189.__)("Manage the font size %s."),
                fontSize.name
              )
            }
          ),
          origin === "custom" && /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(import_components149.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
            import_components149.__experimentalSpacer,
            {
              marginTop: 3,
              marginBottom: 0,
              paddingX: 4,
              children: /* @__PURE__ */ (0, import_jsx_runtime355.jsxs)(Menu9, { children: [
                /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
                  Menu9.TriggerButton,
                  {
                    render: /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
                      import_components149.Button,
                      {
                        size: "small",
                        icon: more_vertical_default,
                        label: (0, import_i18n189.__)(
                          "Font size options"
                        )
                      }
                    )
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime355.jsxs)(Menu9.Popover, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
                    Menu9.Item,
                    {
                      onClick: toggleRenameDialog,
                      children: /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(Menu9.ItemLabel, { children: (0, import_i18n189.__)("Rename") })
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
                    Menu9.Item,
                    {
                      onClick: toggleDeleteConfirm,
                      children: /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(Menu9.ItemLabel, { children: (0, import_i18n189.__)("Delete") })
                    }
                  )
                ] })
              ] })
            }
          ) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(import_components149.__experimentalView, { children: /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
          import_components149.__experimentalSpacer,
          {
            paddingX: 4,
            marginBottom: 0,
            paddingBottom: 6,
            children: /* @__PURE__ */ (0, import_jsx_runtime355.jsxs)(import_components149.__experimentalVStack, { spacing: 4, children: [
              /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(import_components149.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(font_size_preview_default, { fontSize }) }),
              /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
                SizeControl,
                {
                  label: (0, import_i18n189.__)("Size"),
                  value: !isCustomFluid && fontSize.size ? String(fontSize.size) : "",
                  onChange: handleFontSizeChange,
                  disabled: isCustomFluid
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
                import_components149.ToggleControl,
                {
                  label: (0, import_i18n189.__)("Fluid typography"),
                  help: (0, import_i18n189.__)(
                    "Scale the font size dynamically to fit the screen or viewport."
                  ),
                  checked: isFluid,
                  onChange: handleFluidChange
                }
              ),
              isFluid && /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
                import_components149.ToggleControl,
                {
                  label: (0, import_i18n189.__)("Custom fluid values"),
                  help: (0, import_i18n189.__)(
                    "Set custom min and max values for the fluid font size."
                  ),
                  checked: isCustomFluid,
                  onChange: handleCustomFluidValues
                }
              ),
              isCustomFluid && /* @__PURE__ */ (0, import_jsx_runtime355.jsxs)(import_jsx_runtime355.Fragment, { children: [
                /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
                  SizeControl,
                  {
                    label: (0, import_i18n189.__)("Minimum"),
                    value: typeof fontSize?.fluid === "object" ? fontSize.fluid?.min : void 0,
                    onChange: handleMinChange
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime355.jsx)(
                  SizeControl,
                  {
                    label: (0, import_i18n189.__)("Maximum"),
                    value: typeof fontSize?.fluid === "object" ? fontSize.fluid?.max : void 0,
                    onChange: handleMaxChange
                  }
                )
              ] })
            ] })
          }
        ) })
      ] })
    ] });
  }
  var font_size_default = FontSize;

  // packages/global-styles-ui/build-module/global-styles-ui.mjs
  var import_jsx_runtime356 = __toESM(require_jsx_runtime(), 1);
  function BlockStylesNavigationScreens({
    parentMenu,
    blockStyles,
    blockName,
    selectedViewport,
    showResponsiveStateControls,
    showBlockStateControls
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(import_jsx_runtime356.Fragment, { children: blockStyles.map((style, index2) => /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
      import_components150.Navigator.Screen,
      {
        path: parentMenu + "/variations/" + style.name,
        children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
          screen_block_default,
          {
            name: blockName,
            variation: style.name,
            selectedViewport,
            showResponsiveStateControls,
            showBlockStateControls
          }
        )
      },
      index2
    )) });
  }
  function ContextScreens({
    name: name2,
    parentMenu = "",
    selectedViewport,
    showResponsiveStateControls,
    showBlockStateControls
  }) {
    const blockStyleVariations = (0, import_data61.useSelect)(
      (select9) => {
        if (!name2) {
          return [];
        }
        const { getBlockStyles } = select9(import_blocks11.store);
        return getBlockStyles(name2);
      },
      [name2]
    );
    if (!blockStyleVariations?.length) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
      BlockStylesNavigationScreens,
      {
        parentMenu,
        blockStyles: blockStyleVariations,
        blockName: name2 || "",
        selectedViewport,
        showResponsiveStateControls,
        showBlockStateControls
      }
    );
  }
  function GlobalStylesUI({
    value,
    baseValue,
    onChange,
    path,
    onPathChange,
    fontLibraryEnabled = false,
    serverCSS,
    serverSettings,
    selectedViewport,
    showResponsiveStateControls = true,
    showBlockStateControls = true
  }) {
    const blocks = (0, import_blocks11.getBlockTypes)();
    const mergedValue = (0, import_element197.useMemo)(() => {
      return mergeGlobalStyles(baseValue, value);
    }, [baseValue, value]);
    const [globalStylesCSS, globalSettings] = generateGlobalStyles(
      mergedValue,
      [],
      {
        styleOptions: { variationStyles: true }
      }
    );
    const styles = (0, import_element197.useMemo)(
      () => [...serverCSS ?? [], ...globalStylesCSS ?? []],
      [serverCSS, globalStylesCSS]
    );
    const settings = (0, import_element197.useMemo)(() => {
      return {
        ...serverSettings,
        __experimentalFeatures: globalSettings,
        styles
      };
    }, [globalSettings, serverSettings, styles]);
    return /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
      GlobalStylesProvider,
      {
        value,
        baseValue,
        onChange,
        fontLibraryEnabled,
        children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(import_block_editor18.BlockEditorProvider, { settings, children: /* @__PURE__ */ (0, import_jsx_runtime356.jsxs)(
          import_components150.Navigator,
          {
            className: "global-styles-ui-sidebar__navigator-provider",
            initialPath: path || "/",
            children: [
              (path || onPathChange) && /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
                PathSynchronizer,
                {
                  path,
                  onPathChange
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_root_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/colors", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_colors_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/typography", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_typography_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/typography/font-sizes", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(font_sizes_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/typography/font-sizes/:origin/:slug", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(font_size_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/layout", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_layout_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/colors/palette", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_color_palette_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/variations", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_style_variations_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/css", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_css_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/revisions/:revisionId?", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_revisions_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/shadows", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(ScreenShadows, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/shadows/edit/:category/:slug", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(ScreenShadowsEdit, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/background", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_background_default, {}) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/typography/text", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_typography_element_default, { element: "text" }) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/typography/link", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_typography_element_default, { element: "link" }) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/typography/heading", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_typography_element_default, { element: "heading" }) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/typography/caption", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_typography_element_default, { element: "caption" }) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/typography/button", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_typography_element_default, { element: "button" }) }),
              /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(GlobalStylesNavigationScreen, { path: "/blocks", children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(screen_block_list_default, {}) }),
              blocks.map((block) => /* @__PURE__ */ (0, import_jsx_runtime356.jsxs)(import_element197.Fragment, { children: [
                /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
                  GlobalStylesNavigationScreen,
                  {
                    path: "/blocks/" + encodeURIComponent(block.name),
                    children: /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
                      screen_block_default,
                      {
                        name: block.name,
                        selectedViewport,
                        showResponsiveStateControls,
                        showBlockStateControls
                      }
                    )
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
                  ContextScreens,
                  {
                    name: block.name,
                    parentMenu: "/blocks/" + encodeURIComponent(block.name),
                    selectedViewport,
                    showResponsiveStateControls,
                    showBlockStateControls
                  }
                )
              ] }, block.name))
            ]
          }
        ) })
      }
    );
  }
  function GlobalStylesNavigationScreen({
    path,
    children
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime356.jsx)(
      import_components150.Navigator.Screen,
      {
        className: "global-styles-ui-sidebar__navigator-screen",
        path,
        children
      }
    );
  }
  function PathSynchronizer({
    path,
    onPathChange
  }) {
    const navigator2 = (0, import_components150.useNavigator)();
    const { path: childPath } = navigator2.location;
    const previousParentPath = (0, import_compose32.usePrevious)(path);
    const previousChildPath = (0, import_compose32.usePrevious)(childPath);
    (0, import_element197.useEffect)(() => {
      if (path && path !== childPath) {
        if (path !== previousParentPath) {
          navigator2.goTo(path);
        } else if (childPath !== previousChildPath && onPathChange) {
          onPathChange(childPath ?? "/");
        }
      }
    }, [
      onPathChange,
      path,
      previousChildPath,
      previousParentPath,
      childPath,
      navigator2
    ]);
    return null;
  }

  // packages/global-styles-ui/build-module/with-global-styles-provider.mjs
  var import_jsx_runtime357 = __toESM(require_jsx_runtime(), 1);
  function withGlobalStylesProvider(Component3) {
    return function WrappedComponent({
      value,
      baseValue,
      onChange,
      ...props
    }) {
      return /* @__PURE__ */ (0, import_jsx_runtime357.jsx)(
        GlobalStylesProvider,
        {
          value,
          baseValue,
          onChange,
          children: /* @__PURE__ */ (0, import_jsx_runtime357.jsx)(Component3, { ...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_runtime358 = __toESM(require_jsx_runtime(), 1);

  // packages/editor/build-module/components/global-styles/index.mjs
  var import_media_utils6 = __toESM(require_media_utils(), 1);

  // packages/editor/build-module/components/global-styles/block-link.mjs
  var import_data62 = __toESM(require_data(), 1);
  var import_element198 = __toESM(require_element(), 1);
  var import_block_editor19 = __toESM(require_block_editor(), 1);
  var import_compose33 = __toESM(require_compose(), 1);
  function GlobalStylesBlockLink({ path, onPathChange }) {
    const { selectedBlockName, selectedBlockClientId } = (0, import_data62.useSelect)(
      (select9) => {
        const { getSelectedBlockClientId: getSelectedBlockClientId2, getBlockName: getBlockName2 } = select9(import_block_editor19.store);
        const clientId = getSelectedBlockClientId2();
        return {
          selectedBlockName: getBlockName2(clientId),
          selectedBlockClientId: clientId
        };
      },
      []
    );
    const blockHasGlobalStyles = true;
    const previousBlockClientId = (0, import_compose33.usePrevious)(selectedBlockClientId);
    (0, import_element198.useEffect)(() => {
      if (selectedBlockClientId === previousBlockClientId) {
        return;
      }
      if (!selectedBlockClientId || !blockHasGlobalStyles) {
        return;
      }
      if (!path || path !== "/blocks" && !path.startsWith("/blocks/")) {
        return;
      }
      const newPath = "/blocks/" + encodeURIComponent(selectedBlockName);
      if (newPath !== path) {
        onPathChange?.(newPath);
      }
    }, [
      selectedBlockClientId,
      previousBlockClientId,
      selectedBlockName,
      blockHasGlobalStyles,
      path,
      onPathChange
    ]);
    return null;
  }

  // packages/editor/build-module/components/global-styles/hooks.mjs
  var import_element199 = __toESM(require_element(), 1);
  var import_core_data43 = __toESM(require_core_data(), 1);
  var import_data63 = __toESM(require_data(), 1);
  var import_block_editor20 = __toESM(require_block_editor(), 1);
  var { cleanEmptyObject } = unlock(import_block_editor20.privateApis);
  function useGlobalStylesUserConfig() {
    const { globalStylesId, isReady: isReady2, settings, styles, _links } = (0, import_data63.useSelect)(
      (select9) => {
        const {
          getEntityRecord,
          getEditedEntityRecord: getEditedEntityRecord2,
          hasFinishedResolution,
          canUser
        } = select9(import_core_data43.store);
        const _globalStylesId = select9(import_core_data43.store).__experimentalGetCurrentGlobalStylesId();
        let record;
        const userCanEditGlobalStyles = _globalStylesId ? canUser("update", {
          kind: "root",
          name: "globalStyles",
          id: _globalStylesId
        }) : null;
        if (_globalStylesId && /*
        * Test that the OPTIONS request for user capabilities is complete
        * before fetching the global styles entity record.
        * This is to avoid fetching the global styles entity unnecessarily.
        */
        typeof userCanEditGlobalStyles === "boolean") {
          if (userCanEditGlobalStyles) {
            record = getEditedEntityRecord2(
              "root",
              "globalStyles",
              _globalStylesId
            );
          } else {
            record = getEntityRecord(
              "root",
              "globalStyles",
              _globalStylesId,
              { context: "view" }
            );
          }
        }
        let hasResolved = false;
        if (hasFinishedResolution(
          "__experimentalGetCurrentGlobalStylesId"
        )) {
          if (_globalStylesId) {
            hasResolved = userCanEditGlobalStyles ? hasFinishedResolution("getEditedEntityRecord", [
              "root",
              "globalStyles",
              _globalStylesId
            ]) : hasFinishedResolution("getEntityRecord", [
              "root",
              "globalStyles",
              _globalStylesId,
              { context: "view" }
            ]);
          } else {
            hasResolved = true;
          }
        }
        return {
          globalStylesId: _globalStylesId,
          isReady: hasResolved,
          settings: record?.settings,
          styles: record?.styles,
          _links: record?._links
        };
      },
      []
    );
    const { getEditedEntityRecord } = (0, import_data63.useSelect)(import_core_data43.store);
    const { editEntityRecord } = (0, import_data63.useDispatch)(import_core_data43.store);
    const config2 = (0, import_element199.useMemo)(() => {
      return {
        settings: settings ?? {},
        styles: styles ?? {},
        _links: _links ?? {}
      };
    }, [settings, styles, _links]);
    const setConfig = (0, import_element199.useCallback)(
      /**
       * Set the global styles config.
       * @param {Function|Object} callbackOrObject If the callbackOrObject is a function, pass the current config to the callback so the consumer can merge values.
       *                                           Otherwise, overwrite the current config with the incoming object.
       * @param {Object}          options          Options for editEntityRecord Core selector.
       */
      (callbackOrObject, options = {}) => {
        const record = getEditedEntityRecord(
          "root",
          "globalStyles",
          globalStylesId
        );
        const currentConfig = {
          styles: record?.styles ?? {},
          settings: record?.settings ?? {},
          _links: record?._links ?? {}
        };
        const updatedConfig = typeof callbackOrObject === "function" ? callbackOrObject(currentConfig) : callbackOrObject;
        editEntityRecord(
          "root",
          "globalStyles",
          globalStylesId,
          {
            styles: cleanEmptyObject(updatedConfig.styles) || {},
            settings: cleanEmptyObject(updatedConfig.settings) || {},
            _links: cleanEmptyObject(updatedConfig._links) || {}
          },
          options
        );
      },
      [globalStylesId, editEntityRecord, getEditedEntityRecord]
    );
    return [isReady2, config2, setConfig];
  }
  function useGlobalStylesBaseConfig() {
    const baseConfig = (0, import_data63.useSelect)(
      (select9) => select9(import_core_data43.store).__experimentalGetCurrentThemeBaseGlobalStyles(),
      []
    );
    return [!!baseConfig, baseConfig];
  }
  function useGlobalStyles() {
    const [isUserConfigReady, userConfig, setUserConfig] = useGlobalStylesUserConfig();
    const [isBaseConfigReady, baseConfig] = useGlobalStylesBaseConfig();
    const merged = (0, import_element199.useMemo)(() => {
      if (!isUserConfigReady || !isBaseConfigReady) {
        return {};
      }
      return mergeGlobalStyles(baseConfig || {}, userConfig);
    }, [isUserConfigReady, isBaseConfigReady, baseConfig, userConfig]);
    return {
      merged,
      base: baseConfig || {},
      user: userConfig,
      setUser: setUserConfig,
      isReady: isUserConfigReady && isBaseConfigReady
    };
  }
  function useStyle2(path, blockName) {
    const { merged } = useGlobalStyles();
    return (0, import_element199.useMemo)(
      () => getStyle(merged, path, blockName),
      [merged, path, blockName]
    );
  }
  function useSetting2(path, blockName) {
    const { merged } = useGlobalStyles();
    return (0, import_element199.useMemo)(
      () => getSetting(merged, path, blockName),
      [merged, path, blockName]
    );
  }

  // packages/editor/build-module/components/global-styles/index.mjs
  var import_jsx_runtime359 = __toESM(require_jsx_runtime(), 1);
  function useServerData(settings) {
    const styles = settings?.styles;
    const __unstableResolvedAssets = settings?.__unstableResolvedAssets;
    const colors2 = settings?.colors;
    const gradients = settings?.gradients;
    const __experimentalDiscussionSettings = settings?.__experimentalDiscussionSettings;
    const fontLibraryEnabled = settings?.fontLibraryEnabled ?? true;
    const responsiveEditingEnabled = settings?.responsiveEditingEnabled ?? true;
    const blockStatesEditingEnabled = settings?.blockStatesEditingEnabled ?? true;
    const mediaUploadHandler = (0, import_data64.useSelect)((select9) => {
      const { canUser } = select9(import_core_data44.store);
      const canUserUploadMedia = canUser("create", {
        kind: "postType",
        name: "attachment"
      });
      return canUserUploadMedia ? import_media_utils6.uploadMedia : void 0;
    }, []);
    const serverCSS = (0, import_element200.useMemo)(() => {
      if (!styles) {
        return [];
      }
      return styles.filter((style) => !style.isGlobalStyles);
    }, [styles]);
    const serverSettings = (0, import_element200.useMemo)(() => {
      return {
        __unstableResolvedAssets,
        settings: {
          color: {
            palette: {
              theme: colors2 ?? []
            },
            gradients: {
              theme: gradients ?? []
            },
            duotone: {
              theme: []
            }
          }
        },
        __experimentalDiscussionSettings,
        mediaUpload: mediaUploadHandler
      };
    }, [
      __unstableResolvedAssets,
      colors2,
      gradients,
      __experimentalDiscussionSettings,
      mediaUploadHandler
    ]);
    return {
      serverCSS,
      serverSettings,
      fontLibraryEnabled,
      responsiveEditingEnabled,
      blockStatesEditingEnabled
    };
  }
  function GlobalStylesUIWrapper({
    path,
    onPathChange,
    settings,
    selectedViewport,
    showResponsiveStateControls = true
  }) {
    const {
      user: userConfig,
      base: baseConfig,
      setUser: setUserConfig,
      isReady: isReady2
    } = useGlobalStyles();
    const {
      serverCSS,
      serverSettings,
      fontLibraryEnabled,
      responsiveEditingEnabled,
      blockStatesEditingEnabled
    } = useServerData(settings);
    if (!isReady2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime359.jsxs)(import_jsx_runtime359.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime359.jsx)(
        GlobalStylesUI,
        {
          value: userConfig,
          baseValue: baseConfig || {},
          onChange: setUserConfig,
          path,
          onPathChange,
          fontLibraryEnabled,
          serverCSS,
          serverSettings,
          selectedViewport,
          showResponsiveStateControls: showResponsiveStateControls && responsiveEditingEnabled,
          showBlockStateControls: blockStatesEditingEnabled
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime359.jsx)(
        GlobalStylesBlockLink,
        {
          path,
          onPathChange
        }
      )
    ] });
  }

  // packages/editor/build-module/components/provider/use-block-editor-settings.mjs
  var { store: mediaEditorStore } = unlock(privateApis14);
  var EMPTY_OBJECT4 = {};
  function __experimentalReusableBlocksSelect(select9) {
    const { RECEIVE_INTERMEDIATE_RESULTS: RECEIVE_INTERMEDIATE_RESULTS2 } = unlock(import_core_data45.privateApis);
    const { getEntityRecords } = select9(import_core_data45.store);
    return getEntityRecords("postType", "wp_block", {
      per_page: -1,
      [RECEIVE_INTERMEDIATE_RESULTS2]: true
    });
  }
  function __experimentalUserPatternCategoriesSelect(select9) {
    return select9(import_core_data45.store).getUserPatternCategories();
  }
  var BLOCK_EDITOR_SETTINGS = [
    "__experimentalBlockBindingsSupportedAttributes",
    "__experimentalBlockDirectory",
    "__experimentalDiscussionSettings",
    "__experimentalFeatures",
    "__experimentalGlobalStylesBaseStyles",
    "allImageSizes",
    "alignWide",
    "blockStatesEditingEnabled",
    "blockInspectorTabs",
    "maxUploadFileSize",
    "allowedMimeTypes",
    "bodyPlaceholder",
    "canEditCSS",
    "canLockBlocks",
    "canUpdateBlockBindings",
    "capabilities",
    "clearBlockSelection",
    "codeEditingEnabled",
    "colors",
    "disableContentOnlyForTemplateParts",
    "disableContentOnlyForUnsyncedPatterns",
    "disableCustomColors",
    "disableCustomFontSizes",
    "disableCustomSpacingSizes",
    "disableCustomGradients",
    "disableLayoutStyles",
    "enableCustomLineHeight",
    "enableCustomSpacing",
    "enableCustomUnits",
    "enableOpenverseMediaCategory",
    "fontSizes",
    "gradients",
    "generateAnchors",
    "onNavigateToEntityRecord",
    "imageDefaultSize",
    "imageDimensions",
    "imageEditing",
    "imageSizes",
    "isPreviewMode",
    "isRTL",
    "locale",
    "maxWidth",
    "postContentAttributes",
    "postsPerPage",
    "readOnly",
    "styles",
    "titlePlaceholder",
    "supportsLayout",
    "widgetTypesToHideFromLegacyWidgetBlock",
    "__unstableHasCustomAppender",
    "__unstableResolvedAssets",
    "__unstableIsBlockBasedTheme"
  ];
  var {
    globalStylesDataKey,
    globalStylesLinksDataKey,
    selectBlockPatternsKey,
    reusableBlocksSelectKey,
    userPatternCategoriesSelectKey,
    sectionRootClientIdKey,
    mediaEditKey,
    getMediaSelectKey,
    isIsolatedEditorKey,
    deviceTypeKey,
    isNavigationOverlayContextKey,
    isNavigationPostEditorKey,
    mediaUploadOnSuccessKey,
    mediaSideloadFromUrlKey,
    openMediaEditorModalKey
  } = unlock(import_block_editor21.privateApis);
  function useBlockEditorSettings(settings, postType2, postId2, renderingMode2) {
    const isLargeViewport = (0, import_compose34.useViewportMatch)("medium");
    const {
      allImageSizes,
      bigImageSizeThreshold,
      imageStripMeta,
      imageMaxBitDepth,
      allowRightClickOverrides,
      blockTypes,
      focusMode,
      hasFixedToolbar,
      isDistractionFree,
      keepCaretInsideBlock,
      hasUploadPermissions,
      hiddenBlockTypes,
      canUseUnfilteredHTML,
      userCanCreatePages,
      pageOnFront,
      pageForPosts,
      restBlockPatternCategories,
      sectionRootClientId,
      deviceType,
      isNavigationOverlayContext,
      isRevisionsMode: isRevisionsMode2,
      viewablePostTypeLabel,
      currentPostId
    } = (0, import_data65.useSelect)(
      (select9) => {
        const {
          canUser,
          getRawEntityRecord,
          getEntityRecord,
          getBlockPatternCategories,
          getPostType
        } = select9(import_core_data45.store);
        const { get } = select9(import_preferences6.store);
        const { getBlockTypes: getBlockTypes6 } = select9(import_blocks12.store);
        const { getCurrentPostId: getCurrentPostId2, getCurrentPostType: getCurrentPostType2 } = select9(store);
        const { getDeviceType: getDeviceType2, isRevisionsMode: _isRevisionsMode } = unlock(
          select9(store)
        );
        const { getBlocksByName, getBlockAttributes: getBlockAttributes2 } = select9(import_block_editor21.store);
        const siteSettings = canUser("read", {
          kind: "root",
          name: "site"
        }) ? getEntityRecord("root", "site") : void 0;
        const baseData = getEntityRecord("root", "__unstableBase");
        const currentPostType = getCurrentPostType2();
        const postTypeObject = currentPostType ? getPostType(currentPostType) : void 0;
        function getSectionRootBlock() {
          if (renderingMode2 === "template-locked") {
            return getBlocksByName("core/post-content")?.[0] ?? "";
          }
          return getBlocksByName("core/group").find(
            (clientId) => getBlockAttributes2(clientId)?.tagName === "main"
          ) ?? "";
        }
        return {
          allImageSizes: baseData?.image_sizes,
          bigImageSizeThreshold: baseData?.image_size_threshold,
          imageStripMeta: baseData?.image_strip_meta,
          imageMaxBitDepth: baseData?.image_max_bit_depth,
          allowRightClickOverrides: get(
            "core",
            "allowRightClickOverrides"
          ),
          blockTypes: getBlockTypes6(),
          canUseUnfilteredHTML: getRawEntityRecord(
            "postType",
            postType2,
            postId2
          )?._links?.hasOwnProperty("wp:action-unfiltered-html"),
          focusMode: get("core", "focusMode"),
          hasFixedToolbar: get("core", "fixedToolbar") || !isLargeViewport,
          hiddenBlockTypes: get("core", "hiddenBlockTypes"),
          isDistractionFree: get("core", "distractionFree"),
          keepCaretInsideBlock: get("core", "keepCaretInsideBlock"),
          hasUploadPermissions: canUser("create", {
            kind: "postType",
            name: "attachment"
          }) ?? true,
          userCanCreatePages: canUser("create", {
            kind: "postType",
            name: "page"
          }),
          pageOnFront: siteSettings?.page_on_front,
          pageForPosts: siteSettings?.page_for_posts,
          // The post type's singular name, but only for real, front-end
          // rendered content (`viewable`). Empty for synced patterns,
          // navigation and templates, which gates the attached-images
          // category off for them and words its copy for everything else.
          viewablePostTypeLabel: postTypeObject?.viewable ? postTypeObject?.labels?.singular_name : void 0,
          currentPostId: getCurrentPostId2(),
          restBlockPatternCategories: getBlockPatternCategories(),
          sectionRootClientId: getSectionRootBlock(),
          deviceType: getDeviceType2(),
          isNavigationOverlayContext: postType2 === "wp_template_part" && postId2 ? getEntityRecord(
            "postType",
            "wp_template_part",
            postId2
          )?.area === "navigation-overlay" : false,
          isRevisionsMode: _isRevisionsMode()
        };
      },
      [postType2, postId2, isLargeViewport, renderingMode2]
    );
    const { merged: mergedGlobalStyles } = useGlobalStyles();
    const globalStylesData = mergedGlobalStyles.styles ?? EMPTY_OBJECT4;
    const globalStylesLinksData = mergedGlobalStyles._links ?? EMPTY_OBJECT4;
    const settingsBlockPatterns = settings.__experimentalAdditionalBlockPatterns ?? // WP 6.0
    settings.__experimentalBlockPatterns;
    const settingsBlockPatternCategories = settings.__experimentalAdditionalBlockPatternCategories ?? // WP 6.0
    settings.__experimentalBlockPatternCategories;
    const blockPatterns = (0, import_element201.useMemo)(
      () => [...settingsBlockPatterns || []].filter(
        ({ postTypes }) => {
          return !postTypes || Array.isArray(postTypes) && postTypes.includes(postType2);
        }
      ),
      [settingsBlockPatterns, postType2]
    );
    const blockPatternCategories = (0, import_element201.useMemo)(
      () => [
        ...settingsBlockPatternCategories || [],
        ...restBlockPatternCategories || []
      ].filter(
        (x2, index2, arr) => index2 === arr.findIndex((y3) => x2.name === y3.name)
      ),
      [settingsBlockPatternCategories, restBlockPatternCategories]
    );
    const { undo: undo2, setIsInserterOpened: setIsInserterOpened2 } = (0, import_data65.useDispatch)(store);
    const { editMediaEntity } = unlock((0, import_data65.useDispatch)(import_core_data45.store));
    const { saveEntityRecord } = (0, import_data65.useDispatch)(import_core_data45.store);
    const { openMediaEditorModal: openMediaEditorModal2 } = (0, import_data65.useDispatch)(mediaEditorStore);
    const createPageEntity = (0, import_element201.useCallback)(
      (options) => {
        if (!userCanCreatePages) {
          return Promise.reject({
            message: (0, import_i18n190.__)(
              "You do not have permission to create Pages."
            )
          });
        }
        return saveEntityRecord("postType", "page", options);
      },
      [saveEntityRecord, userCanCreatePages]
    );
    const allowedBlockTypes = (0, import_element201.useMemo)(() => {
      if (hiddenBlockTypes && hiddenBlockTypes.length > 0) {
        const defaultAllowedBlockTypes = true === settings.allowedBlockTypes ? blockTypes.map(({ name: name2 }) => name2) : settings.allowedBlockTypes || [];
        return defaultAllowedBlockTypes.filter(
          (type) => !hiddenBlockTypes.includes(type)
        );
      }
      return settings.allowedBlockTypes;
    }, [settings.allowedBlockTypes, hiddenBlockTypes, blockTypes]);
    const forceDisableFocusMode = settings.focusMode === false;
    const inserterMediaCategories2 = (0, import_element201.useMemo)(
      () => getInserterMediaCategories(currentPostId, viewablePostTypeLabel),
      [currentPostId, viewablePostTypeLabel]
    );
    return (0, import_element201.useMemo)(() => {
      const blockEditorSettings = {
        ...Object.fromEntries(
          Object.entries(settings).filter(
            ([key]) => BLOCK_EDITOR_SETTINGS.includes(key)
          )
        ),
        [globalStylesDataKey]: globalStylesData,
        [globalStylesLinksDataKey]: globalStylesLinksData,
        allImageSizes,
        bigImageSizeThreshold,
        imageStripMeta,
        imageMaxBitDepth,
        allowedBlockTypes,
        allowRightClickOverrides,
        focusMode: focusMode && !forceDisableFocusMode,
        hasFixedToolbar,
        isDistractionFree,
        keepCaretInsideBlock,
        [getMediaSelectKey]: (select9, attachmentId) => {
          return select9(import_core_data45.store).getEntityRecord(
            "postType",
            "attachment",
            attachmentId
          );
        },
        [mediaEditKey]: hasUploadPermissions ? editMediaEntity : void 0,
        [openMediaEditorModalKey]: ({ id, onUpdate, onClose }) => openMediaEditorModal2({ id, onUpdate, onClose }),
        mediaUpload: hasUploadPermissions ? mediaUpload : void 0,
        [mediaUploadOnSuccessKey]: hasUploadPermissions ? mediaUploadOnSuccess : void 0,
        mediaSideload: hasUploadPermissions ? media_sideload_default : void 0,
        [mediaSideloadFromUrlKey]: hasUploadPermissions ? mediaSideloadFromUrl : void 0,
        mediaFinalize: hasUploadPermissions ? mediaFinalize : void 0,
        mediaDelete: hasUploadPermissions ? mediaDelete : void 0,
        __experimentalBlockPatterns: blockPatterns,
        [selectBlockPatternsKey]: (select9) => {
          const { hasFinishedResolution, getBlockPatternsForPostType } = unlock(select9(import_core_data45.store));
          const patterns2 = getBlockPatternsForPostType(postType2);
          return hasFinishedResolution("getBlockPatterns") ? patterns2 : void 0;
        },
        [reusableBlocksSelectKey]: __experimentalReusableBlocksSelect,
        [userPatternCategoriesSelectKey]: __experimentalUserPatternCategoriesSelect,
        __experimentalBlockPatternCategories: blockPatternCategories,
        __experimentalFetchLinkSuggestions: (search, searchOptions) => (0, import_core_data45.__experimentalFetchLinkSuggestions)(search, searchOptions, settings),
        inserterMediaCategories: inserterMediaCategories2,
        __experimentalFetchRichUrlData: import_core_data45.__experimentalFetchUrlData,
        // Todo: This only checks the top level post, not the post within a template or any other entity that can be edited.
        // This might be better as a generic "canUser" selector.
        __experimentalCanUserUseUnfilteredHTML: canUseUnfilteredHTML,
        //Todo: this is only needed for native and should probably be removed.
        __experimentalUndo: undo2,
        // Check whether we want all site editor frames to have outlines
        // including the navigation / pattern / parts editors.
        outlineMode: !isDistractionFree && postType2 === "wp_template",
        // Check these two properties: they were not present in the site editor.
        __experimentalCreatePageEntity: createPageEntity,
        __experimentalUserCanCreatePages: userCanCreatePages,
        pageOnFront,
        pageForPosts,
        __experimentalPreferPatternsOnRoot: postType2 === "wp_template",
        templateLock: postType2 === "wp_navigation" ? "insert" : settings.templateLock,
        template: postType2 === "wp_navigation" ? [["core/navigation", {}, []]] : settings.template,
        __experimentalSetIsInserterOpened: setIsInserterOpened2,
        [sectionRootClientIdKey]: sectionRootClientId,
        editorTool: renderingMode2 === "post-only" && postType2 !== "wp_template" ? "edit" : void 0,
        // When editing template parts, patterns, or navigation directly,
        // we're in an isolated editing context (focused on that entity alone).
        [isIsolatedEditorKey]: [
          "wp_template_part",
          "wp_block",
          "wp_navigation"
        ].includes(postType2),
        [isNavigationPostEditorKey]: postType2 === "wp_navigation",
        // When in template-locked mode (e.g., "Show Template" in the post editor),
        // don't treat template parts as contentOnly sections.
        disableContentOnlyForTemplateParts: renderingMode2 === "template-locked" || settings.disableContentOnlyForTemplateParts,
        ...deviceType ? { [deviceTypeKey]: deviceType } : {},
        [isNavigationOverlayContextKey]: isNavigationOverlayContext
      };
      if (isRevisionsMode2) {
        blockEditorSettings.isPreviewMode = true;
      }
      return blockEditorSettings;
    }, [
      isRevisionsMode2,
      allowedBlockTypes,
      allowRightClickOverrides,
      focusMode,
      forceDisableFocusMode,
      hasFixedToolbar,
      isDistractionFree,
      keepCaretInsideBlock,
      settings,
      hasUploadPermissions,
      blockPatterns,
      blockPatternCategories,
      inserterMediaCategories2,
      canUseUnfilteredHTML,
      undo2,
      createPageEntity,
      userCanCreatePages,
      pageOnFront,
      pageForPosts,
      postType2,
      setIsInserterOpened2,
      sectionRootClientId,
      globalStylesData,
      globalStylesLinksData,
      renderingMode2,
      editMediaEntity,
      openMediaEditorModal2,
      deviceType,
      allImageSizes,
      bigImageSizeThreshold,
      imageStripMeta,
      imageMaxBitDepth,
      isNavigationOverlayContext
    ]);
  }
  var use_block_editor_settings_default = useBlockEditorSettings;

  // packages/editor/build-module/components/provider/disable-non-page-content-blocks.mjs
  var import_data66 = __toESM(require_data(), 1);
  var import_block_editor22 = __toESM(require_block_editor(), 1);
  var import_element203 = __toESM(require_element(), 1);

  // packages/editor/build-module/components/provider/use-post-content-block-types.mjs
  var import_element202 = __toESM(require_element(), 1);
  var import_hooks36 = __toESM(require_hooks(), 1);
  var POST_CONTENT_BLOCK_TYPES = [
    "core/post-title",
    "core/post-featured-image",
    "core/post-content"
  ];
  function usePostContentBlockTypes() {
    return (0, import_element202.useMemo)(
      () => [
        ...(0, import_hooks36.applyFilters)(
          "editor.postContentBlockTypes",
          POST_CONTENT_BLOCK_TYPES
        )
      ],
      []
    );
  }

  // packages/editor/build-module/components/provider/disable-non-page-content-blocks.mjs
  function DisableNonPageContentBlocks() {
    const postContentBlockTypes = usePostContentBlockTypes();
    const { contentOnlyIds, templateParts } = (0, import_data66.useSelect)(
      (select9) => {
        const { getPostBlocksByName: getPostBlocksByName2 } = unlock(select9(store));
        const { getBlocksByName } = select9(import_block_editor22.store);
        return {
          contentOnlyIds: getPostBlocksByName2(postContentBlockTypes),
          templateParts: getBlocksByName("core/template-part")
        };
      },
      [postContentBlockTypes]
    );
    const templatePartChildren = (0, import_data66.useSelect)(
      (select9) => {
        const { getBlockOrder: getBlockOrder2 } = select9(import_block_editor22.store);
        return templateParts.flatMap(
          (clientId) => getBlockOrder2(clientId)
        );
      },
      [templateParts]
    );
    const registry = (0, import_data66.useRegistry)();
    (0, import_element203.useEffect)(() => {
      const {
        setBlockEditingMode,
        unsetBlockEditingMode,
        __unstableMarkNextChangeAsNotPersistent
      } = registry.dispatch(import_block_editor22.store);
      __unstableMarkNextChangeAsNotPersistent();
      setBlockEditingMode("", "disabled");
      return () => {
        __unstableMarkNextChangeAsNotPersistent();
        unsetBlockEditingMode("");
      };
    }, [registry]);
    (0, import_element203.useEffect)(() => {
      const {
        setBlockEditingMode,
        unsetBlockEditingMode,
        __unstableMarkNextChangeAsNotPersistent
      } = registry.dispatch(import_block_editor22.store);
      registry.batch(() => {
        for (const clientId of templateParts) {
          __unstableMarkNextChangeAsNotPersistent();
          setBlockEditingMode(clientId, "contentOnly");
        }
      });
      return () => {
        registry.batch(() => {
          for (const clientId of templateParts) {
            __unstableMarkNextChangeAsNotPersistent();
            unsetBlockEditingMode(clientId);
          }
        });
      };
    }, [templateParts, registry]);
    (0, import_element203.useEffect)(() => {
      const {
        setBlockEditingMode,
        unsetBlockEditingMode,
        __unstableMarkNextChangeAsNotPersistent
      } = registry.dispatch(import_block_editor22.store);
      const contentOnlySet = new Set(contentOnlyIds);
      registry.batch(() => {
        for (const clientId of contentOnlyIds) {
          __unstableMarkNextChangeAsNotPersistent();
          setBlockEditingMode(clientId, "contentOnly");
        }
        for (const clientId of templatePartChildren) {
          if (!contentOnlySet.has(clientId)) {
            __unstableMarkNextChangeAsNotPersistent();
            setBlockEditingMode(clientId, "disabled");
          }
        }
      });
      return () => {
        registry.batch(() => {
          for (const clientId of contentOnlyIds) {
            __unstableMarkNextChangeAsNotPersistent();
            unsetBlockEditingMode(clientId);
          }
          for (const clientId of templatePartChildren) {
            if (!contentOnlySet.has(clientId)) {
              __unstableMarkNextChangeAsNotPersistent();
              unsetBlockEditingMode(clientId);
            }
          }
        });
      };
    }, [contentOnlyIds, templatePartChildren, registry]);
    return null;
  }

  // packages/editor/build-module/components/provider/navigation-block-editing-mode.mjs
  var import_element204 = __toESM(require_element(), 1);
  var import_data67 = __toESM(require_data(), 1);
  var import_block_editor23 = __toESM(require_block_editor(), 1);
  function NavigationBlockEditingMode() {
    const registry = (0, import_data67.useRegistry)();
    const blockClientId = (0, import_data67.useSelect)(
      (select9) => select9(import_block_editor23.store).getBlockOrder()?.[0],
      []
    );
    (0, import_element204.useEffect)(() => {
      if (!blockClientId) {
        return;
      }
      const {
        setBlockEditingMode,
        unsetBlockEditingMode,
        __unstableMarkNextChangeAsNotPersistent
      } = registry.dispatch(import_block_editor23.store);
      __unstableMarkNextChangeAsNotPersistent();
      setBlockEditingMode(blockClientId, "contentOnly");
      return () => {
        __unstableMarkNextChangeAsNotPersistent();
        unsetBlockEditingMode(blockClientId);
      };
    }, [registry, blockClientId]);
  }

  // packages/editor/build-module/components/provider/use-hide-blocks-from-inserter.mjs
  var import_element205 = __toESM(require_element(), 1);
  var import_hooks37 = __toESM(require_hooks(), 1);
  var POST_TYPES_ALLOWING_POST_CONTENT_TEMPLATE_PART = [
    "wp_block",
    "wp_template",
    "wp_template_part"
  ];
  function useHideBlocksFromInserter(postType2, mode) {
    (0, import_element205.useEffect)(() => {
      (0, import_hooks37.addFilter)(
        "blockEditor.__unstableCanInsertBlockType",
        "removeTemplatePartsFromInserter",
        (canInsert, blockType) => {
          if (!POST_TYPES_ALLOWING_POST_CONTENT_TEMPLATE_PART.includes(
            postType2
          ) && blockType.name === "core/template-part" && mode === "post-only") {
            return false;
          }
          return canInsert;
        }
      );
      (0, import_hooks37.addFilter)(
        "blockEditor.__unstableCanInsertBlockType",
        "removePostContentFromInserter",
        (canInsert, blockType, rootClientId, { getBlockParentsByBlockName }) => {
          if (!POST_TYPES_ALLOWING_POST_CONTENT_TEMPLATE_PART.includes(
            postType2
          ) && blockType.name === "core/post-content") {
            return getBlockParentsByBlockName(rootClientId, "core/query").length > 0;
          }
          return canInsert;
        }
      );
      return () => {
        (0, import_hooks37.removeFilter)(
          "blockEditor.__unstableCanInsertBlockType",
          "removeTemplatePartsFromInserter"
        );
        (0, import_hooks37.removeFilter)(
          "blockEditor.__unstableCanInsertBlockType",
          "removePostContentFromInserter"
        );
      };
    }, [postType2, mode]);
  }

  // packages/editor/build-module/components/provider/use-revision-blocks.mjs
  var import_data68 = __toESM(require_data(), 1);
  var import_element206 = __toESM(require_element(), 1);
  var import_blocks14 = __toESM(require_blocks(), 1);

  // node_modules/diff/libesm/diff/base.js
  var Diff = class {
    diff(oldStr, newStr, options = {}) {
      let callback;
      if (typeof options === "function") {
        callback = options;
        options = {};
      } else if ("callback" in options) {
        callback = options.callback;
      }
      const oldString = this.castInput(oldStr, options);
      const newString = this.castInput(newStr, options);
      const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
      const newTokens = this.removeEmpty(this.tokenize(newString, options));
      return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
    }
    diffWithOptionsObj(oldTokens, newTokens, options, callback) {
      var _a;
      const done = (value) => {
        value = this.postProcess(value, options);
        if (callback) {
          setTimeout(function() {
            callback(value);
          }, 0);
          return void 0;
        } else {
          return value;
        }
      };
      const newLen = newTokens.length, oldLen = oldTokens.length;
      let editLength = 1;
      let maxEditLength = newLen + oldLen;
      if (options.maxEditLength != null) {
        maxEditLength = Math.min(maxEditLength, options.maxEditLength);
      }
      const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;
      const abortAfterTimestamp = Date.now() + maxExecutionTime;
      const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
      let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
      if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
        return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
      }
      let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
      const execEditLength = () => {
        for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
          let basePath;
          const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
          if (removePath) {
            bestPath[diagonalPath - 1] = void 0;
          }
          let canAdd = false;
          if (addPath) {
            const addPathNewPos = addPath.oldPos - diagonalPath;
            canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
          }
          const canRemove = removePath && removePath.oldPos + 1 < oldLen;
          if (!canAdd && !canRemove) {
            bestPath[diagonalPath] = void 0;
            continue;
          }
          if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
            basePath = this.addToPath(addPath, true, false, 0, options);
          } else {
            basePath = this.addToPath(removePath, false, true, 1, options);
          }
          newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
          if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
            return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
          } else {
            bestPath[diagonalPath] = basePath;
            if (basePath.oldPos + 1 >= oldLen) {
              maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
            }
            if (newPos + 1 >= newLen) {
              minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
            }
          }
        }
        editLength++;
      };
      if (callback) {
        (function exec() {
          setTimeout(function() {
            if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
              return callback(void 0);
            }
            if (!execEditLength()) {
              exec();
            }
          }, 0);
        })();
      } else {
        while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
          const ret = execEditLength();
          if (ret) {
            return ret;
          }
        }
      }
    }
    addToPath(path, added, removed, oldPosInc, options) {
      const last = path.lastComponent;
      if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
        return {
          oldPos: path.oldPos + oldPosInc,
          lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
        };
      } else {
        return {
          oldPos: path.oldPos + oldPosInc,
          lastComponent: { count: 1, added, removed, previousComponent: last }
        };
      }
    }
    extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
      const newLen = newTokens.length, oldLen = oldTokens.length;
      let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
      while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
        newPos++;
        oldPos++;
        commonCount++;
        if (options.oneChangePerToken) {
          basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
        }
      }
      if (commonCount && !options.oneChangePerToken) {
        basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
      }
      basePath.oldPos = oldPos;
      return newPos;
    }
    equals(left, right, options) {
      if (options.comparator) {
        return options.comparator(left, right);
      } else {
        return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
      }
    }
    removeEmpty(array) {
      const ret = [];
      for (let i3 = 0; i3 < array.length; i3++) {
        if (array[i3]) {
          ret.push(array[i3]);
        }
      }
      return ret;
    }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    castInput(value, options) {
      return value;
    }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    tokenize(value, options) {
      return Array.from(value);
    }
    join(chars) {
      return chars.join("");
    }
    postProcess(changeObjects, options) {
      return changeObjects;
    }
    get useLongestToken() {
      return false;
    }
    buildValues(lastComponent, newTokens, oldTokens) {
      const components = [];
      let nextComponent;
      while (lastComponent) {
        components.push(lastComponent);
        nextComponent = lastComponent.previousComponent;
        delete lastComponent.previousComponent;
        lastComponent = nextComponent;
      }
      components.reverse();
      const componentLen = components.length;
      let componentPos = 0, newPos = 0, oldPos = 0;
      for (; componentPos < componentLen; componentPos++) {
        const component = components[componentPos];
        if (!component.removed) {
          if (!component.added && this.useLongestToken) {
            let value = newTokens.slice(newPos, newPos + component.count);
            value = value.map(function(value2, i3) {
              const oldValue = oldTokens[oldPos + i3];
              return oldValue.length > value2.length ? oldValue : value2;
            });
            component.value = this.join(value);
          } else {
            component.value = this.join(newTokens.slice(newPos, newPos + component.count));
          }
          newPos += component.count;
          if (!component.added) {
            oldPos += component.count;
          }
        } else {
          component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
          oldPos += component.count;
        }
      }
      return components;
    }
  };

  // node_modules/diff/libesm/diff/character.js
  var CharacterDiff = class extends Diff {
  };
  var characterDiff = new CharacterDiff();
  function diffChars(oldStr, newStr, options) {
    return characterDiff.diff(oldStr, newStr, options);
  }

  // node_modules/diff/libesm/util/string.js
  function longestCommonPrefix(str1, str22) {
    let i3;
    for (i3 = 0; i3 < str1.length && i3 < str22.length; i3++) {
      if (str1[i3] != str22[i3]) {
        return str1.slice(0, i3);
      }
    }
    return str1.slice(0, i3);
  }
  function longestCommonSuffix(str1, str22) {
    let i3;
    if (!str1 || !str22 || str1[str1.length - 1] != str22[str22.length - 1]) {
      return "";
    }
    for (i3 = 0; i3 < str1.length && i3 < str22.length; i3++) {
      if (str1[str1.length - (i3 + 1)] != str22[str22.length - (i3 + 1)]) {
        return str1.slice(-i3);
      }
    }
    return str1.slice(-i3);
  }
  function replacePrefix(string, oldPrefix, newPrefix) {
    if (string.slice(0, oldPrefix.length) != oldPrefix) {
      throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`);
    }
    return newPrefix + string.slice(oldPrefix.length);
  }
  function replaceSuffix(string, oldSuffix, newSuffix) {
    if (!oldSuffix) {
      return string + newSuffix;
    }
    if (string.slice(-oldSuffix.length) != oldSuffix) {
      throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`);
    }
    return string.slice(0, -oldSuffix.length) + newSuffix;
  }
  function removePrefix(string, oldPrefix) {
    return replacePrefix(string, oldPrefix, "");
  }
  function removeSuffix(string, oldSuffix) {
    return replaceSuffix(string, oldSuffix, "");
  }
  function maximumOverlap(string1, string2) {
    return string2.slice(0, overlapCount(string1, string2));
  }
  function overlapCount(a3, b3) {
    let startA = 0;
    if (a3.length > b3.length) {
      startA = a3.length - b3.length;
    }
    let endB = b3.length;
    if (a3.length < b3.length) {
      endB = a3.length;
    }
    const map = Array(endB);
    let k2 = 0;
    map[0] = 0;
    for (let j2 = 1; j2 < endB; j2++) {
      if (b3[j2] == b3[k2]) {
        map[j2] = map[k2];
      } else {
        map[j2] = k2;
      }
      while (k2 > 0 && b3[j2] != b3[k2]) {
        k2 = map[k2];
      }
      if (b3[j2] == b3[k2]) {
        k2++;
      }
    }
    k2 = 0;
    for (let i3 = startA; i3 < a3.length; i3++) {
      while (k2 > 0 && a3[i3] != b3[k2]) {
        k2 = map[k2];
      }
      if (a3[i3] == b3[k2]) {
        k2++;
      }
    }
    return k2;
  }
  function segment(string, segmenter) {
    const parts = [];
    for (const segmentObj of Array.from(segmenter.segment(string))) {
      const segment2 = segmentObj.segment;
      if (parts.length && /\s/.test(parts[parts.length - 1]) && /\s/.test(segment2)) {
        parts[parts.length - 1] += segment2;
      } else {
        parts.push(segment2);
      }
    }
    return parts;
  }
  function trailingWs(string, segmenter) {
    if (segmenter) {
      return leadingAndTrailingWs(string, segmenter)[1];
    }
    let i3;
    for (i3 = string.length - 1; i3 >= 0; i3--) {
      if (!string[i3].match(/\s/)) {
        break;
      }
    }
    return string.substring(i3 + 1);
  }
  function leadingWs(string, segmenter) {
    if (segmenter) {
      return leadingAndTrailingWs(string, segmenter)[0];
    }
    const match3 = string.match(/^\s*/);
    return match3 ? match3[0] : "";
  }
  function leadingAndTrailingWs(string, segmenter) {
    if (!segmenter) {
      return [leadingWs(string), trailingWs(string)];
    }
    if (segmenter.resolvedOptions().granularity != "word") {
      throw new Error('The segmenter passed must have a granularity of "word"');
    }
    const segments = segment(string, segmenter);
    const firstSeg = segments[0];
    const lastSeg = segments[segments.length - 1];
    const head2 = /\s/.test(firstSeg) ? firstSeg : "";
    const tail = /\s/.test(lastSeg) ? lastSeg : "";
    return [head2, tail];
  }

  // node_modules/diff/libesm/diff/word.js
  var extendedWordChars = "a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}";
  var tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\s+|[^${extendedWordChars}]`, "ug");
  var WordDiff = class extends Diff {
    equals(left, right, options) {
      if (options.ignoreCase) {
        left = left.toLowerCase();
        right = right.toLowerCase();
      }
      return left.trim() === right.trim();
    }
    tokenize(value, options = {}) {
      let parts;
      if (options.intlSegmenter) {
        const segmenter = options.intlSegmenter;
        if (segmenter.resolvedOptions().granularity != "word") {
          throw new Error('The segmenter passed must have a granularity of "word"');
        }
        parts = segment(value, segmenter);
      } else {
        parts = value.match(tokenizeIncludingWhitespace) || [];
      }
      const tokens = [];
      let prevPart = null;
      parts.forEach((part) => {
        if (/\s/.test(part)) {
          if (prevPart == null) {
            tokens.push(part);
          } else {
            tokens.push(tokens.pop() + part);
          }
        } else if (prevPart != null && /\s/.test(prevPart)) {
          if (tokens[tokens.length - 1] == prevPart) {
            tokens.push(tokens.pop() + part);
          } else {
            tokens.push(prevPart + part);
          }
        } else {
          tokens.push(part);
        }
        prevPart = part;
      });
      return tokens;
    }
    join(tokens) {
      return tokens.map((token, i3) => {
        if (i3 == 0) {
          return token;
        } else {
          return token.replace(/^\s+/, "");
        }
      }).join("");
    }
    postProcess(changes, options) {
      if (!changes || options.oneChangePerToken) {
        return changes;
      }
      let lastKeep = null;
      let insertion = null;
      let deletion = null;
      changes.forEach((change) => {
        if (change.added) {
          insertion = change;
        } else if (change.removed) {
          deletion = change;
        } else {
          if (insertion || deletion) {
            dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change, options.intlSegmenter);
          }
          lastKeep = change;
          insertion = null;
          deletion = null;
        }
      });
      if (insertion || deletion) {
        dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null, options.intlSegmenter);
      }
      return changes;
    }
  };
  var wordDiff = new WordDiff();
  function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep, segmenter) {
    if (deletion && insertion) {
      const [oldWsPrefix, oldWsSuffix] = leadingAndTrailingWs(deletion.value, segmenter);
      const [newWsPrefix, newWsSuffix] = leadingAndTrailingWs(insertion.value, segmenter);
      if (startKeep) {
        const commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);
        startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);
        deletion.value = removePrefix(deletion.value, commonWsPrefix);
        insertion.value = removePrefix(insertion.value, commonWsPrefix);
      }
      if (endKeep) {
        const commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);
        endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);
        deletion.value = removeSuffix(deletion.value, commonWsSuffix);
        insertion.value = removeSuffix(insertion.value, commonWsSuffix);
      }
    } else if (insertion) {
      if (startKeep) {
        const ws = leadingWs(insertion.value, segmenter);
        insertion.value = insertion.value.substring(ws.length);
      }
      if (endKeep) {
        const ws = leadingWs(endKeep.value, segmenter);
        endKeep.value = endKeep.value.substring(ws.length);
      }
    } else if (startKeep && endKeep) {
      const newWsFull = leadingWs(endKeep.value, segmenter), [delWsStart, delWsEnd] = leadingAndTrailingWs(deletion.value, segmenter);
      const newWsStart = longestCommonPrefix(newWsFull, delWsStart);
      deletion.value = removePrefix(deletion.value, newWsStart);
      const newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd);
      deletion.value = removeSuffix(deletion.value, newWsEnd);
      endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);
      startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length));
    } else if (endKeep) {
      const endKeepWsPrefix = leadingWs(endKeep.value, segmenter);
      const deletionWsSuffix = trailingWs(deletion.value, segmenter);
      const overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
      deletion.value = removeSuffix(deletion.value, overlap);
    } else if (startKeep) {
      const startKeepWsSuffix = trailingWs(startKeep.value, segmenter);
      const deletionWsPrefix = leadingWs(deletion.value, segmenter);
      const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);
      deletion.value = removePrefix(deletion.value, overlap);
    }
  }
  var WordsWithSpaceDiff = class extends Diff {
    tokenize(value) {
      const regex = new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`, "ug");
      return value.match(regex) || [];
    }
  };
  var wordsWithSpaceDiff = new WordsWithSpaceDiff();
  function diffWordsWithSpace(oldStr, newStr, options) {
    return wordsWithSpaceDiff.diff(oldStr, newStr, options);
  }

  // node_modules/diff/libesm/diff/line.js
  var LineDiff = class extends Diff {
    constructor() {
      super(...arguments);
      this.tokenize = tokenize;
    }
    equals(left, right, options) {
      if (options.ignoreWhitespace) {
        if (!options.newlineIsToken || !left.includes("\n")) {
          left = left.trim();
        }
        if (!options.newlineIsToken || !right.includes("\n")) {
          right = right.trim();
        }
      } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
        if (left.endsWith("\n")) {
          left = left.slice(0, -1);
        }
        if (right.endsWith("\n")) {
          right = right.slice(0, -1);
        }
      }
      return super.equals(left, right, options);
    }
  };
  var lineDiff = new LineDiff();
  function diffLines(oldStr, newStr, options) {
    return lineDiff.diff(oldStr, newStr, options);
  }
  function tokenize(value, options) {
    if (options.stripTrailingCr) {
      value = value.replace(/\r\n/g, "\n");
    }
    const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
    if (!linesAndNewlines[linesAndNewlines.length - 1]) {
      linesAndNewlines.pop();
    }
    for (let i3 = 0; i3 < linesAndNewlines.length; i3++) {
      const line = linesAndNewlines[i3];
      if (i3 % 2 && !options.newlineIsToken) {
        retLines[retLines.length - 1] += line;
      } else {
        retLines.push(line);
      }
    }
    return retLines;
  }

  // node_modules/diff/libesm/diff/array.js
  var ArrayDiff = class extends Diff {
    tokenize(value) {
      return value.slice();
    }
    join(value) {
      return value;
    }
    removeEmpty(value) {
      return value;
    }
  };
  var arrayDiff = new ArrayDiff();
  function diffArrays(oldArr, newArr, options) {
    return arrayDiff.diff(oldArr, newArr, options);
  }

  // packages/editor/build-module/components/post-revisions-preview/block-diff.mjs
  var import_block_serialization_default_parser = __toESM(require_block_serialization_default_parser(), 1);
  var import_blocks13 = __toESM(require_blocks(), 1);
  var import_rich_text4 = __toESM(require_rich_text(), 1);
  var import_i18n192 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/components/post-revisions-preview/diff-format-types.mjs
  var import_i18n191 = __toESM(require_i18n(), 1);
  var import_rich_text3 = __toESM(require_rich_text(), 1);
  var DIFF_DESCRIPTION_IDS = {
    removed: "revision-diff-removed-desc",
    added: "revision-diff-added-desc",
    formatAdded: "revision-diff-format-added-desc",
    formatRemoved: "revision-diff-format-removed-desc",
    formatChanged: "revision-diff-format-changed-desc"
  };
  var DIFF_FORMAT_TYPES = [
    {
      name: "revision/diff-removed",
      title: (0, import_i18n191.__)("Removed"),
      tagName: "del",
      className: "revision-diff-removed"
    },
    {
      name: "revision/diff-added",
      title: (0, import_i18n191.__)("Added"),
      tagName: "ins",
      className: "revision-diff-added"
    },
    {
      name: "revision/diff-format-added",
      title: (0, import_i18n191.__)("Format added"),
      tagName: "mark",
      className: "revision-diff-format-added"
    },
    {
      name: "revision/diff-format-removed",
      title: (0, import_i18n191.__)("Format removed"),
      tagName: "mark",
      className: "revision-diff-format-removed"
    },
    {
      name: "revision/diff-format-changed",
      title: (0, import_i18n191.__)("Format changed"),
      tagName: "mark",
      className: "revision-diff-format-changed"
    }
  ];
  function registerDiffFormatTypes() {
    for (const formatType of DIFF_FORMAT_TYPES) {
      (0, import_rich_text3.registerFormatType)(formatType.name, {
        ...formatType,
        attributes: { "aria-describedby": "aria-describedby" },
        edit: () => null
      });
    }
  }
  function unregisterDiffFormatTypes() {
    for (const formatType of DIFF_FORMAT_TYPES) {
      (0, import_rich_text3.unregisterFormatType)(formatType.name);
    }
  }

  // packages/editor/build-module/components/post-revisions-preview/block-diff.mjs
  var { parseRawBlock } = unlock(import_blocks13.privateApis);
  function isWhitespaceRawBlock(rawBlock) {
    return rawBlock.blockName === null && (!rawBlock.innerHTML || !rawBlock.innerHTML.trim());
  }
  function stringifyValue(value) {
    if (value === null || value === void 0) {
      return "";
    }
    if (typeof value === "object") {
      return JSON.stringify(value, null, 2);
    }
    return String(value);
  }
  function textSimilarity(text1, text2) {
    if (!text1 && !text2) {
      return 1;
    }
    if (!text1 || !text2) {
      return 0;
    }
    const segmenter = new Intl.Segmenter(void 0, {
      granularity: "word"
    });
    const wordLikeRegex = /[\p{L}\p{N}]/u;
    const getWords = (text) => {
      const words = [];
      for (const { segment: segment2, isWordLike } of segmenter.segment(text)) {
        if (isWordLike || wordLikeRegex.test(segment2)) {
          words.push(segment2);
        }
      }
      return words;
    };
    const words1 = getWords(text1);
    const words2 = getWords(text2);
    if (words1.length === 0 && words2.length === 0) {
      return 1;
    }
    const set1 = new Set(words1);
    let intersection = 0;
    for (const word of words2) {
      if (set1.has(word)) {
        intersection++;
      }
    }
    const total = Math.max(words1.length, words2.length);
    return total > 0 ? intersection / total : 0;
  }
  function pairSimilarBlocks(blocks) {
    const removed = [];
    const added = [];
    blocks.forEach((block, index2) => {
      const status = block.__revisionDiffStatus?.status;
      if (status === "removed") {
        removed.push({ block, index: index2 });
      } else if (status === "added") {
        added.push({ block, index: index2 });
      }
    });
    if (removed.length === 0 || added.length === 0) {
      return blocks;
    }
    const pairedRemoved = /* @__PURE__ */ new Set();
    const pairedAdded = /* @__PURE__ */ new Set();
    const modifications = /* @__PURE__ */ new Map();
    const SIMILARITY_THRESHOLD = 0.5;
    const addedByName = /* @__PURE__ */ new Map();
    for (const add3 of added) {
      const name2 = add3.block.blockName;
      if (!addedByName.has(name2)) {
        addedByName.set(name2, []);
      }
      addedByName.get(name2).push(add3);
    }
    const removedByName = /* @__PURE__ */ new Map();
    for (const rem of removed) {
      const name2 = rem.block.blockName;
      if (!removedByName.has(name2)) {
        removedByName.set(name2, []);
      }
      removedByName.get(name2).push(rem);
    }
    let maxPairedAddedIndex = -1;
    for (const rem of removed) {
      const candidates = addedByName.get(rem.block.blockName) || [];
      const sameNameRemoved = removedByName.get(rem.block.blockName) || [];
      const unpaired = candidates.filter(
        (add3) => !modifications.has(add3.index) && add3.index > maxPairedAddedIndex
      );
      if (unpaired.length === 0) {
        continue;
      }
      let bestMatch = null;
      if (sameNameRemoved.length === 1 && unpaired.length === 1) {
        const add3 = unpaired[0];
        const attrsMatch = JSON.stringify(rem.block.attrs) === JSON.stringify(add3.block.attrs);
        const contentMatch = (rem.block.innerHTML || "") === (add3.block.innerHTML || "");
        if (!contentMatch || !attrsMatch) {
          bestMatch = add3;
        }
      } else {
        let bestScore = 0;
        for (const add3 of unpaired) {
          const score = textSimilarity(
            rem.block.innerHTML || "",
            add3.block.innerHTML || ""
          );
          const attrsMatch = JSON.stringify(rem.block.attrs) === JSON.stringify(add3.block.attrs);
          if (score > bestScore && score > SIMILARITY_THRESHOLD && (score < 1 || !attrsMatch)) {
            bestScore = score;
            bestMatch = add3;
          }
        }
      }
      if (bestMatch) {
        maxPairedAddedIndex = bestMatch.index;
        const modifiedBlock = {
          ...bestMatch.block,
          __revisionDiffStatus: { status: "modified" },
          __previousRawBlock: rem.block
        };
        const lo = Math.min(rem.index, bestMatch.index);
        const hi = Math.max(rem.index, bestMatch.index);
        let crossesCurrentContent = false;
        for (let i3 = lo + 1; i3 < hi; i3++) {
          const status = blocks[i3].__revisionDiffStatus?.status;
          if (status === void 0) {
            crossesCurrentContent = true;
            break;
          }
          if (status === "added" && !pairedAdded.has(i3)) {
            crossesCurrentContent = true;
            break;
          }
        }
        if (crossesCurrentContent) {
          modifications.set(bestMatch.index, modifiedBlock);
          pairedRemoved.add(rem.index);
        } else {
          modifications.set(rem.index, modifiedBlock);
          pairedAdded.add(bestMatch.index);
        }
      }
    }
    return blocks.map((block, index2) => {
      if (pairedRemoved.has(index2) || pairedAdded.has(index2)) {
        return null;
      }
      if (modifications.has(index2)) {
        return modifications.get(index2);
      }
      return block;
    }).filter(Boolean);
  }
  function diffRawBlocks(currentRaw, previousRaw) {
    currentRaw = currentRaw.filter((b3) => !isWhitespaceRawBlock(b3));
    previousRaw = previousRaw.filter((b3) => !isWhitespaceRawBlock(b3));
    const createBlockSignature = (rawBlock) => JSON.stringify({
      name: rawBlock.blockName,
      attrs: rawBlock.attrs,
      // Use innerContent filtered to non-null and non-whitespace-only strings.
      // This excludes whitespace between inner blocks which changes based on count.
      html: (rawBlock.innerContent || []).filter(
        (c6) => c6 !== null && c6.trim() !== ""
      )
    });
    const currentSigs = currentRaw.map(createBlockSignature);
    const previousSigs = previousRaw.map(createBlockSignature);
    const diff = diffArrays(previousSigs, currentSigs);
    const result = [];
    let currIdx = 0;
    let prevIdx = 0;
    for (const part of diff) {
      if (part.added) {
        for (let i3 = 0; i3 < part.count; i3++) {
          result.push({
            ...currentRaw[currIdx++],
            __revisionDiffStatus: { status: "added" }
          });
        }
      } else if (part.removed) {
        for (let i3 = 0; i3 < part.count; i3++) {
          result.push({
            ...previousRaw[prevIdx++],
            __revisionDiffStatus: { status: "removed" }
          });
        }
      } else {
        for (let i3 = 0; i3 < part.count; i3++) {
          const currBlock = currentRaw[currIdx++];
          const prevBlock = previousRaw[prevIdx++];
          const diffedInnerBlocks = diffRawBlocks(
            currBlock.innerBlocks || [],
            prevBlock.innerBlocks || []
          );
          result.push({
            ...currBlock,
            innerBlocks: diffedInnerBlocks
          });
        }
      }
    }
    return pairSimilarBlocks(result);
  }
  function hasFormatChangedAtIndex(currentFormats, previousFormats, currentIndex, previousIndex) {
    const currFmts = currentFormats[currentIndex] || [];
    const prevFmts = previousFormats[previousIndex] || [];
    if (currFmts.length !== prevFmts.length) {
      return true;
    }
    for (const fmt of currFmts) {
      const match3 = prevFmts.find(
        (pf) => pf.type === fmt.type && JSON.stringify(pf.attributes) === JSON.stringify(fmt.attributes)
      );
      if (!match3) {
        return true;
      }
    }
    return false;
  }
  function describeFormatChange(currentFormats, previousFormats, currIdx, prevIdx) {
    const currFmts = currentFormats[currIdx] || [];
    const prevFmts = previousFormats[prevIdx] || [];
    let addedCount = 0;
    let removedCount = 0;
    let changedCount = 0;
    for (const fmt of currFmts) {
      const match3 = prevFmts.find((pf) => pf.type === fmt.type);
      if (!match3) {
        addedCount++;
      } else if (JSON.stringify(fmt.attributes) !== JSON.stringify(match3.attributes)) {
        changedCount++;
      }
    }
    for (const fmt of prevFmts) {
      const match3 = currFmts.find((cf) => cf.type === fmt.type);
      if (!match3) {
        removedCount++;
      }
    }
    if (addedCount > 0 && removedCount === 0 && changedCount === 0) {
      return {
        type: "added",
        description: (0, import_i18n192.sprintf)(
          /* translators: %d: number of formats added */
          (0, import_i18n192._n)("%d format added", "%d formats added", addedCount),
          addedCount
        )
      };
    }
    if (removedCount > 0 && addedCount === 0 && changedCount === 0) {
      return {
        type: "removed",
        description: (0, import_i18n192.sprintf)(
          /* translators: %d: number of formats removed */
          (0, import_i18n192._n)("%d format removed", "%d formats removed", removedCount),
          removedCount
        )
      };
    }
    const parts = [];
    if (addedCount > 0) {
      parts.push(
        (0, import_i18n192.sprintf)(
          /* translators: %d: number of formats added */
          (0, import_i18n192._n)("%d format added", "%d formats added", addedCount),
          addedCount
        )
      );
    }
    if (removedCount > 0) {
      parts.push(
        (0, import_i18n192.sprintf)(
          /* translators: %d: number of formats removed */
          (0, import_i18n192._n)("%d format removed", "%d formats removed", removedCount),
          removedCount
        )
      );
    }
    if (changedCount > 0) {
      parts.push(
        (0, import_i18n192.sprintf)(
          /* translators: %d: number of formats changed */
          (0, import_i18n192._n)("%d format changed", "%d formats changed", changedCount),
          changedCount
        )
      );
    }
    return {
      type: "changed",
      description: parts.join(", ") || (0, import_i18n192.__)("Formatting changed")
    };
  }
  function applyRichTextDiff(currentRichText, previousRichText) {
    const currentText = currentRichText.toPlainText();
    const previousText = previousRichText.toPlainText();
    const textDiff = diffWordsWithSpace(previousText, currentText);
    let result = (0, import_rich_text4.create)({ text: "" });
    let currentIdx = 0;
    let previousIdx = 0;
    for (const part of textDiff) {
      if (part.removed) {
        const removedSlice = (0, import_rich_text4.slice)(
          previousRichText,
          previousIdx,
          previousIdx + part.value.length
        );
        const formatted = (0, import_rich_text4.applyFormat)(
          removedSlice,
          {
            type: "revision/diff-removed",
            attributes: {
              "aria-describedby": DIFF_DESCRIPTION_IDS.removed
            }
          },
          0,
          part.value.length
        );
        result = (0, import_rich_text4.concat)(result, formatted);
        previousIdx += part.value.length;
      } else if (part.added) {
        const addedSlice = (0, import_rich_text4.slice)(
          currentRichText,
          currentIdx,
          currentIdx + part.value.length
        );
        const formatted = (0, import_rich_text4.applyFormat)(
          addedSlice,
          {
            type: "revision/diff-added",
            attributes: {
              "aria-describedby": DIFF_DESCRIPTION_IDS.added
            }
          },
          0,
          part.value.length
        );
        result = (0, import_rich_text4.concat)(result, formatted);
        currentIdx += part.value.length;
      } else {
        const currentFormats = currentRichText.formats || [];
        const previousFormats = previousRichText.formats || [];
        const len2 = part.value.length;
        const checkFormatChanged = (offset4) => hasFormatChangedAtIndex(
          currentFormats,
          previousFormats,
          currentIdx + offset4,
          previousIdx + offset4
        );
        let rangeStart = 0;
        let rangeFormatChanged = checkFormatChanged(0);
        for (let i3 = 1; i3 <= len2; i3++) {
          const formatChanged = i3 < len2 && checkFormatChanged(i3);
          if (i3 === len2 || formatChanged !== rangeFormatChanged) {
            const rangeSlice = (0, import_rich_text4.slice)(
              currentRichText,
              currentIdx + rangeStart,
              currentIdx + i3
            );
            if (rangeFormatChanged) {
              const { type } = describeFormatChange(
                currentFormats,
                previousFormats,
                currentIdx + rangeStart,
                previousIdx + rangeStart
              );
              const formatType = {
                added: "revision/diff-format-added",
                removed: "revision/diff-format-removed",
                changed: "revision/diff-format-changed"
              }[type];
              const descriptionId = {
                added: DIFF_DESCRIPTION_IDS.formatAdded,
                removed: DIFF_DESCRIPTION_IDS.formatRemoved,
                changed: DIFF_DESCRIPTION_IDS.formatChanged
              }[type];
              const marked = (0, import_rich_text4.applyFormat)(
                rangeSlice,
                {
                  type: formatType,
                  attributes: {
                    "aria-describedby": descriptionId
                  }
                },
                0,
                i3 - rangeStart
              );
              result = (0, import_rich_text4.concat)(result, marked);
            } else {
              result = (0, import_rich_text4.concat)(result, rangeSlice);
            }
            rangeStart = i3;
            rangeFormatChanged = formatChanged;
          }
        }
        currentIdx += part.value.length;
        previousIdx += part.value.length;
      }
    }
    return new import_rich_text4.RichTextData(result);
  }
  function applyDiffToBlock(currentBlock, previousBlock, diffStatus) {
    const blockType = (0, import_blocks13.getBlockType)(currentBlock.name);
    if (!blockType) {
      return;
    }
    const changedAttributes = {};
    for (const [attrName, attrDef] of Object.entries(
      blockType.attributes
    )) {
      if (attrDef.source === "rich-text") {
        const currentRichText = currentBlock.attributes[attrName];
        const previousRichText = previousBlock.attributes[attrName];
        if (currentRichText instanceof import_rich_text4.RichTextData && previousRichText instanceof import_rich_text4.RichTextData) {
          currentBlock.attributes[attrName] = applyRichTextDiff(
            currentRichText,
            previousRichText
          );
        }
      } else {
        const currStr = stringifyValue(
          currentBlock.attributes[attrName]
        );
        const prevStr = stringifyValue(
          previousBlock.attributes[attrName]
        );
        if (currStr !== prevStr) {
          changedAttributes[attrName] = diffWordsWithSpace(
            prevStr,
            currStr
          );
        }
      }
    }
    if (Object.keys(changedAttributes).length > 0) {
      diffStatus.changedAttributes = changedAttributes;
    }
  }
  function applyDiffRecursively(parsedBlock, rawBlock) {
    if (rawBlock.__revisionDiffStatus) {
      if (rawBlock.__revisionDiffStatus.status === "modified" && rawBlock.__previousRawBlock) {
        const previousParsed = parseRawBlock(rawBlock.__previousRawBlock);
        if (previousParsed) {
          applyDiffToBlock(
            parsedBlock,
            previousParsed,
            rawBlock.__revisionDiffStatus
          );
        }
      }
      parsedBlock.__revisionDiffStatus = rawBlock.__revisionDiffStatus;
      parsedBlock.attributes.__revisionDiffStatus = rawBlock.__revisionDiffStatus;
    }
    if (parsedBlock.innerBlocks && rawBlock.innerBlocks) {
      for (let i3 = 0; i3 < parsedBlock.innerBlocks.length; i3++) {
        const parsedInner = parsedBlock.innerBlocks[i3];
        const rawInner = rawBlock.innerBlocks[i3];
        if (parsedInner && rawInner) {
          applyDiffRecursively(parsedInner, rawInner);
        }
      }
    }
  }
  function diffRevisionContent(currentContent, previousContent) {
    const currentRaw = (0, import_block_serialization_default_parser.parse)(currentContent || "");
    const previousRaw = (0, import_block_serialization_default_parser.parse)(previousContent || "");
    const mergedRaw = diffRawBlocks(currentRaw, previousRaw);
    return mergedRaw.map((rawBlock) => {
      const parsed = parseRawBlock(rawBlock);
      if (parsed) {
        applyDiffRecursively(parsed, rawBlock);
      }
      return parsed;
    }).filter(Boolean);
  }

  // packages/editor/build-module/components/post-revisions-preview/preserve-client-ids.mjs
  function preserveClientIds(newBlocks, prevBlocks) {
    if (!prevBlocks?.length || !newBlocks?.length) {
      return newBlocks;
    }
    const newSigs = newBlocks.map((block) => block.name);
    const prevSigs = prevBlocks.map((block) => block.name);
    const diffResult = diffArrays(prevSigs, newSigs);
    let newIndex = 0;
    let prevIndex = 0;
    const result = [];
    for (const chunk2 of diffResult) {
      if (chunk2.removed) {
        prevIndex += chunk2.count;
      } else if (chunk2.added) {
        for (let i3 = 0; i3 < chunk2.count; i3++) {
          result.push(newBlocks[newIndex++]);
        }
      } else {
        for (let i3 = 0; i3 < chunk2.count; i3++) {
          const newBlock = newBlocks[newIndex++];
          const prevBlock = prevBlocks[prevIndex++];
          result.push({
            ...newBlock,
            clientId: prevBlock.clientId,
            innerBlocks: preserveClientIds(
              newBlock.innerBlocks,
              prevBlock.innerBlocks
            )
          });
        }
      }
    }
    return result;
  }

  // packages/editor/build-module/components/provider/use-revision-blocks.mjs
  function useRevisionBlocks() {
    const {
      isInRevisionsMode,
      showDiff,
      revision,
      previousRevision,
      postType: postType2
    } = (0, import_data68.useSelect)((select9) => {
      const {
        isRevisionsMode: isRevisionsMode2,
        isShowingRevisionDiff: isShowingRevisionDiff2,
        getCurrentRevision: getCurrentRevision2,
        getPreviousRevision: getPreviousRevision2
      } = unlock(select9(store));
      const { getCurrentPostType: getCurrentPostType2 } = select9(store);
      const inRevisions = isRevisionsMode2();
      return {
        isInRevisionsMode: inRevisions,
        showDiff: isShowingRevisionDiff2(),
        revision: inRevisions ? getCurrentRevision2() : void 0,
        previousRevision: inRevisions ? getPreviousRevision2() : void 0,
        postType: getCurrentPostType2()
      };
    }, []);
    const previousBlocksRef = (0, import_element206.useRef)([]);
    const blocks = (0, import_element206.useMemo)(() => {
      if (!isInRevisionsMode) {
        previousBlocksRef.current = [];
        return null;
      }
      if (!revision) {
        return [];
      }
      const currentContent = revision?.content?.raw ?? "";
      let parsedBlocks;
      if (showDiff) {
        const previousContent = previousRevision?.content?.raw || "";
        parsedBlocks = diffRevisionContent(
          currentContent,
          previousContent
        );
      } else {
        parsedBlocks = (0, import_blocks14.parse)(currentContent);
      }
      if (postType2 === "wp_navigation") {
        parsedBlocks = [
          (0, import_blocks14.createBlock)(
            "core/navigation",
            { templateLock: false },
            parsedBlocks
          )
        ];
      }
      const blocksWithStableIds = preserveClientIds(
        parsedBlocks,
        previousBlocksRef.current
      );
      previousBlocksRef.current = blocksWithStableIds;
      return blocksWithStableIds;
    }, [
      isInRevisionsMode,
      revision,
      revision?.content?.raw,
      previousRevision?.content?.raw,
      postType2,
      showDiff
    ]);
    return blocks;
  }

  // packages/editor/build-module/components/commands/index.mjs
  var import_data71 = __toESM(require_data(), 1);
  var import_i18n193 = __toESM(require_i18n(), 1);
  var import_commands = __toESM(require_commands(), 1);
  var import_preferences7 = __toESM(require_preferences(), 1);
  var import_notices16 = __toESM(require_notices(), 1);
  var import_block_editor24 = __toESM(require_block_editor(), 1);
  var import_core_data48 = __toESM(require_core_data(), 1);
  var import_html_entities11 = __toESM(require_html_entities(), 1);

  // packages/editor/build-module/components/pattern-rename-modal/index.mjs
  var import_data69 = __toESM(require_data(), 1);
  var import_patterns6 = __toESM(require_patterns(), 1);
  var import_core_data46 = __toESM(require_core_data(), 1);
  var import_jsx_runtime360 = __toESM(require_jsx_runtime(), 1);
  var { RenamePatternModal } = unlock(import_patterns6.privateApis);
  var modalName = "editor/pattern-rename";
  function PatternRenameModal() {
    const isActive = (0, import_data69.useSelect)(
      (select9) => select9(store3).isModalActive(modalName)
    );
    const { record, postType: postType2 } = (0, import_data69.useSelect)(
      (select9) => {
        if (!isActive) {
          return {};
        }
        const { getCurrentPostType: getCurrentPostType2, getCurrentPostId: getCurrentPostId2 } = select9(store);
        const { getEditedEntityRecord } = select9(import_core_data46.store);
        const _postType = getCurrentPostType2();
        return {
          record: getEditedEntityRecord(
            "postType",
            _postType,
            getCurrentPostId2()
          ),
          postType: _postType
        };
      },
      [isActive]
    );
    const { closeModal: closeModal2 } = (0, import_data69.useDispatch)(store3);
    if (!isActive || postType2 !== PATTERN_POST_TYPE) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime360.jsx)(RenamePatternModal, { onClose: closeModal2, pattern: record });
  }

  // packages/editor/build-module/components/pattern-duplicate-modal/index.mjs
  var import_data70 = __toESM(require_data(), 1);
  var import_patterns7 = __toESM(require_patterns(), 1);
  var import_core_data47 = __toESM(require_core_data(), 1);
  var import_jsx_runtime361 = __toESM(require_jsx_runtime(), 1);
  var { DuplicatePatternModal } = unlock(import_patterns7.privateApis);
  var modalName2 = "editor/pattern-duplicate";
  function PatternDuplicateModal() {
    const isActive = (0, import_data70.useSelect)(
      (select9) => select9(store3).isModalActive(modalName2)
    );
    const { record, postType: postType2 } = (0, import_data70.useSelect)(
      (select9) => {
        if (!isActive) {
          return {};
        }
        const { getCurrentPostType: getCurrentPostType2, getCurrentPostId: getCurrentPostId2 } = select9(store);
        const { getEditedEntityRecord } = select9(import_core_data47.store);
        const _postType = getCurrentPostType2();
        return {
          record: getEditedEntityRecord(
            "postType",
            _postType,
            getCurrentPostId2()
          ),
          postType: _postType
        };
      },
      [isActive]
    );
    const { closeModal: closeModal2 } = (0, import_data70.useDispatch)(store3);
    if (!isActive || postType2 !== PATTERN_POST_TYPE) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime361.jsx)(
      DuplicatePatternModal,
      {
        onClose: closeModal2,
        onSuccess: () => closeModal2(),
        pattern: record
      }
    );
  }

  // packages/editor/build-module/components/commands/index.mjs
  function getTogglePatternEditingCommand({
    disableContentOnlyForPatternsAndTemplateParts,
    stopEditingContentOnlySection,
    updateEditorSettings: updateEditorSettings2
  }) {
    return {
      name: "core/toggle-pattern-editing",
      label: disableContentOnlyForPatternsAndTemplateParts ? (0, import_i18n193.__)("Disable editing all patterns") : (0, import_i18n193.__)("Enable editing all patterns"),
      icon: symbol_default,
      category: "command",
      callback: ({ close }) => {
        const disableContentOnly = !disableContentOnlyForPatternsAndTemplateParts;
        stopEditingContentOnlySection();
        updateEditorSettings2({
          disableContentOnlyForUnsyncedPatterns: disableContentOnly,
          disableContentOnlyForTemplateParts: disableContentOnly
        });
        close();
      }
    };
  }
  function isPatternOrTemplatePartBlock(blockName, attributes) {
    return !!attributes?.metadata?.patternName || blockName === "core/template-part";
  }
  var getEditorCommandLoader = () => function useEditorCommandLoader() {
    const {
      editorMode,
      isListViewOpen,
      showBlockBreadcrumbs,
      isDistractionFree,
      isFocusMode,
      isPreviewMode,
      isViewable,
      isCodeEditingEnabled,
      isRichEditingEnabled,
      isPublishSidebarEnabled: isPublishSidebarEnabled2,
      disableContentOnlyForUnsyncedPatterns,
      disableContentOnlyForTemplateParts
    } = (0, import_data71.useSelect)((select9) => {
      const { get } = select9(import_preferences7.store);
      const { isListViewOpened: isListViewOpened2, getCurrentPostType: getCurrentPostType2, getEditorSettings: getEditorSettings2 } = select9(store);
      const { getSettings: getSettings10 } = select9(import_block_editor24.store);
      const { getPostType } = select9(import_core_data48.store);
      return {
        editorMode: get("core", "editorMode") ?? "visual",
        isListViewOpen: isListViewOpened2(),
        showBlockBreadcrumbs: get("core", "showBlockBreadcrumbs"),
        isDistractionFree: get("core", "distractionFree"),
        isFocusMode: get("core", "focusMode"),
        isPreviewMode: getSettings10().isPreviewMode,
        isViewable: getPostType(getCurrentPostType2())?.viewable ?? false,
        isCodeEditingEnabled: getEditorSettings2().codeEditingEnabled,
        isRichEditingEnabled: getEditorSettings2().richEditingEnabled,
        isPublishSidebarEnabled: select9(store).isPublishSidebarEnabled(),
        disableContentOnlyForUnsyncedPatterns: !!getEditorSettings2().disableContentOnlyForUnsyncedPatterns,
        disableContentOnlyForTemplateParts: !!getEditorSettings2().disableContentOnlyForTemplateParts
      };
    }, []);
    const { getActiveComplementaryArea: getActiveComplementaryArea2 } = (0, import_data71.useSelect)(store3);
    const { toggle } = (0, import_data71.useDispatch)(import_preferences7.store);
    const { createInfoNotice } = (0, import_data71.useDispatch)(import_notices16.store);
    const {
      __unstableSaveForPreview: __unstableSaveForPreview2,
      setIsListViewOpened: setIsListViewOpened2,
      switchEditorMode: switchEditorMode2,
      toggleDistractionFree: toggleDistractionFree2,
      toggleSpotlightMode: toggleSpotlightMode2,
      toggleTopToolbar: toggleTopToolbar2,
      updateEditorSettings: updateEditorSettings2
    } = (0, import_data71.useDispatch)(store);
    const { stopEditingContentOnlySection } = unlock(
      (0, import_data71.useDispatch)(import_block_editor24.store)
    );
    const { openModal: openModal2, enableComplementaryArea: enableComplementaryArea2, disableComplementaryArea: disableComplementaryArea2 } = (0, import_data71.useDispatch)(store3);
    const { getCurrentPostId: getCurrentPostId2 } = (0, import_data71.useSelect)(store);
    const allowSwitchEditorMode = isCodeEditingEnabled && isRichEditingEnabled;
    if (isPreviewMode) {
      return { commands: [], isLoading: false };
    }
    const commands = [];
    const disableContentOnlyForPatternsAndTemplateParts = disableContentOnlyForUnsyncedPatterns && disableContentOnlyForTemplateParts;
    commands.push({
      name: "core/open-shortcut-help",
      label: (0, import_i18n193.__)("Keyboard shortcuts"),
      icon: keyboard_default,
      category: "view",
      callback: ({ close }) => {
        close();
        openModal2("editor/keyboard-shortcut-help");
      }
    });
    commands.push({
      name: "core/toggle-distraction-free",
      label: isDistractionFree ? (0, import_i18n193.__)("Exit Distraction free") : (0, import_i18n193.__)("Enter Distraction free"),
      category: "command",
      callback: ({ close }) => {
        toggleDistractionFree2();
        close();
      }
    });
    commands.push({
      name: "core/open-preferences",
      label: (0, import_i18n193.__)("Editor preferences"),
      category: "view",
      callback: ({ close }) => {
        close();
        openModal2("editor/preferences");
      }
    });
    commands.push({
      name: "core/toggle-spotlight-mode",
      label: isFocusMode ? (0, import_i18n193.__)("Exit Spotlight mode") : (0, import_i18n193.__)("Enter Spotlight mode"),
      category: "command",
      callback: ({ close }) => {
        toggleSpotlightMode2();
        close();
      }
    });
    commands.push({
      name: "core/toggle-list-view",
      label: isListViewOpen ? (0, import_i18n193.__)("Close List View") : (0, import_i18n193.__)("Open List View"),
      icon: list_view_default,
      category: "command",
      callback: ({ close }) => {
        setIsListViewOpened2(!isListViewOpen);
        close();
        createInfoNotice(
          isListViewOpen ? (0, import_i18n193.__)("List View off.") : (0, import_i18n193.__)("List View on."),
          {
            id: "core/editor/toggle-list-view/notice",
            type: "snackbar"
          }
        );
      }
    });
    commands.push({
      name: "core/toggle-top-toolbar",
      label: (0, import_i18n193.__)("Top toolbar"),
      category: "command",
      callback: ({ close }) => {
        toggleTopToolbar2();
        close();
      }
    });
    commands.push(
      getTogglePatternEditingCommand({
        disableContentOnlyForPatternsAndTemplateParts,
        stopEditingContentOnlySection,
        updateEditorSettings: updateEditorSettings2
      })
    );
    if (allowSwitchEditorMode) {
      commands.push({
        name: "core/toggle-code-editor",
        label: editorMode === "visual" ? (0, import_i18n193.__)("Open code editor") : (0, import_i18n193.__)("Exit code editor"),
        icon: code_default,
        category: "command",
        callback: ({ close }) => {
          switchEditorMode2(
            editorMode === "visual" ? "text" : "visual"
          );
          close();
        }
      });
    }
    commands.push({
      name: "core/toggle-breadcrumbs",
      label: showBlockBreadcrumbs ? (0, import_i18n193.__)("Hide block breadcrumbs") : (0, import_i18n193.__)("Show block breadcrumbs"),
      category: "command",
      callback: ({ close }) => {
        toggle("core", "showBlockBreadcrumbs");
        close();
        createInfoNotice(
          showBlockBreadcrumbs ? (0, import_i18n193.__)("Breadcrumbs hidden.") : (0, import_i18n193.__)("Breadcrumbs visible."),
          {
            id: "core/editor/toggle-breadcrumbs/notice",
            type: "snackbar"
          }
        );
      }
    });
    commands.push({
      name: "core/open-settings-sidebar",
      label: (0, import_i18n193.__)("Show or hide the Settings panel"),
      icon: (0, import_i18n193.isRTL)() ? drawer_left_default : drawer_right_default,
      category: "command",
      callback: ({ close }) => {
        const activeSidebar = getActiveComplementaryArea2("core");
        close();
        if (activeSidebar === "edit-post/document") {
          disableComplementaryArea2("core");
        } else {
          enableComplementaryArea2("core", "edit-post/document");
        }
      }
    });
    commands.push({
      name: "core/open-block-inspector",
      label: (0, import_i18n193.__)("Show or hide the Block settings panel"),
      icon: block_default_default,
      category: "command",
      callback: ({ close }) => {
        const activeSidebar = getActiveComplementaryArea2("core");
        close();
        if (activeSidebar === "edit-post/block") {
          disableComplementaryArea2("core");
        } else {
          enableComplementaryArea2("core", "edit-post/block");
        }
      }
    });
    commands.push({
      name: "core/toggle-publish-sidebar",
      label: isPublishSidebarEnabled2 ? (0, import_i18n193.__)("Disable pre-publish checks") : (0, import_i18n193.__)("Enable pre-publish checks"),
      icon: format_list_bullets_default,
      category: "command",
      callback: ({ close }) => {
        close();
        toggle("core", "isPublishSidebarEnabled");
        createInfoNotice(
          isPublishSidebarEnabled2 ? (0, import_i18n193.__)("Pre-publish checks disabled.") : (0, import_i18n193.__)("Pre-publish checks enabled."),
          {
            id: "core/editor/publish-sidebar/notice",
            type: "snackbar"
          }
        );
      }
    });
    if (isViewable) {
      commands.push({
        name: "core/preview-link",
        label: (0, import_i18n193.__)("Preview in a new tab"),
        icon: external_default,
        category: "view",
        callback: async ({ close }) => {
          close();
          const postId2 = getCurrentPostId2();
          const link = await __unstableSaveForPreview2();
          window.open(link, `wp-preview-${postId2}`);
        }
      });
    }
    return {
      commands,
      isLoading: false
    };
  };
  var getPatternEditingContextualCommands = () => function usePatternEditingContextualCommands({ search }) {
    const {
      disableContentOnlyForPatternsAndTemplateParts,
      hasPatternOrTemplatePartSelection,
      isPreviewMode
    } = (0, import_data71.useSelect)((select9) => {
      const {
        getBlockAttributes: getBlockAttributes2,
        getBlockName: getBlockName2,
        getBlockParents,
        getSelectedBlockClientId: getSelectedBlockClientId2,
        getSelectedBlockClientIds,
        getSettings: getSettings10
      } = select9(import_block_editor24.store);
      const { getEditorSettings: getEditorSettings2 } = select9(store);
      const editorSettings2 = getEditorSettings2();
      const selectedBlockClientId = getSelectedBlockClientId2();
      const selectedBlockClientIds = getSelectedBlockClientIds();
      const clientIdsToCheck = selectedBlockClientId && selectedBlockClientIds.length === 1 ? [
        selectedBlockClientId,
        ...getBlockParents(selectedBlockClientId, true)
      ] : [];
      return {
        disableContentOnlyForPatternsAndTemplateParts: !!editorSettings2.disableContentOnlyForUnsyncedPatterns && !!editorSettings2.disableContentOnlyForTemplateParts,
        hasPatternOrTemplatePartSelection: clientIdsToCheck.some(
          (clientId) => isPatternOrTemplatePartBlock(
            getBlockName2(clientId),
            getBlockAttributes2(clientId)
          )
        ),
        isPreviewMode: getSettings10().isPreviewMode
      };
    }, []);
    const { updateEditorSettings: updateEditorSettings2 } = (0, import_data71.useDispatch)(store);
    const { stopEditingContentOnlySection } = unlock(
      (0, import_data71.useDispatch)(import_block_editor24.store)
    );
    if (search || !hasPatternOrTemplatePartSelection && !disableContentOnlyForPatternsAndTemplateParts || isPreviewMode) {
      return { isLoading: false, commands: [] };
    }
    return {
      isLoading: false,
      commands: [
        getTogglePatternEditingCommand({
          disableContentOnlyForPatternsAndTemplateParts,
          stopEditingContentOnlySection,
          updateEditorSettings: updateEditorSettings2
        })
      ]
    };
  };
  var getEditedEntityContextualCommands = () => function useEditedEntityContextualCommands() {
    const { postType: postType2 } = (0, import_data71.useSelect)((select9) => {
      const { getCurrentPostType: getCurrentPostType2 } = select9(store);
      return {
        postType: getCurrentPostType2()
      };
    }, []);
    const { openModal: openModal2 } = (0, import_data71.useDispatch)(store3);
    const commands = [];
    if (postType2 === PATTERN_POST_TYPE) {
      commands.push({
        name: "core/rename-pattern",
        label: (0, import_i18n193.__)("Rename pattern"),
        icon: pencil_default,
        category: "edit",
        callback: ({ close }) => {
          openModal2(modalName);
          close();
        }
      });
      commands.push({
        name: "core/duplicate-pattern",
        label: (0, import_i18n193.__)("Duplicate pattern"),
        icon: symbol_default,
        category: "command",
        callback: ({ close }) => {
          openModal2(modalName2);
          close();
        }
      });
    }
    return { isLoading: false, commands };
  };
  var getPageContentFocusCommands = () => function usePageContentFocusCommands() {
    const {
      onNavigateToEntityRecord,
      goBack,
      templateId: templateId2,
      isPreviewMode,
      canEditTemplate
    } = (0, import_data71.useSelect)((select9) => {
      const {
        getRenderingMode: getRenderingMode2,
        getEditorSettings: _getEditorSettings,
        getCurrentTemplateId: getCurrentTemplateId2
      } = unlock(select9(store));
      const editorSettings2 = _getEditorSettings();
      const _templateId = getCurrentTemplateId2();
      return {
        isTemplateHidden: getRenderingMode2() === "post-only",
        onNavigateToEntityRecord: editorSettings2.onNavigateToEntityRecord,
        getEditorSettings: _getEditorSettings,
        goBack: editorSettings2.onNavigateToPreviousEntityRecord,
        templateId: _templateId,
        isPreviewMode: editorSettings2.isPreviewMode,
        canEditTemplate: !!_templateId && select9(import_core_data48.store).canUser("update", {
          kind: "postType",
          name: "wp_template",
          id: _templateId
        })
      };
    }, []);
    const { editedRecord: template2, hasResolved } = (0, import_core_data48.useEntityRecord)(
      "postType",
      "wp_template",
      templateId2
    );
    if (isPreviewMode) {
      return { isLoading: false, commands: [] };
    }
    const commands = [];
    if (templateId2 && hasResolved && canEditTemplate) {
      commands.push({
        name: "core/switch-to-template-focus",
        label: (0, import_i18n193.sprintf)(
          /* translators: %s: template title */
          (0, import_i18n193.__)("Edit template: %s"),
          (0, import_html_entities11.decodeEntities)(template2.title)
        ),
        icon: layout_default,
        category: "edit",
        callback: ({ close }) => {
          onNavigateToEntityRecord({
            postId: templateId2,
            postType: "wp_template"
          });
          close();
        }
      });
    }
    if (!!goBack) {
      commands.push({
        name: "core/switch-to-previous-entity",
        label: (0, import_i18n193.__)("Go back"),
        icon: page_default,
        category: "view",
        callback: ({ close }) => {
          goBack();
          close();
        }
      });
    }
    return { isLoading: false, commands };
  };
  var getManipulateDocumentCommands = () => function useManipulateDocumentCommands() {
    const { postType: postType2, postId: postId2 } = (0, import_data71.useSelect)((select9) => {
      const { getCurrentPostId: getCurrentPostId2, getCurrentPostType: getCurrentPostType2 } = select9(store);
      return {
        postType: getCurrentPostType2(),
        postId: getCurrentPostId2()
      };
    }, []);
    const { editedRecord: template2, hasResolved } = (0, import_core_data48.useEntityRecord)(
      "postType",
      postType2,
      postId2
    );
    const { revertTemplate: revertTemplate3 } = unlock((0, import_data71.useDispatch)(store));
    if (!hasResolved || ![TEMPLATE_PART_POST_TYPE, TEMPLATE_POST_TYPE].includes(
      postType2
    )) {
      return { isLoading: true, commands: [] };
    }
    const commands = [];
    if (isTemplateRevertable(template2)) {
      const label = template2.type === TEMPLATE_POST_TYPE ? (0, import_i18n193.sprintf)(
        /* translators: %s: template title */
        (0, import_i18n193.__)("Reset template: %s"),
        (0, import_html_entities11.decodeEntities)(template2.title)
      ) : (0, import_i18n193.sprintf)(
        /* translators: %s: template part title */
        (0, import_i18n193.__)("Reset template part: %s"),
        (0, import_html_entities11.decodeEntities)(template2.title)
      );
      commands.push({
        name: "core/reset-template",
        label,
        icon: (0, import_i18n193.isRTL)() ? rotate_right_default : rotate_left_default,
        category: "command",
        callback: ({ close }) => {
          revertTemplate3(template2);
          close();
        }
      });
    }
    return {
      isLoading: !hasResolved,
      commands
    };
  };
  function useCommands() {
    (0, import_commands.useCommandLoader)({
      name: "core/editor/edit-ui",
      hook: getEditorCommandLoader()
    });
    (0, import_commands.useCommandLoader)({
      name: "core/editor/contextual-commands",
      hook: getEditedEntityContextualCommands(),
      context: "entity-edit"
    });
    (0, import_commands.useCommandLoader)({
      name: "core/editor/pattern-editing-contextual-commands",
      hook: getPatternEditingContextualCommands(),
      context: "block-selection-edit"
    });
    (0, import_commands.useCommandLoader)({
      name: "core/editor/page-content-focus",
      hook: getPageContentFocusCommands(),
      context: "entity-edit"
    });
    (0, import_commands.useCommandLoader)({
      name: "core/edit-site/manipulate-document",
      hook: getManipulateDocumentCommands()
    });
  }

  // packages/editor/build-module/components/provider/use-upload-save-lock.mjs
  var import_data72 = __toESM(require_data(), 1);
  var import_element207 = __toESM(require_element(), 1);
  var import_upload_media = __toESM(require_upload_media(), 1);
  var LOCK_NAME = "upload-in-progress";
  function useUploadSaveLock() {
    const isUploading = (0, import_data72.useSelect)(
      (select9) => select9(import_upload_media.store).isUploading(),
      []
    );
    const {
      lockPostSaving: lockPostSaving2,
      unlockPostSaving: unlockPostSaving2,
      lockPostAutosaving: lockPostAutosaving2,
      unlockPostAutosaving: unlockPostAutosaving2
    } = (0, import_data72.useDispatch)(store);
    (0, import_element207.useEffect)(() => {
      if (isUploading) {
        lockPostSaving2(LOCK_NAME);
        lockPostAutosaving2(LOCK_NAME);
      } else {
        unlockPostSaving2(LOCK_NAME);
        unlockPostAutosaving2(LOCK_NAME);
      }
      return () => {
        unlockPostSaving2(LOCK_NAME);
        unlockPostAutosaving2(LOCK_NAME);
      };
    }, [
      isUploading,
      lockPostSaving2,
      unlockPostSaving2,
      lockPostAutosaving2,
      unlockPostAutosaving2
    ]);
  }

  // packages/editor/build-module/components/provider/use-network-reconnect.mjs
  var import_element208 = __toESM(require_element(), 1);
  var import_data73 = __toESM(require_data(), 1);
  var import_upload_media2 = __toESM(require_upload_media(), 1);
  function useNetworkReconnect() {
    const isEnabled = window.__clientSideMediaProcessing;
    const registry = (0, import_data73.useRegistry)();
    (0, import_element208.useEffect)(() => {
      if (!isEnabled) {
        return;
      }
      const handleOffline = () => {
        unlock(registry.dispatch(import_upload_media2.store)).pauseQueue();
      };
      const handleOnline = () => {
        unlock(registry.dispatch(import_upload_media2.store)).resumeQueue();
      };
      window.addEventListener("offline", handleOffline);
      window.addEventListener("online", handleOnline);
      return () => {
        window.removeEventListener("offline", handleOffline);
        window.removeEventListener("online", handleOnline);
      };
    }, [isEnabled, registry]);
  }

  // packages/editor/build-module/components/block-removal-warnings/index.mjs
  var import_i18n194 = __toESM(require_i18n(), 1);
  var import_block_editor25 = __toESM(require_block_editor(), 1);
  var import_data74 = __toESM(require_data(), 1);
  var import_element209 = __toESM(require_element(), 1);
  var import_jsx_runtime362 = __toESM(require_jsx_runtime(), 1);
  var { BlockRemovalWarningModal } = unlock(import_block_editor25.privateApis);
  var TEMPLATE_BLOCKS = [
    "core/post-content",
    "core/post-template",
    "core/query"
  ];
  var BLOCK_REMOVAL_RULES = [
    {
      // Template blocks.
      // The warning is only shown when a user manipulates templates or template parts.
      postTypes: ["wp_template", "wp_template_part"],
      callback(removedBlocks) {
        const removedPostContentBlocks = removedBlocks.filter(
          ({ name: name2 }) => name2 === "core/post-content"
        );
        if (removedPostContentBlocks.length) {
          return {
            description: (0, import_i18n194.__)(
              "This block displays the content of posts and pages using this template."
            ),
            warning: (0, import_i18n194.__)(
              "If you delete it, posts or pages using this template will not display any content."
            ),
            subtext: (0, import_i18n194.__)("Visitors will see blank pages."),
            requireConfirmation: true
          };
        }
        const removedTemplateBlocks = removedBlocks.filter(
          ({ name: name2 }) => TEMPLATE_BLOCKS.includes(name2)
        );
        if (removedTemplateBlocks.length) {
          return (0, import_i18n194._n)(
            "Deleting this block will stop your post or page content from displaying on this template. It is not recommended.",
            "Some of the deleted blocks will stop your post or page content from displaying on this template. It is not recommended.",
            removedBlocks.length
          );
        }
      }
    },
    {
      // Pattern overrides.
      // The warning is only shown when the user edits a pattern.
      postTypes: ["wp_block"],
      callback(removedBlocks) {
        const removedBlocksWithOverrides = removedBlocks.filter(
          ({ attributes }) => attributes?.metadata?.bindings && Object.values(attributes.metadata.bindings).some(
            (binding) => binding.source === "core/pattern-overrides"
          )
        );
        if (removedBlocksWithOverrides.length) {
          return (0, import_i18n194._n)(
            "The deleted block allows instance overrides. Removing it may result in content not displaying where this pattern is used. Are you sure you want to proceed?",
            "Some of the deleted blocks allow instance overrides. Removing them may result in content not displaying where this pattern is used. Are you sure you want to proceed?",
            removedBlocks.length
          );
        }
      }
    }
  ];
  function BlockRemovalWarnings() {
    const currentPostType = (0, import_data74.useSelect)(
      (select9) => select9(store).getCurrentPostType(),
      []
    );
    const removalRulesForPostType = (0, import_element209.useMemo)(
      () => BLOCK_REMOVAL_RULES.filter(
        (rule) => rule.postTypes.includes(currentPostType)
      ),
      [currentPostType]
    );
    if (!removalRulesForPostType) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime362.jsx)(BlockRemovalWarningModal, { rules: removalRulesForPostType });
  }

  // packages/editor/build-module/components/start-page-options/index.mjs
  var import_components151 = __toESM(require_components(), 1);
  var import_i18n195 = __toESM(require_i18n(), 1);
  var import_element210 = __toESM(require_element(), 1);
  var import_block_editor26 = __toESM(require_block_editor(), 1);
  var import_data75 = __toESM(require_data(), 1);
  var import_core_data49 = __toESM(require_core_data(), 1);
  var import_blocks15 = __toESM(require_blocks(), 1);
  var import_preferences8 = __toESM(require_preferences(), 1);
  var import_jsx_runtime363 = __toESM(require_jsx_runtime(), 1);
  function useStartPatterns() {
    const { blockPatternsWithPostContentBlockType, postType: postType2 } = (0, import_data75.useSelect)(
      (select9) => {
        const { getPatternsByBlockTypes, getBlocksByName } = select9(import_block_editor26.store);
        const { getCurrentPostType: getCurrentPostType2, getRenderingMode: getRenderingMode2 } = select9(store);
        const rootClientId = getRenderingMode2() === "post-only" ? "" : getBlocksByName("core/post-content")?.[0];
        return {
          blockPatternsWithPostContentBlockType: getPatternsByBlockTypes(
            "core/post-content",
            rootClientId
          ),
          postType: getCurrentPostType2()
        };
      },
      []
    );
    return (0, import_element210.useMemo)(() => {
      if (!blockPatternsWithPostContentBlockType?.length) {
        return [];
      }
      return blockPatternsWithPostContentBlockType.filter((pattern) => {
        return postType2 === "page" && !pattern.postTypes || Array.isArray(pattern.postTypes) && pattern.postTypes.includes(postType2);
      });
    }, [postType2, blockPatternsWithPostContentBlockType]);
  }
  function PatternSelection({ blockPatterns, onChoosePattern }) {
    const { editEntityRecord } = (0, import_data75.useDispatch)(import_core_data49.store);
    const { postType: postType2, postId: postId2 } = (0, import_data75.useSelect)((select9) => {
      const { getCurrentPostType: getCurrentPostType2, getCurrentPostId: getCurrentPostId2 } = select9(store);
      return {
        postType: getCurrentPostType2(),
        postId: getCurrentPostId2()
      };
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
      import_block_editor26.__experimentalBlockPatternsList,
      {
        blockPatterns,
        onClickPattern: (_pattern, blocks) => {
          editEntityRecord("postType", postType2, postId2, {
            blocks,
            content: ({ blocks: blocksForSerialization = [] }) => (0, import_blocks15.__unstableSerializeAndClean)(blocksForSerialization)
          });
          onChoosePattern();
        }
      }
    );
  }
  function StartPageOptionsModal({ onClose }) {
    const [showStartPatterns, setShowStartPatterns] = (0, import_element210.useState)(true);
    const { set: setPreference } = (0, import_data75.useDispatch)(import_preferences8.store);
    const startPatterns = useStartPatterns();
    const hasStartPattern = startPatterns.length > 0;
    if (!hasStartPattern) {
      return null;
    }
    function handleClose() {
      onClose();
      setPreference("core", "enableChoosePatternModal", showStartPatterns);
    }
    return /* @__PURE__ */ (0, import_jsx_runtime363.jsxs)(
      import_components151.Modal,
      {
        className: "editor-start-page-options__modal",
        title: (0, import_i18n195.__)("Choose a pattern"),
        isFullScreen: true,
        onRequestClose: handleClose,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime363.jsx)("div", { className: "editor-start-page-options__modal-content", children: /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
            PatternSelection,
            {
              blockPatterns: startPatterns,
              onChoosePattern: handleClose
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
            import_components151.Flex,
            {
              className: "editor-start-page-options__modal__actions",
              justify: "flex-start",
              expanded: false,
              children: /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(import_components151.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(
                import_components151.CheckboxControl,
                {
                  checked: showStartPatterns,
                  label: (0, import_i18n195.__)(
                    "Always show starter patterns for new pages"
                  ),
                  onChange: (newValue) => {
                    setShowStartPatterns(newValue);
                  }
                }
              ) })
            }
          )
        ]
      }
    );
  }
  function StartPageOptions() {
    const [isOpen2, setIsOpen] = (0, import_element210.useState)(false);
    const { isEditedPostEmpty: isEditedPostEmpty2 } = (0, import_data75.useSelect)(store);
    const { getEntityRecordNonTransientEdits } = (0, import_data75.useSelect)(import_core_data49.store);
    const { isModalActive: isModalActive2 } = (0, import_data75.useSelect)(store3);
    const { enabled, postType: postType2, postId: postId2 } = (0, import_data75.useSelect)((select9) => {
      const { getCurrentPostId: getCurrentPostId2, getCurrentPostType: getCurrentPostType2 } = select9(store);
      const choosePatternModalEnabled = select9(import_preferences8.store).get(
        "core",
        "enableChoosePatternModal"
      );
      const currentPostType = getCurrentPostType2();
      return {
        postType: currentPostType,
        postId: getCurrentPostId2(),
        enabled: choosePatternModalEnabled && ATTACHMENT_POST_TYPE !== currentPostType && TEMPLATE_POST_TYPE !== currentPostType && TEMPLATE_PART_POST_TYPE !== currentPostType
      };
    }, []);
    (0, import_element210.useEffect)(() => {
      const hasEdits = Object.keys(
        getEntityRecordNonTransientEdits(
          "postType",
          postType2,
          postId2
        ) ?? {}
      ).length > 0;
      const isFreshPage = !hasEdits && isEditedPostEmpty2();
      const isPreferencesModalActive = isModalActive2("editor/preferences");
      if (!enabled || !isFreshPage || isPreferencesModalActive) {
        return;
      }
      setIsOpen(true);
    }, [
      enabled,
      postType2,
      postId2,
      getEntityRecordNonTransientEdits,
      isEditedPostEmpty2,
      isModalActive2
    ]);
    if (!isOpen2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime363.jsx)(StartPageOptionsModal, { onClose: () => setIsOpen(false) });
  }

  // packages/editor/build-module/components/keyboard-shortcut-help-modal/index.mjs
  var import_components152 = __toESM(require_components(), 1);
  var import_i18n197 = __toESM(require_i18n(), 1);
  var import_keyboard_shortcuts3 = __toESM(require_keyboard_shortcuts(), 1);
  var import_data77 = __toESM(require_data(), 1);

  // packages/editor/build-module/components/keyboard-shortcut-help-modal/config.mjs
  var import_i18n196 = __toESM(require_i18n(), 1);
  var textFormattingShortcuts = [
    {
      keyCombination: { modifier: "primary", character: "b" },
      description: (0, import_i18n196.__)("Make the selected text bold.")
    },
    {
      keyCombination: { modifier: "primary", character: "i" },
      description: (0, import_i18n196.__)("Make the selected text italic.")
    },
    {
      keyCombination: { modifier: "primary", character: "k" },
      description: (0, import_i18n196.__)("Convert the selected text into a link.")
    },
    {
      keyCombination: { modifier: "primaryShift", character: "k" },
      description: (0, import_i18n196.__)("Remove a link.")
    },
    {
      keyCombination: { character: "[[" },
      description: (0, import_i18n196.__)("Insert a link to a post or page.")
    },
    {
      keyCombination: { modifier: "primary", character: "u" },
      description: (0, import_i18n196.__)("Underline the selected text.")
    },
    {
      keyCombination: { modifier: "access", character: "d" },
      description: (0, import_i18n196.__)("Strikethrough the selected text.")
    },
    {
      keyCombination: { modifier: "access", character: "x" },
      description: (0, import_i18n196.__)("Make the selected text inline code.")
    },
    {
      keyCombination: {
        modifier: "access",
        character: "0"
      },
      aliases: [
        {
          modifier: "access",
          character: "7"
        }
      ],
      description: (0, import_i18n196.__)("Convert the current heading to a paragraph.")
    },
    {
      keyCombination: { modifier: "access", character: "1-6" },
      description: (0, import_i18n196.__)(
        "Convert the current paragraph or heading to a heading of level 1 to 6."
      )
    },
    {
      keyCombination: { modifier: "primaryShift", character: "SPACE" },
      description: (0, import_i18n196.__)("Add non breaking space.")
    }
  ];

  // packages/editor/build-module/components/keyboard-shortcut-help-modal/shortcut.mjs
  var import_element211 = __toESM(require_element(), 1);
  var import_keycodes7 = __toESM(require_keycodes(), 1);
  var import_jsx_runtime364 = __toESM(require_jsx_runtime(), 1);
  function KeyCombination({ keyCombination, forceAriaLabel }) {
    const shortcut = keyCombination.modifier ? import_keycodes7.displayShortcutList[keyCombination.modifier](
      keyCombination.character
    ) : keyCombination.character;
    const ariaLabel = keyCombination.modifier ? import_keycodes7.shortcutAriaLabel[keyCombination.modifier](
      keyCombination.character
    ) : keyCombination.character;
    return /* @__PURE__ */ (0, import_jsx_runtime364.jsx)(
      "kbd",
      {
        className: "editor-keyboard-shortcut-help-modal__shortcut-key-combination",
        "aria-label": forceAriaLabel || ariaLabel,
        children: (Array.isArray(shortcut) ? shortcut : [shortcut]).map(
          (character, index2) => {
            if (character === "+") {
              return /* @__PURE__ */ (0, import_jsx_runtime364.jsx)(import_element211.Fragment, { children: character }, index2);
            }
            return /* @__PURE__ */ (0, import_jsx_runtime364.jsx)(
              "kbd",
              {
                className: "editor-keyboard-shortcut-help-modal__shortcut-key",
                children: character
              },
              index2
            );
          }
        )
      }
    );
  }
  function Shortcut({ description, keyCombination, aliases = [], ariaLabel }) {
    return /* @__PURE__ */ (0, import_jsx_runtime364.jsxs)(import_jsx_runtime364.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime364.jsx)("div", { className: "editor-keyboard-shortcut-help-modal__shortcut-description", children: description }),
      /* @__PURE__ */ (0, import_jsx_runtime364.jsxs)("div", { className: "editor-keyboard-shortcut-help-modal__shortcut-term", children: [
        /* @__PURE__ */ (0, import_jsx_runtime364.jsx)(
          KeyCombination,
          {
            keyCombination,
            forceAriaLabel: ariaLabel
          }
        ),
        aliases.map((alias, index2) => /* @__PURE__ */ (0, import_jsx_runtime364.jsx)(
          KeyCombination,
          {
            keyCombination: alias,
            forceAriaLabel: ariaLabel
          },
          index2
        ))
      ] })
    ] });
  }
  var shortcut_default = Shortcut;

  // packages/editor/build-module/components/keyboard-shortcut-help-modal/dynamic-shortcut.mjs
  var import_data76 = __toESM(require_data(), 1);
  var import_keyboard_shortcuts2 = __toESM(require_keyboard_shortcuts(), 1);
  var import_jsx_runtime365 = __toESM(require_jsx_runtime(), 1);
  function DynamicShortcut({ name: name2 }) {
    const { keyCombination, description, aliases } = (0, import_data76.useSelect)(
      (select9) => {
        const {
          getShortcutKeyCombination,
          getShortcutDescription,
          getShortcutAliases
        } = select9(import_keyboard_shortcuts2.store);
        return {
          keyCombination: getShortcutKeyCombination(name2),
          aliases: getShortcutAliases(name2),
          description: getShortcutDescription(name2)
        };
      },
      [name2]
    );
    if (!keyCombination) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime365.jsx)(
      shortcut_default,
      {
        keyCombination,
        description,
        aliases
      }
    );
  }
  var dynamic_shortcut_default = DynamicShortcut;

  // packages/editor/build-module/components/keyboard-shortcut-help-modal/index.mjs
  var import_jsx_runtime366 = __toESM(require_jsx_runtime(), 1);
  var KEYBOARD_SHORTCUT_HELP_MODAL_NAME = "editor/keyboard-shortcut-help";
  var ShortcutList = ({ shortcuts }) => (
    /*
     * Disable reason: The `list` ARIA role is redundant but
     * Safari+VoiceOver won't announce the list otherwise.
     */
    /* eslint-disable jsx-a11y/no-redundant-roles */
    /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
      "ul",
      {
        className: "editor-keyboard-shortcut-help-modal__shortcut-list",
        role: "list",
        children: shortcuts.map((shortcut, index2) => /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
          "li",
          {
            className: "editor-keyboard-shortcut-help-modal__shortcut",
            children: typeof shortcut === "string" ? /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(dynamic_shortcut_default, { name: shortcut }) : /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(shortcut_default, { ...shortcut })
          },
          index2
        ))
      }
    )
  );
  var ShortcutSection = ({ title, shortcuts, className }) => /* @__PURE__ */ (0, import_jsx_runtime366.jsxs)(
    "section",
    {
      className: clsx_default(
        "editor-keyboard-shortcut-help-modal__section",
        className
      ),
      children: [
        !!title && /* @__PURE__ */ (0, import_jsx_runtime366.jsx)("h2", { className: "editor-keyboard-shortcut-help-modal__section-title", children: title }),
        /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(ShortcutList, { shortcuts })
      ]
    }
  );
  var ShortcutCategorySection = ({
    title,
    categoryName,
    additionalShortcuts = []
  }) => {
    const categoryShortcuts = (0, import_data77.useSelect)(
      (select9) => {
        return select9(import_keyboard_shortcuts3.store).getCategoryShortcuts(
          categoryName
        );
      },
      [categoryName]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
      ShortcutSection,
      {
        title,
        shortcuts: categoryShortcuts.concat(additionalShortcuts)
      }
    );
  };
  function KeyboardShortcutHelpModal() {
    const isModalActive2 = (0, import_data77.useSelect)(
      (select9) => select9(store3).isModalActive(
        KEYBOARD_SHORTCUT_HELP_MODAL_NAME
      ),
      []
    );
    const { openModal: openModal2, closeModal: closeModal2 } = (0, import_data77.useDispatch)(store3);
    const toggleModal = () => {
      if (isModalActive2) {
        closeModal2();
      } else {
        openModal2(KEYBOARD_SHORTCUT_HELP_MODAL_NAME);
      }
    };
    (0, import_keyboard_shortcuts3.useShortcut)("core/editor/keyboard-shortcuts", toggleModal);
    if (!isModalActive2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime366.jsxs)(
      import_components152.Modal,
      {
        className: "editor-keyboard-shortcut-help-modal",
        title: (0, import_i18n197.__)("Keyboard shortcuts"),
        closeButtonLabel: (0, import_i18n197.__)("Close"),
        onRequestClose: toggleModal,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
            ShortcutSection,
            {
              className: "editor-keyboard-shortcut-help-modal__main-shortcuts",
              shortcuts: ["core/editor/keyboard-shortcuts"]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
            ShortcutCategorySection,
            {
              title: (0, import_i18n197.__)("Global shortcuts"),
              categoryName: "global"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
            ShortcutCategorySection,
            {
              title: (0, import_i18n197.__)("Selection shortcuts"),
              categoryName: "selection"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
            ShortcutCategorySection,
            {
              title: (0, import_i18n197.__)("Block shortcuts"),
              categoryName: "block",
              additionalShortcuts: [
                {
                  keyCombination: { character: "/" },
                  description: (0, import_i18n197.__)(
                    "Change the block type after adding a new paragraph."
                  ),
                  /* translators: The forward-slash character. e.g. '/'. */
                  ariaLabel: (0, import_i18n197.__)("Forward-slash")
                }
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
            ShortcutSection,
            {
              title: (0, import_i18n197.__)("Text formatting"),
              shortcuts: textFormattingShortcuts
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime366.jsx)(
            ShortcutCategorySection,
            {
              title: (0, import_i18n197.__)("List View shortcuts"),
              categoryName: "list-view"
            }
          )
        ]
      }
    );
  }
  var keyboard_shortcut_help_modal_default = KeyboardShortcutHelpModal;

  // packages/editor/build-module/components/start-template-options/index.mjs
  var import_components153 = __toESM(require_components(), 1);
  var import_i18n198 = __toESM(require_i18n(), 1);
  var import_element212 = __toESM(require_element(), 1);
  var import_block_editor27 = __toESM(require_block_editor(), 1);
  var import_data78 = __toESM(require_data(), 1);
  var import_blocks16 = __toESM(require_blocks(), 1);
  var import_core_data50 = __toESM(require_core_data(), 1);
  var import_jsx_runtime367 = __toESM(require_jsx_runtime(), 1);
  function useFallbackTemplateContent(slug, isCustom = false) {
    return (0, import_data78.useSelect)(
      (select9) => {
        const { getEntityRecord, getDefaultTemplateId } = select9(import_core_data50.store);
        const templateId2 = getDefaultTemplateId({
          slug,
          is_custom: isCustom,
          ignore_empty: true
        });
        return templateId2 ? getEntityRecord("postType", TEMPLATE_POST_TYPE, templateId2)?.content?.raw : void 0;
      },
      [slug, isCustom]
    );
  }
  function useStartPatterns2(fallbackContent) {
    const { slug, patterns: patterns2 } = (0, import_data78.useSelect)((select9) => {
      const { getCurrentPostType: getCurrentPostType2, getCurrentPostId: getCurrentPostId2 } = select9(store);
      const { getEntityRecord, getBlockPatterns } = select9(import_core_data50.store);
      const postId2 = getCurrentPostId2();
      const postType2 = getCurrentPostType2();
      const record = getEntityRecord("postType", postType2, postId2);
      return {
        slug: record.slug,
        patterns: getBlockPatterns()
      };
    }, []);
    const currentThemeStylesheet = (0, import_data78.useSelect)(
      (select9) => select9(import_core_data50.store).getCurrentTheme().stylesheet
    );
    function injectThemeAttributeInBlockTemplateContent2(block) {
      if (block.innerBlocks.find(
        (innerBlock) => innerBlock.name === "core/template-part"
      )) {
        block.innerBlocks = block.innerBlocks.map((innerBlock) => {
          if (innerBlock.name === "core/template-part" && innerBlock.attributes.theme === void 0) {
            innerBlock.attributes.theme = currentThemeStylesheet;
          }
          return innerBlock;
        });
      }
      if (block.name === "core/template-part" && block.attributes.theme === void 0) {
        block.attributes.theme = currentThemeStylesheet;
      }
      return block;
    }
    return (0, import_element212.useMemo)(() => {
      return [
        {
          name: "fallback",
          blocks: (0, import_blocks16.parse)(fallbackContent),
          title: (0, import_i18n198.__)("Fallback content")
        },
        ...patterns2.filter((pattern) => {
          return Array.isArray(pattern.templateTypes) && pattern.templateTypes.some(
            (templateType) => slug.startsWith(templateType)
          );
        }).map((pattern) => {
          return {
            ...pattern,
            blocks: (0, import_blocks16.parse)(pattern.content).map(
              (block) => injectThemeAttributeInBlockTemplateContent2(block)
            )
          };
        })
      ];
    }, [fallbackContent, slug, patterns2]);
  }
  function PatternSelection2({ fallbackContent, onChoosePattern, postType: postType2 }) {
    const [, , onChange] = (0, import_core_data50.useEntityBlockEditor)("postType", postType2);
    const blockPatterns = useStartPatterns2(fallbackContent);
    return /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
      import_block_editor27.__experimentalBlockPatternsList,
      {
        blockPatterns,
        onClickPattern: (pattern, blocks) => {
          onChange(blocks, { selection: void 0 });
          onChoosePattern();
        }
      }
    );
  }
  function StartModal({ slug, isCustom, onClose, postType: postType2 }) {
    const fallbackContent = useFallbackTemplateContent(slug, isCustom);
    if (!fallbackContent) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime367.jsxs)(
      import_components153.Modal,
      {
        className: "editor-start-template-options__modal",
        title: (0, import_i18n198.__)("Choose a pattern"),
        closeLabel: (0, import_i18n198.__)("Cancel"),
        focusOnMount: "firstElement",
        onRequestClose: onClose,
        isFullScreen: true,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime367.jsx)("div", { className: "editor-start-template-options__modal-content", children: /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
            PatternSelection2,
            {
              fallbackContent,
              slug,
              isCustom,
              postType: postType2,
              onChoosePattern: () => {
                onClose();
              }
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
            import_components153.Flex,
            {
              className: "editor-start-template-options__modal__actions",
              justify: "flex-end",
              expanded: false,
              children: /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(import_components153.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
                import_components153.Button,
                {
                  __next40pxDefaultSize: true,
                  variant: "tertiary",
                  onClick: onClose,
                  children: (0, import_i18n198.__)("Skip")
                }
              ) })
            }
          )
        ]
      }
    );
  }
  function StartTemplateOptions() {
    const [isClosed, setIsClosed] = (0, import_element212.useState)(false);
    const { shouldOpenModal, slug, isCustom, postType: postType2, postId: postId2 } = (0, import_data78.useSelect)(
      (select9) => {
        const { getCurrentPostType: getCurrentPostType2, getCurrentPostId: getCurrentPostId2 } = select9(store);
        const _postType = getCurrentPostType2();
        const _postId = getCurrentPostId2();
        const { getEditedEntityRecord, getEntityRecordNonTransientEdits } = select9(import_core_data50.store);
        const templateRecord = getEditedEntityRecord(
          "postType",
          _postType,
          _postId
        );
        const hasEdits = Object.keys(
          getEntityRecordNonTransientEdits(
            "postType",
            _postType,
            _postId
          ) ?? {}
        ).length > 0;
        return {
          shouldOpenModal: !hasEdits && "" === templateRecord.content && TEMPLATE_POST_TYPE === _postType,
          slug: templateRecord.slug,
          isCustom: templateRecord.is_custom,
          postType: _postType,
          postId: _postId
        };
      },
      []
    );
    (0, import_element212.useEffect)(() => {
      setIsClosed(false);
    }, [postType2, postId2]);
    if (!shouldOpenModal || isClosed) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime367.jsx)(
      StartModal,
      {
        slug,
        isCustom,
        postType: postType2,
        onClose: () => setIsClosed(true)
      }
    );
  }

  // packages/editor/build-module/components/global-keyboard-shortcuts/index.mjs
  var import_keyboard_shortcuts4 = __toESM(require_keyboard_shortcuts(), 1);
  var import_data79 = __toESM(require_data(), 1);
  var import_block_editor28 = __toESM(require_block_editor(), 1);
  var { usesNativeUndo } = unlock(import_block_editor28.privateApis);
  function EditorKeyboardShortcuts() {
    const isModeToggleDisabled = (0, import_data79.useSelect)((select9) => {
      const { richEditingEnabled, codeEditingEnabled } = select9(store).getEditorSettings();
      return !richEditingEnabled || !codeEditingEnabled;
    }, []);
    const { getBlockSelectionStart: getBlockSelectionStart2 } = (0, import_data79.useSelect)(import_block_editor28.store);
    const { getActiveComplementaryArea: getActiveComplementaryArea2 } = (0, import_data79.useSelect)(store3);
    const { enableComplementaryArea: enableComplementaryArea2, disableComplementaryArea: disableComplementaryArea2 } = (0, import_data79.useDispatch)(store3);
    const {
      redo: redo2,
      undo: undo2,
      savePost: savePost2,
      setIsListViewOpened: setIsListViewOpened2,
      switchEditorMode: switchEditorMode2,
      toggleDistractionFree: toggleDistractionFree2
    } = (0, import_data79.useDispatch)(store);
    const {
      isEditedPostDirty: isEditedPostDirty2,
      isPostSavingLocked: isPostSavingLocked2,
      isListViewOpened: isListViewOpened2,
      getEditorMode: getEditorMode2,
      isSavingNonPostEntityChanges: isSavingNonPostEntityChanges2
    } = (0, import_data79.useSelect)(store);
    (0, import_keyboard_shortcuts4.useShortcut)(
      "core/editor/toggle-mode",
      () => {
        switchEditorMode2(
          getEditorMode2() === "visual" ? "text" : "visual"
        );
      },
      {
        isDisabled: isModeToggleDisabled
      }
    );
    (0, import_keyboard_shortcuts4.useShortcut)("core/editor/toggle-distraction-free", () => {
      toggleDistractionFree2();
    });
    (0, import_keyboard_shortcuts4.useShortcut)("core/editor/undo", (event) => {
      if (usesNativeUndo(event)) {
        return;
      }
      undo2();
      event.preventDefault();
    });
    (0, import_keyboard_shortcuts4.useShortcut)("core/editor/redo", (event) => {
      if (usesNativeUndo(event)) {
        return;
      }
      redo2();
      event.preventDefault();
    });
    (0, import_keyboard_shortcuts4.useShortcut)("core/editor/save", (event) => {
      event.preventDefault();
      if (isPostSavingLocked2() || isSavingNonPostEntityChanges2()) {
        return;
      }
      if (!isEditedPostDirty2()) {
        return;
      }
      savePost2();
    });
    (0, import_keyboard_shortcuts4.useShortcut)("core/editor/toggle-list-view", (event) => {
      if (!isListViewOpened2()) {
        event.preventDefault();
        setIsListViewOpened2(true);
      }
    });
    (0, import_keyboard_shortcuts4.useShortcut)("core/editor/toggle-sidebar", (event) => {
      event.preventDefault();
      const isEditorSidebarOpened = [
        "edit-post/document",
        "edit-post/block"
      ].includes(getActiveComplementaryArea2("core"));
      if (isEditorSidebarOpened) {
        disableComplementaryArea2("core");
      } else {
        const sidebarToOpen = getBlockSelectionStart2() ? "edit-post/block" : "edit-post/document";
        enableComplementaryArea2("core", sidebarToOpen);
      }
    });
    return null;
  }

  // packages/editor/build-module/components/template-part-menu-items/index.mjs
  var import_data82 = __toESM(require_data(), 1);
  var import_block_editor31 = __toESM(require_block_editor(), 1);

  // packages/editor/build-module/components/template-part-menu-items/convert-to-regular.mjs
  var import_data80 = __toESM(require_data(), 1);
  var import_block_editor29 = __toESM(require_block_editor(), 1);
  var import_core_data51 = __toESM(require_core_data(), 1);
  var import_components154 = __toESM(require_components(), 1);
  var import_i18n199 = __toESM(require_i18n(), 1);
  var import_html_entities12 = __toESM(require_html_entities(), 1);
  var import_element213 = __toESM(require_element(), 1);
  var import_jsx_runtime368 = __toESM(require_jsx_runtime(), 1);
  function ConvertToRegularBlocks({ clientId, onClose }) {
    const [showConfirmDialog, setShowConfirmDialog] = (0, import_element213.useState)(false);
    const { getBlocks: getBlocks2 } = (0, import_data80.useSelect)(import_block_editor29.store);
    const { replaceBlocks: replaceBlocks2 } = (0, import_data80.useDispatch)(import_block_editor29.store);
    const { canRemove, templatePartTitle } = (0, import_data80.useSelect)(
      (select9) => {
        const { canRemoveBlock, getBlock: getBlock2 } = select9(import_block_editor29.store);
        const { getEntityRecord, getCurrentTheme } = select9(import_core_data51.store);
        const block = getBlock2(clientId);
        const { slug, theme: theme2 } = block?.attributes ?? {};
        const themeSlug = theme2 || getCurrentTheme()?.stylesheet;
        const templatePartId = themeSlug && slug ? `${themeSlug}//${slug}` : null;
        const entity = templatePartId ? getEntityRecord(
          "postType",
          "wp_template_part",
          templatePartId
        ) : null;
        return {
          canRemove: canRemoveBlock(clientId),
          templatePartTitle: entity?.title?.rendered ? (0, import_html_entities12.decodeEntities)(entity.title.rendered) : null
        };
      },
      [clientId]
    );
    if (!canRemove) {
      return null;
    }
    const title = templatePartTitle ? (0, import_i18n199.sprintf)(
      /* translators: %s: template part title, e.g. "Header" */
      (0, import_i18n199.__)("Detach %s?"),
      templatePartTitle
    ) : (0, import_i18n199.__)("Detach template part?");
    const message2 = templatePartTitle ? (0, import_i18n199.sprintf)(
      /* translators: %s: template part title, e.g. "Header" */
      (0, import_i18n199.__)(
        "The blocks will be separated from the original template part and will be fully editable. Future changes to the %s template part will not apply here."
      ),
      templatePartTitle
    ) : (0, import_i18n199.__)(
      "The blocks will be separated from the original template part and will be fully editable. Future changes to the template part will not apply here."
    );
    return /* @__PURE__ */ (0, import_jsx_runtime368.jsxs)(import_jsx_runtime368.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(import_components154.MenuItem, { onClick: () => setShowConfirmDialog(true), children: (0, import_i18n199.__)("Detach") }),
      /* @__PURE__ */ (0, import_jsx_runtime368.jsx)(
        import_components154.__experimentalConfirmDialog,
        {
          isOpen: showConfirmDialog,
          onConfirm: () => {
            replaceBlocks2(clientId, getBlocks2(clientId));
            onClose();
          },
          onCancel: () => setShowConfirmDialog(false),
          confirmButtonText: (0, import_i18n199.__)("Detach"),
          size: "medium",
          title,
          __experimentalHideHeader: false,
          children: message2
        }
      )
    ] });
  }

  // packages/editor/build-module/components/template-part-menu-items/convert-to-template-part.mjs
  var import_data81 = __toESM(require_data(), 1);
  var import_block_editor30 = __toESM(require_block_editor(), 1);
  var import_components155 = __toESM(require_components(), 1);
  var import_blocks17 = __toESM(require_blocks(), 1);
  var import_i18n200 = __toESM(require_i18n(), 1);
  var import_element214 = __toESM(require_element(), 1);
  var import_notices17 = __toESM(require_notices(), 1);
  var import_core_data52 = __toESM(require_core_data(), 1);
  var import_jsx_runtime369 = __toESM(require_jsx_runtime(), 1);
  function ConvertToTemplatePart({ clientIds, blocks }) {
    const [isModalOpen, setIsModalOpen] = (0, import_element214.useState)(false);
    const { replaceBlocks: replaceBlocks2 } = (0, import_data81.useDispatch)(import_block_editor30.store);
    const { createSuccessNotice } = (0, import_data81.useDispatch)(import_notices17.store);
    const { isBlockBasedTheme, canCreate } = (0, import_data81.useSelect)((select9) => {
      return {
        isBlockBasedTheme: select9(import_core_data52.store).getCurrentTheme()?.is_block_theme,
        canCreate: select9(import_block_editor30.store).canInsertBlockType(
          "core/template-part"
        )
      };
    }, []);
    if (!isBlockBasedTheme || !canCreate) {
      return null;
    }
    const onConvert = async (templatePart) => {
      replaceBlocks2(
        clientIds,
        (0, import_blocks17.createBlock)("core/template-part", {
          slug: templatePart.slug,
          theme: templatePart.theme
        })
      );
      createSuccessNotice((0, import_i18n200.__)("Template part created."), {
        type: "snackbar"
      });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime369.jsxs)(import_jsx_runtime369.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(
        import_components155.MenuItem,
        {
          icon: symbol_filled_default,
          onClick: () => {
            setIsModalOpen(true);
          },
          "aria-expanded": isModalOpen,
          "aria-haspopup": "dialog",
          children: (0, import_i18n200.__)("Create template part")
        }
      ),
      isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime369.jsx)(
        CreateTemplatePartModal,
        {
          closeModal: () => {
            setIsModalOpen(false);
          },
          blocks,
          onCreate: onConvert
        }
      )
    ] });
  }

  // packages/editor/build-module/components/template-part-menu-items/index.mjs
  var import_jsx_runtime370 = __toESM(require_jsx_runtime(), 1);
  function TemplatePartMenuItems() {
    return /* @__PURE__ */ (0, import_jsx_runtime370.jsx)(import_block_editor31.BlockSettingsMenuControls, { children: ({ selectedClientIds, onClose }) => /* @__PURE__ */ (0, import_jsx_runtime370.jsx)(
      TemplatePartConverterMenuItem,
      {
        clientIds: selectedClientIds,
        onClose
      }
    ) });
  }
  function TemplatePartConverterMenuItem({ clientIds, onClose }) {
    const { blocks } = (0, import_data82.useSelect)(
      (select9) => {
        const { getBlocksByClientId: getBlocksByClientId2 } = select9(import_block_editor31.store);
        return {
          blocks: getBlocksByClientId2(clientIds)
        };
      },
      [clientIds]
    );
    if (blocks.length === 1 && blocks[0]?.name === "core/template-part") {
      return /* @__PURE__ */ (0, import_jsx_runtime370.jsx)(
        ConvertToRegularBlocks,
        {
          clientId: clientIds[0],
          onClose
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime370.jsx)(ConvertToTemplatePart, { clientIds, blocks });
  }

  // packages/editor/build-module/components/media/media-editor-modal.mjs
  var import_block_editor32 = __toESM(require_block_editor(), 1);
  var import_data84 = __toESM(require_data(), 1);
  var import_element216 = __toESM(require_element(), 1);

  // packages/editor/build-module/components/post-fields/index.mjs
  var import_element215 = __toESM(require_element(), 1);
  var import_data83 = __toESM(require_data(), 1);
  function usePostFields({
    postType: postType2
  }) {
    const { registerPostTypeSchema: registerPostTypeSchema2 } = unlock((0, import_data83.useDispatch)(store));
    (0, import_element215.useEffect)(() => {
      registerPostTypeSchema2(postType2);
    }, [registerPostTypeSchema2, postType2]);
    const { fields: fields2 } = (0, import_data83.useSelect)(
      (select9) => {
        const { getEntityFields: getEntityFields3 } = unlock(select9(store));
        return {
          fields: getEntityFields3("postType", postType2)
        };
      },
      [postType2]
    );
    return fields2;
  }
  var post_fields_default = usePostFields;

  // packages/editor/build-module/components/media/media-editor-modal.mjs
  var import_jsx_runtime371 = __toESM(require_jsx_runtime(), 1);
  var { MediaEditorModal: MediaEditorModal2, store: mediaEditorStore2 } = unlock(
    privateApis14
  );
  function ratioToNumber(ratio) {
    if (ratio === void 0 || ratio === null) {
      return NaN;
    }
    const [a3, b3, ...rest] = String(ratio).split("/").map(Number);
    if (a3 <= 0 || b3 <= 0 || Number.isNaN(a3) || Number.isNaN(b3) || rest.length) {
      return NaN;
    }
    return b3 ? a3 / b3 : a3;
  }
  function aspectRatioPresetFromSettings({ name: name2, ratio } = {}) {
    const value = ratioToNumber(ratio);
    if (!name2 || !Number.isFinite(value) || value <= 0) {
      return null;
    }
    return {
      label: name2,
      value
    };
  }
  function MediaEditorModalMount() {
    const isOpen2 = (0, import_data84.useSelect)(
      (select9) => select9(mediaEditorStore2).isOpen(),
      []
    );
    if (!isOpen2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime371.jsx)(MediaEditorModalContent, {});
  }
  function MediaEditorModalContent() {
    const fields2 = post_fields_default({ postType: "attachment" });
    const [defaultRatios, themeRatios, showDefaultRatios] = (0, import_block_editor32.useSettings)(
      "dimensions.aspectRatios.default",
      "dimensions.aspectRatios.theme",
      "dimensions.defaultAspectRatios"
    );
    const aspectRatioPresets = (0, import_element216.useMemo)(() => {
      const hasAspectRatioSettings = Array.isArray(defaultRatios) || Array.isArray(themeRatios) || typeof showDefaultRatios === "boolean";
      if (!hasAspectRatioSettings) {
        return void 0;
      }
      const candidateRatios = [
        ...showDefaultRatios && Array.isArray(defaultRatios) ? defaultRatios : [],
        ...Array.isArray(themeRatios) ? themeRatios : []
      ];
      const presets = candidateRatios.map(aspectRatioPresetFromSettings).filter(Boolean);
      if (presets.length || showDefaultRatios === false) {
        return presets;
      }
      return void 0;
    }, [defaultRatios, themeRatios, showDefaultRatios]);
    return /* @__PURE__ */ (0, import_jsx_runtime371.jsx)(
      MediaEditorModal2,
      {
        fields: fields2,
        aspectRatioPresets
      }
    );
  }

  // packages/editor/build-module/components/provider/index.mjs
  var import_jsx_runtime372 = __toESM(require_jsx_runtime(), 1);
  var { ExperimentalBlockEditorProvider } = unlock(import_block_editor33.privateApis);
  var { PatternsMenuItems } = unlock(import_patterns8.privateApis);
  var noop10 = () => {
  };
  var NON_CONTEXTUAL_POST_TYPES = [
    "wp_block",
    "wp_navigation",
    "wp_template_part"
  ];
  function useBlockEditorProps(post2, template2, mode) {
    const revisionBlocks = useRevisionBlocks();
    const rootLevelPost = mode === "template-locked" ? "template" : "post";
    const [postBlocks, onInput, onChange] = (0, import_core_data53.useEntityBlockEditor)(
      "postType",
      post2.type,
      { id: post2.id }
    );
    const [templateBlocks, onInputTemplate, onChangeTemplate] = (0, import_core_data53.useEntityBlockEditor)("postType", template2?.type, {
      id: template2?.id
    });
    const maybeNavigationBlocks = (0, import_element217.useMemo)(() => {
      if (post2.type === "wp_navigation") {
        return [
          (0, import_blocks18.createBlock)("core/navigation", {
            ref: post2.id,
            // As the parent editor is locked with `templateLock`, the template locking
            // must be explicitly "unset" on the block itself to allow the user to modify
            // the block's content.
            templateLock: false
          })
        ];
      }
    }, [post2.type, post2.id]);
    const blocks = (0, import_element217.useMemo)(() => {
      if (maybeNavigationBlocks) {
        return maybeNavigationBlocks;
      }
      if (rootLevelPost === "template") {
        return templateBlocks;
      }
      return postBlocks;
    }, [maybeNavigationBlocks, rootLevelPost, templateBlocks, postBlocks]);
    if (revisionBlocks !== null) {
      return [revisionBlocks, noop10, noop10];
    }
    const disableRootLevelChanges = !!template2 && mode === "template-locked" || post2.type === "wp_navigation";
    if (disableRootLevelChanges) {
      return [blocks, noop10, noop10];
    }
    return [
      blocks,
      rootLevelPost === "post" ? onInput : onInputTemplate,
      rootLevelPost === "post" ? onChange : onChangeTemplate
    ];
  }
  var ExperimentalEditorProvider = with_registry_provider_default(
    ({
      post: post2,
      settings,
      recovery,
      initialEdits,
      children,
      BlockEditorProviderComponent = ExperimentalBlockEditorProvider,
      __unstableTemplate: template2
    }) => {
      const hasTemplate = !!template2;
      const {
        editorSettings: editorSettings2,
        selection,
        isReady: isReady2,
        mode,
        defaultMode,
        postTypeEntities,
        isInRevisionsMode,
        currentRevisionId
      } = (0, import_data85.useSelect)(
        (select9) => {
          const {
            getEditorSettings: getEditorSettings2,
            getRenderingMode: getRenderingMode2,
            __unstableIsEditorReady: __unstableIsEditorReady2,
            getDefaultRenderingMode: getDefaultRenderingMode2,
            isRevisionsMode: _isRevisionsMode,
            getCurrentRevisionId: _getCurrentRevisionId
          } = unlock(select9(store));
          const { getEntitiesConfig, getEntityRecordEdits } = select9(import_core_data53.store);
          const _mode = getRenderingMode2();
          const _defaultMode = getDefaultRenderingMode2(post2.type);
          const hasResolvedDefaultMode = _defaultMode === "template-locked" ? hasTemplate : _defaultMode !== void 0;
          const isRenderingModeReady = _defaultMode !== void 0;
          const entityEdits = getEntityRecordEdits(
            "postType",
            post2.type,
            post2.id
          );
          return {
            editorSettings: getEditorSettings2(),
            isReady: __unstableIsEditorReady2(),
            mode: isRenderingModeReady ? _mode : void 0,
            defaultMode: hasResolvedDefaultMode ? _defaultMode : void 0,
            selection: entityEdits?.selection,
            postTypeEntities: post2.type === "wp_template" ? getEntitiesConfig("postType") : null,
            isInRevisionsMode: _isRevisionsMode(),
            currentRevisionId: _getCurrentRevisionId()
          };
        },
        [post2.type, post2.id, hasTemplate]
      );
      const shouldRenderTemplate = hasTemplate && mode !== "post-only";
      const rootLevelPost = shouldRenderTemplate ? template2 : post2;
      const defaultBlockContext = (0, import_element217.useMemo)(() => {
        const postContext = {};
        if (post2.type === "wp_template") {
          if (post2.slug === "page") {
            postContext.postType = "page";
          } else if (post2.slug === "single") {
            postContext.postType = "post";
          } else if (post2.slug.split("-")[0] === "single") {
            const postTypeNames = postTypeEntities?.map((entity) => entity.name) || [];
            const match3 = post2.slug.match(
              `^single-(${postTypeNames.join("|")})(?:-.+)?$`
            );
            if (match3) {
              postContext.postType = match3[1];
            }
          }
        } else if (!NON_CONTEXTUAL_POST_TYPES.includes(rootLevelPost.type) || shouldRenderTemplate) {
          postContext.postId = post2.id;
          postContext.postType = post2.type;
        }
        return {
          ...postContext,
          templateSlug: rootLevelPost.type === "wp_template" ? rootLevelPost.slug : void 0
        };
      }, [
        shouldRenderTemplate,
        post2.id,
        post2.type,
        post2.slug,
        rootLevelPost.type,
        rootLevelPost.slug,
        postTypeEntities
      ]);
      const { id, type } = rootLevelPost;
      const blockEditorSettings = use_block_editor_settings_default(
        editorSettings2,
        type,
        id,
        mode
      );
      const [blocks, onInput, onChange] = useBlockEditorProps(
        post2,
        template2,
        mode
      );
      const {
        updatePostLock: updatePostLock2,
        setupEditor: setupEditor2,
        updateEditorSettings: updateEditorSettings2,
        setCurrentTemplateId: setCurrentTemplateId2,
        setEditedPost: setEditedPost2,
        setRenderingMode: setRenderingMode2,
        setCurrentRevisionId: setCurrentRevisionId2
      } = unlock((0, import_data85.useDispatch)(store));
      const { editEntityRecord } = (0, import_data85.useDispatch)(import_core_data53.store);
      const registry = (0, import_data85.useRegistry)();
      const onChangeSelection = (0, import_element217.useCallback)(
        (newSelection) => {
          editEntityRecord(
            "postType",
            post2.type,
            post2.id,
            { selection: newSelection },
            { undoIgnore: true }
          );
        },
        [editEntityRecord, post2.type, post2.id]
      );
      const { createWarningNotice, removeNotice } = (0, import_data85.useDispatch)(import_notices18.store);
      (0, import_element217.useLayoutEffect)(() => {
        if (recovery) {
          return;
        }
        updatePostLock2(settings.postLock);
        if (!registry.select(store).__unstableIsEditorReady()) {
          setupEditor2(post2, initialEdits, settings.template);
        }
        if (settings.autosave) {
          const autosaveId = Number(
            (0, import_url13.getQueryArg)(settings.autosave.editLink, "revision")
          );
          createWarningNotice(
            (0, import_i18n201.__)(
              "There is an autosave of this post that is more recent than the version below."
            ),
            {
              id: "autosave-exists",
              actions: [
                {
                  label: (0, import_i18n201.__)("View the autosave"),
                  ...autosaveId ? {
                    onClick: () => {
                      const {
                        disableVisualRevisions
                      } = registry.select(store).getEditorSettings();
                      if (disableVisualRevisions) {
                        window.location.href = settings.autosave.editLink;
                        return;
                      }
                      setCurrentRevisionId2(
                        autosaveId
                      );
                    }
                  } : { url: settings.autosave.editLink }
                }
              ]
            }
          );
        }
      }, []);
      (0, import_element217.useEffect)(() => {
        setEditedPost2(post2.type, post2.id);
        if (typeof window !== "undefined" && window.__experimentalTemplateActivate) {
          removeNotice("template-activate-notice");
        }
        return () => setEditedPost2(null, null);
      }, [post2.type, post2.id, setEditedPost2, removeNotice]);
      (0, import_element217.useLayoutEffect)(() => {
        updateEditorSettings2(settings);
      }, [settings, updateEditorSettings2]);
      (0, import_element217.useEffect)(() => {
        setCurrentTemplateId2(template2?.id);
      }, [template2?.id, setCurrentTemplateId2]);
      (0, import_element217.useEffect)(() => {
        if (defaultMode) {
          setRenderingMode2(defaultMode);
        }
      }, [defaultMode, setRenderingMode2]);
      useHideBlocksFromInserter(post2.type, mode);
      useCommands();
      useUploadSaveLock();
      useNetworkReconnect();
      if (!isReady2 || !mode) {
        return null;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(import_core_data53.EntityProvider, { kind: "root", type: "site", children: /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
        import_core_data53.EntityProvider,
        {
          kind: "postType",
          type: post2.type,
          id: post2.id,
          revisionId: currentRevisionId ?? void 0,
          children: /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(import_block_editor33.BlockContextProvider, { value: defaultBlockContext, children: /* @__PURE__ */ (0, import_jsx_runtime372.jsxs)(
            BlockEditorProviderComponent,
            {
              value: blocks,
              onChange,
              onInput,
              selection: isInRevisionsMode ? void 0 : selection,
              onChangeSelection: isInRevisionsMode ? noop10 : onChangeSelection,
              settings: blockEditorSettings,
              useSubRegistry: false,
              children: [
                children,
                !settings.isPreviewMode && /* @__PURE__ */ (0, import_jsx_runtime372.jsxs)(import_jsx_runtime372.Fragment, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(PatternsMenuItems, {}),
                  /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(TemplatePartMenuItems, {}),
                  mode === "template-locked" && /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(DisableNonPageContentBlocks, {}),
                  type === "wp_navigation" && /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(NavigationBlockEditingMode, {}),
                  /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(EditorKeyboardShortcuts, {}),
                  /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(keyboard_shortcut_help_modal_default, {}),
                  /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(BlockRemovalWarnings, {}),
                  /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(StartPageOptions, {}),
                  /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(StartTemplateOptions, {}),
                  /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(PatternRenameModal, {}),
                  /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(PatternDuplicateModal, {}),
                  /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(MediaEditorModalMount, {})
                ] })
              ]
            }
          ) })
        }
      ) });
    }
  );
  function EditorProvider(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime372.jsx)(
      ExperimentalEditorProvider,
      {
        ...props,
        BlockEditorProviderComponent: import_block_editor33.BlockEditorProvider,
        children: props.children
      }
    );
  }
  var provider_default = EditorProvider;

  // packages/editor/build-module/dataviews/fields/content-preview/content-preview-view.mjs
  var import_jsx_runtime373 = __toESM(require_jsx_runtime(), 1);
  function PostPreviewContainer({
    template: template2,
    post: post2
  }) {
    const [backgroundColor = "white"] = useStyle2("color.background");
    const [postBlocks] = (0, import_core_data54.useEntityBlockEditor)("postType", post2.type, {
      id: post2.id
    });
    const [templateBlocks] = (0, import_core_data54.useEntityBlockEditor)(
      "postType",
      template2?.type,
      {
        id: template2?.id
      }
    );
    const blocks = template2 && templateBlocks ? templateBlocks : postBlocks;
    const isEmpty2 = !blocks?.length;
    return /* @__PURE__ */ (0, import_jsx_runtime373.jsxs)(
      "div",
      {
        className: "editor-fields-content-preview",
        style: {
          backgroundColor
        },
        children: [
          isEmpty2 && /* @__PURE__ */ (0, import_jsx_runtime373.jsx)("span", { className: "editor-fields-content-preview__empty", children: (0, import_i18n202.__)("Empty content") }),
          !isEmpty2 && /* @__PURE__ */ (0, import_jsx_runtime373.jsx)(import_block_editor34.BlockPreview.Async, { children: /* @__PURE__ */ (0, import_jsx_runtime373.jsx)(import_block_editor34.BlockPreview, { blocks }) })
        ]
      }
    );
  }
  function PostPreviewView({ item }) {
    const { settings, template: template2 } = (0, import_data86.useSelect)(
      (select9) => {
        const { canUser, getPostType, getTemplateId, getEntityRecord } = unlock(select9(import_core_data54.store));
        const canViewTemplate = canUser("read", {
          kind: "postType",
          name: "wp_template"
        });
        const _settings = select9(store).getEditorSettings();
        const supportsTemplateMode = _settings.supportsTemplateMode;
        const isViewable = getPostType(item.type)?.viewable ?? false;
        const templateId2 = supportsTemplateMode && isViewable && canViewTemplate ? getTemplateId(item.type, item.id) : null;
        return {
          settings: _settings,
          template: templateId2 ? getEntityRecord("postType", "wp_template", templateId2) : void 0
        };
      },
      [item.type, item.id]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime373.jsx)(
      EditorProvider,
      {
        post: item,
        settings,
        __unstableTemplate: template2,
        children: /* @__PURE__ */ (0, import_jsx_runtime373.jsx)(PostPreviewContainer, { template: template2, post: item })
      }
    );
  }

  // packages/editor/build-module/dataviews/fields/content-preview/index.mjs
  var postPreviewField = {
    type: "media",
    id: "content-preview",
    label: (0, import_i18n203.__)("Content preview"),
    render: PostPreviewView,
    enableSorting: false
  };
  var content_preview_default = postPreviewField;

  // packages/editor/build-module/dataviews/store/private-actions.mjs
  function hasEditorNotesSupport(supports) {
    const editor = supports?.editor;
    if (Array.isArray(editor)) {
      return !!editor[0]?.notes;
    }
    return false;
  }
  function registerEntityAction(kind, name2, config2) {
    return {
      type: "REGISTER_ENTITY_ACTION",
      kind,
      name: name2,
      config: config2
    };
  }
  function unregisterEntityAction(kind, name2, actionId) {
    return {
      type: "UNREGISTER_ENTITY_ACTION",
      kind,
      name: name2,
      actionId
    };
  }
  function registerEntityField(kind, name2, config2) {
    return {
      type: "REGISTER_ENTITY_FIELD",
      kind,
      name: name2,
      config: config2
    };
  }
  function unregisterEntityField(kind, name2, fieldId) {
    return {
      type: "UNREGISTER_ENTITY_FIELD",
      kind,
      name: name2,
      fieldId
    };
  }
  function setIsReady(kind, name2) {
    return {
      type: "SET_IS_READY",
      kind,
      name: name2
    };
  }
  var ORDERED_MEDIA_FIELDS = [
    // Metadata in panels (collapsed by default).
    date_added_default,
    author_default2,
    filename_default,
    mime_type_default,
    filesize_default,
    media_dimensions_default,
    attached_to_default,
    // Regular layout fields (always visible).
    title_default,
    alt_text_default,
    caption_default,
    description_default2
  ];
  var registerPostTypeSchema = (postType2) => async ({ registry }) => {
    const isReady2 = unlock(registry.select(store)).isEntityReady(
      "postType",
      postType2
    );
    if (isReady2) {
      return;
    }
    unlock(registry.dispatch(store)).setIsReady(
      "postType",
      postType2
    );
    const postTypeConfig = await registry.resolveSelect(import_core_data55.store).getPostType(postType2);
    const canCreate = await registry.resolveSelect(import_core_data55.store).canUser("create", {
      kind: "postType",
      name: postType2
    });
    const currentTheme = await registry.resolveSelect(import_core_data55.store).getCurrentTheme();
    const { disablePostFormats } = registry.select(store).getEditorSettings();
    let canDuplicate = !["wp_block", "wp_template_part"].includes(
      postTypeConfig.slug
    ) && canCreate && duplicate_post_default;
    if (true) {
      if ("wp_template" !== postTypeConfig.slug) {
        canDuplicate = void 0;
      }
    }
    if (postTypeConfig.slug === "wp_template" && !window?.__experimentalTemplateActivate) {
      canDuplicate = void 0;
    }
    const actions2 = [
      postTypeConfig.viewable ? view_post_default : void 0,
      !!postTypeConfig.supports?.revisions ? view_post_revisions_default : void 0,
      // @ts-ignore
      canDuplicate,
      postTypeConfig.slug === "wp_template_part" && canCreate && currentTheme?.is_block_theme ? duplicate_template_part_default : void 0,
      canCreate && postTypeConfig.slug === "wp_block" ? duplicate_pattern_default : void 0,
      postTypeConfig.supports?.title ? rename_post_default : void 0,
      postTypeConfig.supports?.["page-attributes"] ? reorder_page_default : void 0,
      postTypeConfig.slug === "wp_block" ? export_pattern_default : void 0,
      restore_post_default,
      reset_post_default,
      delete_post_default,
      trash_post_default,
      permanently_delete_post_default
    ].filter(Boolean);
    let fields2;
    if (postType2 === ATTACHMENT_POST_TYPE) {
      fields2 = ORDERED_MEDIA_FIELDS;
    } else {
      const postTypeSlug = postTypeConfig.slug;
      const isDesignPostType = DESIGN_POST_TYPES.includes(postTypeSlug);
      const isPattern = postTypeSlug === "wp_block";
      fields2 = [
        postTypeConfig.supports?.thumbnail && currentTheme?.theme_supports?.["post-thumbnails"] && featured_image_default,
        !isDesignPostType && postTypeConfig.supports?.author && author_default,
        postTypeSlug === "wp_template" && templateAuthorField,
        postTypeSlug === "wp_template_part" && templatePartAuthorField,
        !isDesignPostType && status_default,
        !isDesignPostType && date_default,
        !isDesignPostType && scheduled_date_default,
        last_edited_default,
        !isDesignPostType && slug_default,
        !isDesignPostType && postTypeConfig.supports?.excerpt && excerpt_default,
        isPattern && postTypeConfig.supports?.excerpt && pattern_description_default,
        postTypeConfig.supports?.["page-attributes"] && parent_default,
        postTypeConfig.supports?.comments && comment_status_default,
        postTypeConfig.supports?.trackbacks && ping_status_default,
        (postTypeConfig.supports?.comments || postTypeConfig.supports?.trackbacks) && discussion_default,
        !isDesignPostType && template_default,
        postTypeConfig.supports?.["post-formats"] && !disablePostFormats && format_default,
        (!isDesignPostType || isPattern) && postTypeConfig.supports?.editor && post_content_info_default,
        !isDesignPostType && password_default,
        postTypeSlug === "post" && sticky_default,
        postTypeSlug === "wp_template" && description_default,
        postTypeSlug === "wp_template" && readOnlyDescriptionField,
        // The `home`/`index` template summary exposes a few fields that
        // target other entities (`root/site` and the posts page).
        // `DataFormPostSummary` overrides them to read/write the right
        // entity and to control their visibility.
        postTypeSlug === "wp_template" && posts_page_title_default,
        postTypeSlug === "wp_template" && posts_per_page_default,
        postTypeSlug === "wp_template" && site_discussion_default,
        postTypeConfig.supports?.editor && postTypeConfig.viewable && content_preview_default,
        hasEditorNotesSupport(postTypeConfig.supports) && notes_default,
        isPattern && pattern_sync_status_default
      ].filter(Boolean);
      if (postTypeConfig.supports?.title) {
        let _titleField;
        if (postType2 === "page") {
          _titleField = page_title_default;
        } else if (postType2 === "wp_template") {
          _titleField = template_title_default;
        } else if (["wp_block", "wp_template_part"].includes(postType2)) {
          _titleField = pattern_title_default;
        } else {
          _titleField = title_default;
        }
        fields2.push(_titleField);
      }
    }
    registry.batch(() => {
      actions2.forEach((action) => {
        unlock(registry.dispatch(store)).registerEntityAction(
          "postType",
          postType2,
          action
        );
      });
      fields2.forEach((field) => {
        unlock(registry.dispatch(store)).registerEntityField(
          "postType",
          postType2,
          field
        );
      });
    });
    (0, import_hooks38.doAction)("core.registerPostTypeSchema", postType2);
  };

  // packages/editor/build-module/store/private-actions.mjs
  function setCurrentTemplateId(id) {
    return {
      type: "SET_CURRENT_TEMPLATE_ID",
      id
    };
  }
  var createTemplate = (template2) => async ({ select: select9, dispatch: dispatch8, registry }) => {
    const savedTemplate = await registry.dispatch(import_core_data56.store).saveEntityRecord("postType", "wp_template", template2);
    registry.dispatch(import_core_data56.store).editEntityRecord(
      "postType",
      select9.getCurrentPostType(),
      select9.getCurrentPostId(),
      {
        template: savedTemplate.slug
      }
    );
    registry.dispatch(import_notices19.store).createSuccessNotice(
      (0, import_i18n204.__)("Custom template created. You're in template mode now."),
      {
        type: "snackbar",
        actions: [
          {
            label: (0, import_i18n204.__)("Go back"),
            onClick: () => dispatch8.setRenderingMode(
              select9.getEditorSettings().defaultRenderingMode
            )
          }
        ]
      }
    );
    return savedTemplate;
  };
  var showBlockTypes = (blockNames) => ({ registry }) => {
    const existingBlockNames = registry.select(import_preferences9.store).get("core", "hiddenBlockTypes") ?? [];
    const newBlockNames = existingBlockNames.filter(
      (type) => !(Array.isArray(blockNames) ? blockNames : [blockNames]).includes(type)
    );
    registry.dispatch(import_preferences9.store).set("core", "hiddenBlockTypes", newBlockNames);
  };
  var hideBlockTypes = (blockNames) => ({ registry }) => {
    const existingBlockNames = registry.select(import_preferences9.store).get("core", "hiddenBlockTypes") ?? [];
    const mergedBlockNames = /* @__PURE__ */ new Set([
      ...existingBlockNames,
      ...Array.isArray(blockNames) ? blockNames : [blockNames]
    ]);
    registry.dispatch(import_preferences9.store).set("core", "hiddenBlockTypes", [...mergedBlockNames]);
  };
  var saveDirtyEntities = ({
    onSave,
    dirtyEntityRecords = [],
    entitiesToSkip = [],
    close,
    successNoticeContent
  } = {}) => ({ registry }) => {
    const PUBLISH_ON_SAVE_ENTITIES = [
      { kind: "postType", name: "wp_navigation" }
    ];
    const saveNoticeId = "site-editor-save-success";
    const homeUrl = registry.select(import_core_data56.store).getEntityRecord("root", "__unstableBase")?.home;
    registry.dispatch(import_notices19.store).removeNotice(saveNoticeId);
    const entitiesToSave = dirtyEntityRecords.filter(
      ({ kind, name: name2, key, property }) => {
        return !entitiesToSkip.some(
          (elt) => elt.kind === kind && elt.name === name2 && elt.key === key && elt.property === property
        );
      }
    );
    close?.(entitiesToSave);
    const siteItemsToSave = [];
    const pendingSavedRecords = [];
    entitiesToSave.forEach(({ kind, name: name2, key, property }) => {
      if ("root" === kind && "site" === name2) {
        siteItemsToSave.push(property);
      } else {
        if (PUBLISH_ON_SAVE_ENTITIES.some(
          (typeToPublish) => typeToPublish.kind === kind && typeToPublish.name === name2
        )) {
          registry.dispatch(import_core_data56.store).editEntityRecord(kind, name2, key, {
            status: "publish"
          });
        }
        pendingSavedRecords.push(
          registry.dispatch(import_core_data56.store).saveEditedEntityRecord(kind, name2, key, {
            throwOnError: true
          }).catch(ensureError)
        );
      }
    });
    if (siteItemsToSave.length) {
      pendingSavedRecords.push(
        registry.dispatch(import_core_data56.store).__experimentalSaveSpecifiedEntityEdits(
          "root",
          "site",
          void 0,
          siteItemsToSave,
          {
            throwOnError: true
          }
        ).catch(ensureError)
      );
    }
    registry.dispatch(import_block_editor35.store).__unstableMarkLastChangeAsPersistent();
    return Promise.all(pendingSavedRecords).then(async (values) => {
      if (onSave) {
        await onSave();
      }
      return values;
    }).then((values) => {
      const errors = values.filter((v3) => v3 instanceof Error);
      if (errors.length) {
        const firstMessage = errors.find(
          (e3) => e3.message
        )?.message;
        registry.dispatch(import_notices19.store).createErrorNotice(
          (0, import_html_entities13.decodeEntities)(
            firstMessage || (0, import_i18n204.__)("Saving failed.")
          ),
          {
            type: "snackbar",
            id: saveNoticeId
          }
        );
      } else {
        registry.dispatch(import_notices19.store).createSuccessNotice(
          successNoticeContent || (0, import_i18n204.__)("Site updated."),
          {
            type: "snackbar",
            id: saveNoticeId,
            actions: [
              {
                label: (0, import_i18n204.__)("View site"),
                url: homeUrl,
                openInNewTab: true
              }
            ]
          }
        );
      }
    }).catch(
      (error2) => registry.dispatch(import_notices19.store).createErrorNotice(
        (0, import_html_entities13.decodeEntities)(
          error2?.message || (0, import_i18n204.__)("Saving failed.")
        ),
        {
          type: "snackbar",
          id: saveNoticeId
        }
      )
    );
    function ensureError(error2) {
      if (error2 instanceof Error) {
        return error2;
      }
      let message2;
      if (!error2) {
      } else if (typeof error2.message === "string") {
        message2 = error2.message;
      } else if (typeof error2 === "string") {
        message2 = error2;
      } else if (Object.hasOwn(error2, "toString") && typeof error2.toString === "function") {
        const result = error2.toString();
        if (typeof result === "string") {
          message2 = result;
        }
      }
      return new Error(message2, { cause: error2 });
    }
  };
  var revertTemplate2 = (template2, { allowUndo = true } = {}) => async ({ registry }) => {
    const noticeId = "edit-site-template-reverted";
    registry.dispatch(import_notices19.store).removeNotice(noticeId);
    if (!isTemplateRevertable(template2)) {
      registry.dispatch(import_notices19.store).createErrorNotice((0, import_i18n204.__)("This template is not revertable."), {
        type: "snackbar"
      });
      return;
    }
    try {
      const templateEntityConfig = registry.select(import_core_data56.store).getEntityConfig("postType", template2.type);
      if (!templateEntityConfig) {
        registry.dispatch(import_notices19.store).createErrorNotice(
          (0, import_i18n204.__)(
            "The editor has encountered an unexpected error. Please reload."
          ),
          { type: "snackbar" }
        );
        return;
      }
      const fileTemplatePath = (0, import_url14.addQueryArgs)(
        `${templateEntityConfig.baseURL}/${template2.id}`,
        { context: "edit", source: template2.origin }
      );
      const fileTemplate = await (0, import_api_fetch7.default)({ path: fileTemplatePath });
      if (!fileTemplate) {
        registry.dispatch(import_notices19.store).createErrorNotice(
          (0, import_i18n204.__)(
            "The editor has encountered an unexpected error. Please reload."
          ),
          { type: "snackbar" }
        );
        return;
      }
      const serializeBlocks = ({
        blocks: blocksForSerialization = []
      }) => (0, import_blocks19.__unstableSerializeAndClean)(blocksForSerialization);
      const edited = registry.select(import_core_data56.store).getEditedEntityRecord(
        "postType",
        template2.type,
        template2.id
      );
      registry.dispatch(import_core_data56.store).editEntityRecord(
        "postType",
        template2.type,
        template2.id,
        {
          content: serializeBlocks,
          // Required to make the `undo` behave correctly.
          blocks: edited.blocks,
          // Required to revert the blocks in the editor.
          source: "custom"
          // required to avoid turning the editor into a dirty state
        },
        {
          undoIgnore: true
          // Required to merge this edit with the last undo level.
        }
      );
      const blocks = (0, import_blocks19.parse)(fileTemplate?.content?.raw);
      registry.dispatch(import_core_data56.store).editEntityRecord("postType", template2.type, fileTemplate.id, {
        content: serializeBlocks,
        blocks,
        source: "theme"
      });
      if (allowUndo) {
        const undoRevert = () => {
          registry.dispatch(import_core_data56.store).editEntityRecord(
            "postType",
            template2.type,
            edited.id,
            {
              content: serializeBlocks,
              blocks: edited.blocks,
              source: "custom"
            }
          );
        };
        registry.dispatch(import_notices19.store).createSuccessNotice((0, import_i18n204.__)("Template reset."), {
          type: "snackbar",
          id: noticeId,
          actions: [
            {
              label: (0, import_i18n204.__)("Undo"),
              onClick: undoRevert
            }
          ]
        });
      }
    } catch (error2) {
      const errorMessage = error2.message && error2.code !== "unknown_error" ? error2.message : (0, import_i18n204.__)("Template revert failed. Please reload.");
      registry.dispatch(import_notices19.store).createErrorNotice(errorMessage, { type: "snackbar" });
    }
  };
  var removeTemplates = (items) => async ({ registry }) => {
    const isResetting = items.every((item) => item?.has_theme_file);
    const promiseResult = await Promise.allSettled(
      items.map((item) => {
        return registry.dispatch(import_core_data56.store).deleteEntityRecord(
          "postType",
          item.type,
          item.id,
          { force: true },
          { throwOnError: true }
        );
      })
    );
    if (promiseResult.every(({ status }) => status === "fulfilled")) {
      let successMessage;
      if (items.length === 1) {
        let title;
        if (typeof items[0].title === "string") {
          title = items[0].title;
        } else if (typeof items[0].title?.rendered === "string") {
          title = items[0].title?.rendered;
        } else if (typeof items[0].title?.raw === "string") {
          title = items[0].title?.raw;
        }
        successMessage = isResetting ? (0, import_i18n204.sprintf)(
          /* translators: %s: The template/part's name. */
          (0, import_i18n204.__)('"%s" reset.'),
          (0, import_html_entities13.decodeEntities)(title)
        ) : (0, import_i18n204.sprintf)(
          /* translators: %s: The template/part's name. */
          (0, import_i18n204._x)('"%s" deleted.', "template part"),
          (0, import_html_entities13.decodeEntities)(title)
        );
      } else {
        successMessage = isResetting ? (0, import_i18n204.__)("Items reset.") : (0, import_i18n204.__)("Items deleted.");
      }
      registry.dispatch(import_notices19.store).createSuccessNotice(successMessage, {
        type: "snackbar",
        id: "editor-template-deleted-success"
      });
    } else {
      let errorMessage;
      if (promiseResult.length === 1) {
        if (promiseResult[0].reason?.message) {
          errorMessage = promiseResult[0].reason.message;
        } else {
          errorMessage = isResetting ? (0, import_i18n204.__)("An error occurred while reverting the item.") : (0, import_i18n204.__)("An error occurred while deleting the item.");
        }
      } else {
        const errorMessages = /* @__PURE__ */ new Set();
        const failedPromises = promiseResult.filter(
          ({ status }) => status === "rejected"
        );
        for (const failedPromise of failedPromises) {
          if (failedPromise.reason?.message) {
            errorMessages.add(failedPromise.reason.message);
          }
        }
        if (errorMessages.size === 0) {
          errorMessage = (0, import_i18n204.__)(
            "An error occurred while deleting the items."
          );
        } else if (errorMessages.size === 1) {
          errorMessage = isResetting ? (0, import_i18n204.sprintf)(
            /* translators: %s: an error message */
            (0, import_i18n204.__)(
              "An error occurred while reverting the items: %s"
            ),
            [...errorMessages][0]
          ) : (0, import_i18n204.sprintf)(
            /* translators: %s: an error message */
            (0, import_i18n204.__)(
              "An error occurred while deleting the items: %s"
            ),
            [...errorMessages][0]
          );
        } else {
          errorMessage = isResetting ? (0, import_i18n204.sprintf)(
            /* translators: %s: a list of comma separated error messages */
            (0, import_i18n204.__)(
              "Some errors occurred while reverting the items: %s"
            ),
            [...errorMessages].join(",")
          ) : (0, import_i18n204.sprintf)(
            /* translators: %s: a list of comma separated error messages */
            (0, import_i18n204.__)(
              "Some errors occurred while deleting the items: %s"
            ),
            [...errorMessages].join(",")
          );
        }
      }
      registry.dispatch(import_notices19.store).createErrorNotice(errorMessage, { type: "snackbar" });
    }
  };
  var setDefaultRenderingMode = (mode) => ({ select: select9, registry }) => {
    const postType2 = select9.getCurrentPostType();
    const theme2 = registry.select(import_core_data56.store).getCurrentTheme()?.stylesheet;
    const renderingModes = registry.select(import_preferences9.store).get("core", "renderingModes")?.[theme2] ?? {};
    if (renderingModes[postType2] === mode) {
      return;
    }
    const newModes = {
      [theme2]: {
        ...renderingModes,
        [postType2]: mode
      }
    };
    registry.dispatch(import_preferences9.store).set("core", "renderingModes", newModes);
  };
  function setStylesPath(path) {
    return {
      type: "SET_STYLES_PATH",
      path
    };
  }
  function setShowStylebook(show) {
    return {
      type: "SET_SHOW_STYLEBOOK",
      show
    };
  }
  function resetStylesNavigation() {
    return {
      type: "RESET_STYLES_NAVIGATION"
    };
  }
  function setCanvasWidth(width) {
    return ({ dispatch: dispatch8, registry }) => {
      dispatch8({
        type: "SET_CANVAS_WIDTH",
        width
      });
      const blockEditorSelect = unlock(registry.select(import_block_editor35.store));
      if (blockEditorSelect.isResponsiveEditing()) {
        const viewportSettings = blockEditorSelect.getSettings().__experimentalFeatures?.viewport;
        const deviceType = getDeviceTypeByCanvasWidth(
          width,
          viewportSettings
        );
        unlock(
          registry.dispatch(import_block_editor35.store)
        ).setStyleStateViewport(
          VIEWPORT_STATE_BY_DEVICE_TYPE[deviceType] ?? "default"
        );
      }
    };
  }
  function setCurrentRevisionId(revisionId2) {
    return {
      type: "SET_CURRENT_REVISION_ID",
      revisionId: revisionId2
    };
  }
  var setRevisionPage = (page) => async ({ dispatch: dispatch8, select: select9, registry }) => {
    const postType2 = select9.getCurrentPostType();
    const postId2 = select9.getCurrentPostId();
    const entityConfig = registry.select(import_core_data56.store).getEntityConfig("postType", postType2);
    const revisionKey = entityConfig?.revisionKey || "id";
    const revisions = await registry.resolveSelect(import_core_data56.store).getRevisions(
      "postType",
      postType2,
      postId2,
      buildRevisionsPageQuery(revisionKey, page)
    );
    registry.batch(() => {
      dispatch8({ type: "SET_REVISION_PAGE", page });
      if (revisions?.length) {
        dispatch8.setCurrentRevisionId(revisions[0][revisionKey]);
      }
    });
  };
  function createRevisionsLoadFailedNotice(registry) {
    registry.dispatch(import_notices19.store).createNotice("warning", (0, import_i18n204.__)("Revisions could not be loaded."), {
      type: "snackbar",
      id: "editor-revisions-load-failed"
    });
  }
  var openRevision = (revisionId2) => async ({ dispatch: dispatch8, select: select9, registry }) => {
    dispatch8.setCurrentRevisionId(revisionId2);
    const postType2 = select9.getCurrentPostType();
    const postId2 = select9.getCurrentPostId();
    const entityConfig = registry.select(import_core_data56.store).getEntityConfig("postType", postType2);
    const revisionKey = entityConfig?.revisionKey || "id";
    const revisions = await registry.resolveSelect(import_core_data56.store).getRevisions("postType", postType2, postId2, {
      per_page: -1,
      context: "edit",
      orderby: "date",
      order: "desc",
      _fields: revisionKey
    });
    if (select9.getCurrentRevisionId() !== revisionId2) {
      return;
    }
    if (!revisions) {
      createRevisionsLoadFailedNotice(registry);
      return;
    }
    const index2 = revisions.findIndex(
      (revision) => revision[revisionKey] === revisionId2
    );
    if (index2 === -1) {
      let revision;
      try {
        revision = await (0, import_api_fetch7.default)({
          path: (0, import_url14.addQueryArgs)(
            entityConfig.getRevisionsUrl(postId2, revisionId2),
            { context: "edit" }
          )
        });
      } catch (error2) {
        if (select9.getCurrentRevisionId() !== revisionId2) {
          return;
        }
        if (error2?.data?.status !== 404) {
          createRevisionsLoadFailedNotice(registry);
          return;
        }
        dispatch8.setCurrentRevisionId(null);
        registry.dispatch(import_notices19.store).createNotice("warning", (0, import_i18n204.__)("Invalid revision ID."), {
          type: "snackbar",
          id: "editor-revision-invalid"
        });
        return;
      }
      if (select9.getCurrentRevisionId() !== revisionId2) {
        return;
      }
      if (!revision) {
        createRevisionsLoadFailedNotice(registry);
        return;
      }
      await registry.dispatch(import_core_data56.store).receiveRevisions("postType", postType2, postId2, revision, {
        context: "edit"
      });
      return;
    }
    const page = Math.floor(index2 / select9.getRevisionsPerPage()) + 1;
    if (page !== select9.getRevisionPage()) {
      dispatch8({ type: "SET_REVISION_PAGE", page });
    }
  };
  function setShowRevisionDiff(showDiff) {
    return {
      type: "SET_SHOW_REVISION_DIFF",
      showDiff
    };
  }
  var restoreRevision = (revisionId2) => async ({ select: select9, dispatch: dispatch8, registry }) => {
    const postType2 = select9.getCurrentPostType();
    const postId2 = select9.getCurrentPostId();
    const entityConfig = registry.select(import_core_data56.store).getEntityConfig("postType", postType2);
    const revisionKey = entityConfig?.revisionKey || "id";
    const revision = await registry.resolveSelect(import_core_data56.store).getRevision("postType", postType2, postId2, revisionId2, {
      context: "edit",
      _fields: [
        .../* @__PURE__ */ new Set([
          "id",
          "date",
          "modified",
          "author",
          "meta",
          "title.raw",
          "excerpt.raw",
          "content.raw",
          revisionKey
        ])
      ].join()
    });
    if (!revision) {
      return;
    }
    const edits = {
      blocks: void 0,
      content: revision.content.raw
    };
    if (revision.title?.raw !== void 0) {
      edits.title = revision.title.raw;
    }
    if (revision.excerpt?.raw !== void 0) {
      edits.excerpt = revision.excerpt.raw;
    }
    if (revision.meta !== void 0) {
      edits.meta = revision.meta;
    }
    dispatch8.editPost(edits);
    dispatch8.setCurrentRevisionId(null);
    await dispatch8.savePost();
    if (select9.didPostSaveRequestFail()) {
      return;
    }
    registry.dispatch(import_notices19.store).removeNotice("autosave-exists");
    registry.dispatch(import_notices19.store).createSuccessNotice(
      (0, import_i18n204.sprintf)(
        /* translators: %s: Date and time of the revision. */
        (0, import_i18n204.__)("Restored to revision from %s."),
        (0, import_date16.dateI18n)((0, import_date16.getSettings)().formats.datetime, revision.date)
      ),
      {
        type: "snackbar",
        id: "editor-revision-restored"
      }
    );
  };
  function selectNote(noteId, options = { focus: false }) {
    return {
      type: "SELECT_NOTE",
      noteId,
      options
    };
  }

  // packages/editor/build-module/store/actions.mjs
  var setupEditor = (post2, edits, template2) => ({ dispatch: dispatch8 }) => {
    dispatch8.setEditedPost(post2.type, post2.id);
    const isNewPost = post2.status === "auto-draft";
    if (isNewPost && template2) {
      let content;
      if ("content" in edits) {
        content = edits.content;
      } else {
        content = post2.content.raw;
      }
      let blocks = (0, import_blocks20.parse)(content);
      blocks = (0, import_blocks20.synchronizeBlocksWithTemplate)(blocks, template2);
      dispatch8.resetEditorBlocks(blocks, {
        __unstableShouldCreateUndoLevel: false
      });
    }
    if (edits && Object.entries(edits).some(
      ([key, edit]) => edit !== (post2[key]?.raw ?? post2[key])
    )) {
      dispatch8.editPost(edits);
    }
  };
  function __experimentalTearDownEditor() {
    (0, import_deprecated9.default)(
      "wp.data.dispatch( 'core/editor' ).__experimentalTearDownEditor",
      {
        since: "6.5"
      }
    );
    return { type: "DO_NOTHING" };
  }
  function resetPost() {
    (0, import_deprecated9.default)("wp.data.dispatch( 'core/editor' ).resetPost", {
      since: "6.0",
      version: "6.3",
      alternative: "Initialize the editor with the setupEditorState action"
    });
    return { type: "DO_NOTHING" };
  }
  function updatePost() {
    (0, import_deprecated9.default)("wp.data.dispatch( 'core/editor' ).updatePost", {
      since: "5.7",
      alternative: "Use the core entities store instead"
    });
    return {
      type: "DO_NOTHING"
    };
  }
  function setupEditorState(post2) {
    (0, import_deprecated9.default)("wp.data.dispatch( 'core/editor' ).setupEditorState", {
      since: "6.5",
      alternative: "wp.data.dispatch( 'core/editor' ).setEditedPost"
    });
    return setEditedPost(post2.type, post2.id);
  }
  function setEditedPost(postType2, postId2) {
    return {
      type: "SET_EDITED_POST",
      postType: postType2,
      postId: postId2
    };
  }
  var editPost = (edits, options) => ({ select: select9, registry }) => {
    const { id, type } = select9.getCurrentPost();
    registry.dispatch(import_core_data57.store).editEntityRecord("postType", type, id, edits, options);
  };
  var savePost = (options = {}) => async ({ select: select9, dispatch: dispatch8, registry }) => {
    if (!select9.isEditedPostSaveable()) {
      return;
    }
    const content = select9.getEditedPostContent();
    dispatch8.editPost({ content }, { undoIgnore: true });
    const previousRecord = select9.getCurrentPost();
    let edits = {
      id: previousRecord.id,
      ...registry.select(import_core_data57.store).getEntityRecordNonTransientEdits(
        "postType",
        previousRecord.type,
        previousRecord.id
      ),
      content
    };
    dispatch8({ type: "REQUEST_POST_UPDATE_START", options });
    let error2 = false;
    try {
      edits = await (0, import_hooks39.applyFiltersAsync)(
        "editor.preSavePost",
        edits,
        options
      );
    } catch (err) {
      error2 = err;
    }
    if (!error2) {
      try {
        await registry.dispatch(import_core_data57.store).saveEntityRecord(
          "postType",
          previousRecord.type,
          edits,
          options
        );
      } catch (err) {
        error2 = err.message && err.code !== "unknown_error" ? err.message : (0, import_i18n205.__)("An error occurred while updating.");
      }
    }
    if (!error2) {
      error2 = registry.select(import_core_data57.store).getLastEntitySaveError(
        "postType",
        previousRecord.type,
        previousRecord.id
      );
    }
    if (!error2) {
      try {
        await (0, import_hooks39.applyFilters)(
          "editor.__unstableSavePost",
          Promise.resolve(),
          options
        );
      } catch (err) {
        error2 = err;
      }
    }
    if (!error2) {
      try {
        await (0, import_hooks39.doActionAsync)(
          "editor.savePost",
          { id: previousRecord.id, type: previousRecord.type },
          options
        );
      } catch (err) {
        error2 = err;
      }
    }
    dispatch8({ type: "REQUEST_POST_UPDATE_FINISH", options });
    if (typeof window !== "undefined" && window.__experimentalTemplateActivate && !options.isAutosave && previousRecord.type === "wp_template" && (typeof previousRecord.id === "number" || /^\d+$/.test(previousRecord.id))) {
      templateActivationNotice({ select: select9, dispatch: dispatch8, registry });
    }
    if (error2) {
      const args = getNotificationArgumentsForSaveFail({
        post: previousRecord,
        edits,
        error: error2
      });
      if (args.length) {
        registry.dispatch(import_notices20.store).createErrorNotice(...args);
      }
    } else {
      const updatedRecord = select9.getCurrentPost();
      const args = getNotificationArgumentsForSaveSuccess({
        previousPost: previousRecord,
        post: updatedRecord,
        postType: await registry.resolveSelect(import_core_data57.store).getPostType(updatedRecord.type),
        options
      });
      if (args.length) {
        registry.dispatch(import_notices20.store).createSuccessNotice(...args);
      }
      if (!options.isAutosave) {
        registry.dispatch(import_block_editor36.store).__unstableMarkLastChangeAsPersistent();
      }
    }
  };
  async function templateActivationNotice({ select: select9, registry }) {
    const editorSettings2 = select9.getEditorSettings();
    if (editorSettings2.onNavigateToPreviousEntityRecord) {
      return;
    }
    const { id, slug } = select9.getCurrentPost();
    const site = await registry.select(import_core_data57.store).getEntityRecord("root", "site");
    if (site.active_templates[slug] === id) {
      return;
    }
    const currentTheme = await registry.resolveSelect(import_core_data57.store).getCurrentTheme();
    const templateType = currentTheme?.default_template_types.find(
      (type) => type.slug === slug
    );
    await registry.dispatch(import_notices20.store).createNotice(
      "info",
      (0, import_i18n205.sprintf)(
        // translators: %s: The name (or slug) of the type of template.
        (0, import_i18n205.__)('Do you want to activate this "%s" template?'),
        templateType?.title ?? slug
      ),
      {
        id: "template-activate-notice",
        actions: [
          {
            label: (0, import_i18n205.__)("Activate"),
            onClick: async () => {
              await registry.dispatch(import_notices20.store).createNotice(
                "info",
                (0, import_i18n205.__)("Activating template\u2026"),
                { id: "template-activate-notice" }
              );
              try {
                const currentSite = await registry.select(import_core_data57.store).getEntityRecord("root", "site");
                await registry.dispatch(import_core_data57.store).saveEntityRecord(
                  "root",
                  "site",
                  {
                    active_templates: {
                      ...currentSite.active_templates,
                      [slug]: id
                    }
                  },
                  { throwOnError: true }
                );
                await registry.dispatch(import_notices20.store).createSuccessNotice(
                  (0, import_i18n205.__)("Template activated."),
                  { id: "template-activate-notice" }
                );
              } catch (error2) {
                await registry.dispatch(import_notices20.store).createErrorNotice(
                  (0, import_i18n205.__)("Template activation failed."),
                  { id: "template-activate-notice" }
                );
                throw error2;
              }
            }
          }
        ]
      }
    );
  }
  function refreshPost() {
    (0, import_deprecated9.default)("wp.data.dispatch( 'core/editor' ).refreshPost", {
      since: "6.0",
      version: "6.3",
      alternative: "Use the core entities store instead"
    });
    return { type: "DO_NOTHING" };
  }
  var trashPost2 = () => async ({ select: select9, dispatch: dispatch8, registry }) => {
    const postTypeSlug = select9.getCurrentPostType();
    const postType2 = await registry.resolveSelect(import_core_data57.store).getPostType(postTypeSlug);
    const { rest_base: restBase, rest_namespace: restNamespace = "wp/v2" } = postType2;
    dispatch8({ type: "REQUEST_POST_DELETE_START" });
    try {
      const post2 = select9.getCurrentPost();
      await (0, import_api_fetch8.default)({
        path: `/${restNamespace}/${restBase}/${post2.id}`,
        method: "DELETE"
      });
      await dispatch8.savePost();
    } catch (error2) {
      registry.dispatch(import_notices20.store).createErrorNotice(
        ...getNotificationArgumentsForTrashFail({ error: error2 })
      );
    }
    dispatch8({ type: "REQUEST_POST_DELETE_FINISH" });
  };
  var autosave = ({ local = false, ...options } = {}) => async ({ select: select9, dispatch: dispatch8 }) => {
    const post2 = select9.getCurrentPost();
    if (local) {
      const isPostNew = select9.isEditedPostNew();
      const title = select9.getEditedPostAttribute("title");
      const content = select9.getEditedPostAttribute("content");
      const excerpt = select9.getEditedPostAttribute("excerpt");
      localAutosaveSet(post2.id, isPostNew, title, content, excerpt);
    } else {
      await dispatch8.savePost({ isAutosave: true, ...options });
    }
  };
  var __unstableSaveForPreview = ({ forceIsAutosaveable } = {}) => async ({ select: select9, dispatch: dispatch8 }) => {
    if ((forceIsAutosaveable || select9.isEditedPostAutosaveable()) && !select9.isPostLocked()) {
      const isDraft = ["draft", "auto-draft"].includes(
        select9.getEditedPostAttribute("status")
      );
      if (isDraft) {
        await dispatch8.savePost({ isPreview: true });
      } else {
        await dispatch8.autosave({ isPreview: true });
      }
    }
    return select9.getEditedPostPreviewLink();
  };
  var redo = () => ({ registry }) => {
    registry.dispatch(import_core_data57.store).redo();
  };
  var undo = () => ({ registry }) => {
    registry.dispatch(import_core_data57.store).undo();
  };
  function createUndoLevel() {
    (0, import_deprecated9.default)("wp.data.dispatch( 'core/editor' ).createUndoLevel", {
      since: "6.0",
      version: "6.3",
      alternative: "Use the core entities store instead"
    });
    return { type: "DO_NOTHING" };
  }
  function updatePostLock(lock9) {
    return {
      type: "UPDATE_POST_LOCK",
      lock: lock9
    };
  }
  var enablePublishSidebar = () => ({ registry }) => {
    registry.dispatch(import_preferences10.store).set("core", "isPublishSidebarEnabled", true);
  };
  var disablePublishSidebar = () => ({ registry }) => {
    registry.dispatch(import_preferences10.store).set("core", "isPublishSidebarEnabled", false);
  };
  function lockPostSaving(lockName) {
    return {
      type: "LOCK_POST_SAVING",
      lockName
    };
  }
  function unlockPostSaving(lockName) {
    return {
      type: "UNLOCK_POST_SAVING",
      lockName
    };
  }
  function lockPostAutosaving(lockName) {
    return {
      type: "LOCK_POST_AUTOSAVING",
      lockName
    };
  }
  function unlockPostAutosaving(lockName) {
    return {
      type: "UNLOCK_POST_AUTOSAVING",
      lockName
    };
  }
  var resetEditorBlocks = (blocks, options = {}) => ({ select: select9, dispatch: dispatch8, registry }) => {
    const { __unstableShouldCreateUndoLevel, selection } = options;
    const edits = { blocks, selection };
    if (__unstableShouldCreateUndoLevel !== false) {
      const { id, type } = select9.getCurrentPost();
      const noChange = registry.select(import_core_data57.store).getEditedEntityRecord("postType", type, id).blocks === edits.blocks;
      if (noChange) {
        registry.dispatch(import_core_data57.store).__unstableCreateUndoLevel("postType", type, id);
        return;
      }
      edits.content = ({ blocks: blocksForSerialization = [] }) => (0, import_blocks20.__unstableSerializeAndClean)(blocksForSerialization);
    }
    dispatch8.editPost(edits);
  };
  function updateEditorSettings(settings) {
    return {
      type: "UPDATE_EDITOR_SETTINGS",
      settings
    };
  }
  var setRenderingMode = (mode) => ({ dispatch: dispatch8, registry, select: select9 }) => {
    if (select9.__unstableIsEditorReady() && !select9.getEditorSettings().isPreviewMode) {
      registry.dispatch(import_block_editor36.store).clearSelectedBlock();
    }
    dispatch8({
      type: "SET_RENDERING_MODE",
      mode
    });
  };
  function setDeviceType(deviceType) {
    return ({ dispatch: dispatch8, registry }) => {
      const viewportSettings = unlock(
        registry.select(import_block_editor36.store)
      ).getSettings().__experimentalFeatures?.viewport;
      const width = getCanvasWidthByDeviceType(
        deviceType,
        viewportSettings
      );
      dispatch8(setCanvasWidth(width));
    };
  }
  var toggleEditorPanelEnabled = (panelName) => ({ registry }) => {
    const inactivePanels = registry.select(import_preferences10.store).get("core", "inactivePanels") ?? [];
    const isPanelInactive = !!inactivePanels?.includes(panelName);
    let updatedInactivePanels;
    if (isPanelInactive) {
      updatedInactivePanels = inactivePanels.filter(
        (invactivePanelName) => invactivePanelName !== panelName
      );
    } else {
      updatedInactivePanels = [...inactivePanels, panelName];
    }
    registry.dispatch(import_preferences10.store).set("core", "inactivePanels", updatedInactivePanels);
  };
  var toggleEditorPanelOpened = (panelName) => ({ registry }) => {
    const openPanels = registry.select(import_preferences10.store).get("core", "openPanels") ?? [];
    const isPanelOpen = !!openPanels?.includes(panelName);
    let updatedOpenPanels;
    if (isPanelOpen) {
      updatedOpenPanels = openPanels.filter(
        (openPanelName) => openPanelName !== panelName
      );
    } else {
      updatedOpenPanels = [...openPanels, panelName];
    }
    registry.dispatch(import_preferences10.store).set("core", "openPanels", updatedOpenPanels);
  };
  function removeEditorPanel(panelName) {
    return {
      type: "REMOVE_PANEL",
      panelName
    };
  }
  var setIsInserterOpened = (value) => ({ dispatch: dispatch8, registry }) => {
    if (typeof value === "object" && value.hasOwnProperty("rootClientId") && value.hasOwnProperty("insertionIndex")) {
      unlock(registry.dispatch(import_block_editor36.store)).setInsertionPoint({
        rootClientId: value.rootClientId,
        index: value.insertionIndex
      });
    }
    dispatch8({
      type: "SET_IS_INSERTER_OPENED",
      value
    });
  };
  function setIsListViewOpened(isOpen2) {
    return {
      type: "SET_IS_LIST_VIEW_OPENED",
      isOpen: isOpen2
    };
  }
  var toggleDistractionFree = ({ createNotice = true } = {}) => ({ dispatch: dispatch8, registry }) => {
    const isDistractionFree = registry.select(import_preferences10.store).get("core", "distractionFree");
    if (isDistractionFree) {
      registry.dispatch(import_preferences10.store).set("core", "fixedToolbar", false);
    }
    if (!isDistractionFree) {
      registry.batch(() => {
        registry.dispatch(import_preferences10.store).set("core", "fixedToolbar", true);
        dispatch8.setIsInserterOpened(false);
        dispatch8.setIsListViewOpened(false);
        unlock(
          registry.dispatch(import_block_editor36.store)
        ).resetZoomLevel();
      });
    }
    registry.batch(() => {
      registry.dispatch(import_preferences10.store).set("core", "distractionFree", !isDistractionFree);
      if (createNotice) {
        registry.dispatch(import_notices20.store).createInfoNotice(
          isDistractionFree ? (0, import_i18n205.__)("Distraction free mode deactivated.") : (0, import_i18n205.__)("Distraction free mode activated."),
          {
            id: "core/editor/distraction-free-mode/notice",
            type: "snackbar",
            actions: [
              {
                label: (0, import_i18n205.__)("Undo"),
                onClick: () => {
                  registry.batch(() => {
                    registry.dispatch(import_preferences10.store).set(
                      "core",
                      "fixedToolbar",
                      isDistractionFree
                    );
                    registry.dispatch(import_preferences10.store).toggle(
                      "core",
                      "distractionFree"
                    );
                  });
                }
              }
            ]
          }
        );
      }
    });
  };
  var toggleSpotlightMode = () => ({ registry }) => {
    registry.dispatch(import_preferences10.store).toggle("core", "focusMode");
    const isFocusMode = registry.select(import_preferences10.store).get("core", "focusMode");
    registry.dispatch(import_notices20.store).createInfoNotice(
      isFocusMode ? (0, import_i18n205.__)("Spotlight mode activated.") : (0, import_i18n205.__)("Spotlight mode deactivated."),
      {
        id: "core/editor/toggle-spotlight-mode/notice",
        type: "snackbar",
        actions: [
          {
            label: (0, import_i18n205.__)("Undo"),
            onClick: () => {
              registry.dispatch(import_preferences10.store).toggle("core", "focusMode");
            }
          }
        ]
      }
    );
  };
  var toggleTopToolbar = () => ({ registry }) => {
    registry.dispatch(import_preferences10.store).toggle("core", "fixedToolbar");
    const isTopToolbar = registry.select(import_preferences10.store).get("core", "fixedToolbar");
    registry.dispatch(import_notices20.store).createInfoNotice(
      isTopToolbar ? (0, import_i18n205.__)("Top toolbar activated.") : (0, import_i18n205.__)("Top toolbar deactivated."),
      {
        id: "core/editor/toggle-top-toolbar/notice",
        type: "snackbar",
        actions: [
          {
            label: (0, import_i18n205.__)("Undo"),
            onClick: () => {
              registry.dispatch(import_preferences10.store).toggle("core", "fixedToolbar");
            }
          }
        ]
      }
    );
  };
  var switchEditorMode = (mode) => ({ dispatch: dispatch8, registry }) => {
    registry.dispatch(import_preferences10.store).set("core", "editorMode", mode);
    if (mode !== "visual") {
      registry.dispatch(import_block_editor36.store).clearSelectedBlock();
      unlock(registry.dispatch(import_block_editor36.store)).resetZoomLevel();
    }
    if (mode === "visual") {
      (0, import_a11y7.speak)((0, import_i18n205.__)("Visual editor selected"), "assertive");
    } else if (mode === "text") {
      const isDistractionFree = registry.select(import_preferences10.store).get("core", "distractionFree");
      if (isDistractionFree) {
        dispatch8.toggleDistractionFree();
      }
      (0, import_a11y7.speak)((0, import_i18n205.__)("Code editor selected"), "assertive");
    }
  };
  function openPublishSidebar() {
    return {
      type: "OPEN_PUBLISH_SIDEBAR"
    };
  }
  function closePublishSidebar() {
    return {
      type: "CLOSE_PUBLISH_SIDEBAR"
    };
  }
  function togglePublishSidebar() {
    return {
      type: "TOGGLE_PUBLISH_SIDEBAR"
    };
  }
  var getBlockEditorAction = (name2) => (...args) => ({ registry }) => {
    (0, import_deprecated9.default)("`wp.data.dispatch( 'core/editor' )." + name2 + "`", {
      since: "5.3",
      alternative: "`wp.data.dispatch( 'core/block-editor' )." + name2 + "`",
      version: "6.2"
    });
    registry.dispatch(import_block_editor36.store)[name2](...args);
  };
  var resetBlocks = getBlockEditorAction("resetBlocks");
  var receiveBlocks = getBlockEditorAction("receiveBlocks");
  var updateBlock = getBlockEditorAction("updateBlock");
  var updateBlockAttributes = getBlockEditorAction(
    "updateBlockAttributes"
  );
  var selectBlock = getBlockEditorAction("selectBlock");
  var startMultiSelect = getBlockEditorAction("startMultiSelect");
  var stopMultiSelect = getBlockEditorAction("stopMultiSelect");
  var multiSelect = getBlockEditorAction("multiSelect");
  var clearSelectedBlock = getBlockEditorAction("clearSelectedBlock");
  var toggleSelection = getBlockEditorAction("toggleSelection");
  var replaceBlocks = getBlockEditorAction("replaceBlocks");
  var replaceBlock = getBlockEditorAction("replaceBlock");
  var moveBlocksDown = getBlockEditorAction("moveBlocksDown");
  var moveBlocksUp = getBlockEditorAction("moveBlocksUp");
  var moveBlockToPosition = getBlockEditorAction(
    "moveBlockToPosition"
  );
  var insertBlock = getBlockEditorAction("insertBlock");
  var insertBlocks = getBlockEditorAction("insertBlocks");
  var showInsertionPoint = getBlockEditorAction("showInsertionPoint");
  var hideInsertionPoint = getBlockEditorAction("hideInsertionPoint");
  var setTemplateValidity = getBlockEditorAction(
    "setTemplateValidity"
  );
  var synchronizeTemplate = getBlockEditorAction(
    "synchronizeTemplate"
  );
  var mergeBlocks = getBlockEditorAction("mergeBlocks");
  var removeBlocks = getBlockEditorAction("removeBlocks");
  var removeBlock = getBlockEditorAction("removeBlock");
  var toggleBlockMode = getBlockEditorAction("toggleBlockMode");
  var startTyping = getBlockEditorAction("startTyping");
  var stopTyping = getBlockEditorAction("stopTyping");
  var enterFormattedText = getBlockEditorAction("enterFormattedText");
  var exitFormattedText = getBlockEditorAction("exitFormattedText");
  var insertDefaultBlock = getBlockEditorAction("insertDefaultBlock");
  var updateBlockListSettings = getBlockEditorAction(
    "updateBlockListSettings"
  );

  // packages/editor/build-module/store/index.mjs
  var storeConfig = {
    reducer: reducer_default2,
    selectors: selectors_exports,
    actions: actions_exports3
  };
  var store = (0, import_data87.createReduxStore)(STORE_NAME, {
    ...storeConfig
  });
  (0, import_data87.register)(store);
  unlock(store).registerPrivateActions(private_actions_exports);
  unlock(store).registerPrivateSelectors(private_selectors_exports);

  // packages/editor/build-module/hooks/custom-sources-backwards-compatibility.mjs
  var import_jsx_runtime374 = __toESM(require_jsx_runtime(), 1);
  var createWithMetaAttributeSource = (metaAttributes) => (0, import_compose35.createHigherOrderComponent)(
    (BlockEdit2) => ({ attributes, setAttributes, ...props }) => {
      const postType2 = (0, import_data88.useSelect)(
        (select9) => select9(store).getCurrentPostType(),
        []
      );
      const [meta2, setMeta] = (0, import_core_data58.useEntityProp)(
        "postType",
        postType2,
        "meta"
      );
      const mergedAttributes = (0, import_element218.useMemo)(
        () => ({
          ...attributes,
          ...Object.fromEntries(
            Object.entries(metaAttributes).map(
              ([attributeKey, metaKey]) => [
                attributeKey,
                meta2[metaKey]
              ]
            )
          )
        }),
        [attributes, meta2]
      );
      return /* @__PURE__ */ (0, import_jsx_runtime374.jsx)(
        BlockEdit2,
        {
          attributes: mergedAttributes,
          setAttributes: (nextAttributes) => {
            const nextMeta = Object.fromEntries(
              Object.entries(nextAttributes ?? {}).filter(
                // Filter to intersection of keys between the updated
                // attributes and those with an associated meta key.
                ([key]) => key in metaAttributes
              ).map(([attributeKey, value]) => [
                // Rename the keys to the expected meta key name.
                metaAttributes[attributeKey],
                value
              ])
            );
            if (Object.entries(nextMeta).length) {
              setMeta(nextMeta);
            }
            setAttributes(nextAttributes);
          },
          ...props
        }
      );
    },
    "withMetaAttributeSource"
  );
  function shimAttributeSource(settings) {
    const metaAttributes = Object.fromEntries(
      Object.entries(settings.attributes ?? {}).filter(([, { source }]) => source === "meta").map(([attributeKey, { meta: meta2 }]) => [attributeKey, meta2])
    );
    if (Object.entries(metaAttributes).length) {
      settings.edit = createWithMetaAttributeSource(metaAttributes)(
        settings.edit
      );
    }
    return settings;
  }
  (0, import_hooks40.addFilter)(
    "blocks.registerBlockType",
    "core/editor/custom-sources-backwards-compatibility/shim-attribute-source",
    shimAttributeSource
  );

  // packages/editor/build-module/hooks/default-autocompleters.mjs
  var import_hooks52 = __toESM(require_hooks(), 1);

  // packages/editor/build-module/components/autocompleters/link.mjs
  var import_api_fetch9 = __toESM(require_api_fetch(), 1);
  var import_url15 = __toESM(require_url(), 1);
  var import_html_entities14 = __toESM(require_html_entities(), 1);
  var import_jsx_runtime375 = __toESM(require_jsx_runtime(), 1);
  var SHOWN_SUGGESTIONS = 10;
  var link_default2 = {
    name: "links",
    className: "editor-autocompleters__link",
    triggerPrefix: "[[",
    isDebounced: true,
    async options(filterValue) {
      const options = await (0, import_api_fetch9.default)({
        path: (0, import_url15.addQueryArgs)("/wp/v2/search", {
          per_page: SHOWN_SUGGESTIONS,
          search: filterValue,
          type: "post"
        })
      });
      return options.filter((option) => option.title !== "");
    },
    getOptionKeywords(item) {
      const expansionWords = item.title.split(/\s+/);
      return [...expansionWords];
    },
    getOptionLabel(item) {
      return /* @__PURE__ */ (0, import_jsx_runtime375.jsxs)(import_jsx_runtime375.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime375.jsx)(icon_default, { icon: item.subtype === "page" ? page_default : post_default }),
        (0, import_html_entities14.decodeEntities)(item.title)
      ] });
    },
    getOptionCompletion(item) {
      return /* @__PURE__ */ (0, import_jsx_runtime375.jsx)("a", { href: item.url, children: item.title });
    }
  };

  // packages/editor/build-module/components/autocompleters/user.mjs
  var import_element219 = __toESM(require_element(), 1);
  var import_data89 = __toESM(require_data(), 1);
  var import_core_data59 = __toESM(require_core_data(), 1);
  var import_jsx_runtime376 = __toESM(require_jsx_runtime(), 1);
  function getUserLabel(user) {
    const avatar = user.avatar_urls && user.avatar_urls[24] ? /* @__PURE__ */ (0, import_jsx_runtime376.jsx)(
      "img",
      {
        className: "editor-autocompleters__user-avatar",
        alt: "",
        src: user.avatar_urls[24]
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime376.jsx)("span", { className: "editor-autocompleters__no-avatar" });
    return /* @__PURE__ */ (0, import_jsx_runtime376.jsxs)(import_jsx_runtime376.Fragment, { children: [
      avatar,
      /* @__PURE__ */ (0, import_jsx_runtime376.jsx)("span", { className: "editor-autocompleters__user-name", children: user.name }),
      /* @__PURE__ */ (0, import_jsx_runtime376.jsx)("span", { className: "editor-autocompleters__user-slug", children: user.slug })
    ] });
  }
  var user_default = {
    name: "users",
    className: "editor-autocompleters__user",
    triggerPrefix: "@",
    useItems(filterValue) {
      const users = (0, import_data89.useSelect)(
        (select9) => {
          const { getUsers } = select9(import_core_data59.store);
          return getUsers({
            context: "view",
            search: filterValue
          });
        },
        [filterValue]
      );
      const options = (0, import_element219.useMemo)(
        () => users ? users.map((user) => ({
          key: `user-${user.slug}`,
          value: user,
          label: getUserLabel(user)
        })) : [],
        [users]
      );
      return [options];
    },
    getOptionCompletion(user) {
      return `@${user.slug}`;
    }
  };

  // packages/editor/build-module/components/autosave-monitor/index.mjs
  var import_element220 = __toESM(require_element(), 1);
  var import_data90 = __toESM(require_data(), 1);
  var import_core_data60 = __toESM(require_core_data(), 1);
  function useInterval(callback, intervalInSeconds) {
    const callbackRef = (0, import_element220.useRef)(callback);
    (0, import_element220.useEffect)(() => {
      callbackRef.current = callback;
    }, [callback]);
    (0, import_element220.useEffect)(() => {
      if (!intervalInSeconds) {
        return;
      }
      const id = setInterval(
        () => callbackRef.current(),
        intervalInSeconds * 1e3
      );
      return () => clearInterval(id);
    }, [intervalInSeconds]);
  }
  function AutosaveMonitor({ interval, autosave: autosave2 }) {
    const { autosave: autosaveAction } = (0, import_data90.useDispatch)(store);
    const triggerAutosave = autosave2 ?? autosaveAction;
    const { getReferenceByDistinctEdits } = (0, import_data90.useSelect)(import_core_data60.store);
    const { isEditedPostDirty: isEditedPostDirty2, isEditedPostAutosaveable: isEditedPostAutosaveable2, isAutosavingPost: isAutosavingPost2 } = (0, import_data90.useSelect)(store);
    const autosaveInterval = (0, import_data90.useSelect)(
      (select9) => {
        if (interval !== void 0) {
          return interval;
        }
        return select9(store).getEditorSettings().autosaveInterval;
      },
      [interval]
    );
    const lastEditsReferenceRef = (0, import_element220.useRef)();
    useInterval(() => {
      if (!isEditedPostAutosaveable2()) {
        return;
      }
      const editsReference = getReferenceByDistinctEdits();
      const hasNewEdits = editsReference !== lastEditsReferenceRef.current;
      if (hasNewEdits && isEditedPostDirty2() && !isAutosavingPost2()) {
        lastEditsReferenceRef.current = editsReference;
        triggerAutosave();
      }
    }, autosaveInterval);
    return null;
  }

  // packages/editor/build-module/components/document-bar/index.mjs
  var import_i18n212 = __toESM(require_i18n(), 1);
  var import_data99 = __toESM(require_data(), 1);
  var import_components163 = __toESM(require_components(), 1);
  var import_block_editor41 = __toESM(require_block_editor(), 1);
  var import_core_data64 = __toESM(require_core_data(), 1);
  var import_commands3 = __toESM(require_commands(), 1);
  var import_element227 = __toESM(require_element(), 1);
  var import_compose38 = __toESM(require_compose(), 1);
  var import_html_entities16 = __toESM(require_html_entities(), 1);
  var import_dom23 = __toESM(require_dom(), 1);

  // packages/editor/build-module/utils/pageTypeBadge.mjs
  var import_i18n206 = __toESM(require_i18n(), 1);
  var import_data91 = __toESM(require_data(), 1);
  var import_core_data61 = __toESM(require_core_data(), 1);
  function usePageTypeBadge(postId2) {
    const { isFrontPage, isPostsPage } = (0, import_data91.useSelect)((select9) => {
      const { canUser, getEditedEntityRecord } = select9(import_core_data61.store);
      const siteSettings = canUser("read", {
        kind: "root",
        name: "site"
      }) ? getEditedEntityRecord("root", "site") : void 0;
      const _postId = parseInt(postId2, 10);
      return {
        isFrontPage: siteSettings?.page_on_front === _postId,
        isPostsPage: siteSettings?.page_for_posts === _postId
      };
    });
    if (isFrontPage) {
      return (0, import_i18n206.__)("Homepage");
    } else if (isPostsPage) {
      return (0, import_i18n206.__)("Posts Page");
    }
    return false;
  }

  // packages/editor/build-module/components/styles-canvas/index.mjs
  var import_components162 = __toESM(require_components(), 1);
  var import_keycodes10 = __toESM(require_keycodes(), 1);
  var import_i18n211 = __toESM(require_i18n(), 1);
  var import_data97 = __toESM(require_data(), 1);
  var import_compose37 = __toESM(require_compose(), 1);
  var import_preferences11 = __toESM(require_preferences(), 1);

  // packages/editor/build-module/components/styles-canvas/style-book.mjs
  var import_element224 = __toESM(require_element(), 1);

  // packages/editor/build-module/components/style-book/index.mjs
  var import_components158 = __toESM(require_components(), 1);
  var import_i18n209 = __toESM(require_i18n(), 1);
  var import_block_editor38 = __toESM(require_block_editor(), 1);
  var import_data94 = __toESM(require_data(), 1);
  var import_element223 = __toESM(require_element(), 1);
  var import_keycodes8 = __toESM(require_keycodes(), 1);
  var import_media_utils7 = __toESM(require_media_utils(), 1);
  var import_core_data62 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/style-book/constants.mjs
  var import_i18n207 = __toESM(require_i18n(), 1);
  var STYLE_BOOK_COLOR_GROUPS = [
    {
      slug: "theme-colors",
      title: (0, import_i18n207.__)("Theme Colors"),
      origin: "theme",
      type: "colors"
    },
    {
      slug: "theme-gradients",
      title: (0, import_i18n207.__)("Theme Gradients"),
      origin: "theme",
      type: "gradients"
    },
    {
      slug: "custom-colors",
      title: (0, import_i18n207.__)("Custom Colors"),
      origin: "custom",
      type: "colors"
    },
    {
      slug: "custom-gradients",
      title: (0, import_i18n207.__)("Custom Gradients"),
      origin: "custom",
      // User.
      type: "gradients"
    },
    {
      slug: "duotones",
      title: (0, import_i18n207.__)("Duotones"),
      origin: "theme",
      type: "duotones"
    },
    {
      slug: "default-colors",
      title: (0, import_i18n207.__)("Default Colors"),
      origin: "default",
      type: "colors"
    },
    {
      slug: "default-gradients",
      title: (0, import_i18n207.__)("Default Gradients"),
      origin: "default",
      type: "gradients"
    }
  ];
  var STYLE_BOOK_THEME_SUBCATEGORIES = [
    {
      slug: "site-identity",
      title: (0, import_i18n207.__)("Site Identity"),
      blocks: ["core/site-logo", "core/site-title", "core/site-tagline"]
    },
    {
      slug: "design",
      title: (0, import_i18n207.__)("Design"),
      blocks: ["core/navigation", "core/avatar", "core/post-time-to-read"],
      exclude: ["core/home-link", "core/navigation-link"]
    },
    {
      slug: "posts",
      title: (0, import_i18n207.__)("Posts"),
      blocks: [
        "core/post-title",
        "core/post-excerpt",
        "core/post-author",
        "core/post-author-name",
        "core/post-author-biography",
        "core/post-date",
        "core/post-terms",
        "core/term-description",
        "core/query-title",
        "core/query-no-results",
        "core/query-pagination",
        "core/query-numbers"
      ]
    },
    {
      slug: "comments",
      title: (0, import_i18n207.__)("Comments"),
      blocks: [
        "core/comments-title",
        "core/comments-pagination",
        "core/comments-pagination-numbers",
        "core/comments",
        "core/comments-author-name",
        "core/comment-content",
        "core/comment-date",
        "core/comment-edit-link",
        "core/comment-reply-link",
        "core/comment-template",
        "core/post-comments-count",
        "core/post-comments-link"
      ]
    }
  ];
  var STYLE_BOOK_CATEGORIES = [
    {
      slug: "overview",
      title: (0, import_i18n207.__)("Overview"),
      blocks: []
    },
    {
      slug: "text",
      title: (0, import_i18n207.__)("Text"),
      blocks: [
        "core/post-content",
        "core/home-link",
        "core/navigation-link"
      ]
    },
    {
      slug: "colors",
      title: (0, import_i18n207.__)("Colors"),
      blocks: []
    },
    {
      slug: "theme",
      title: (0, import_i18n207.__)("Theme"),
      subcategories: STYLE_BOOK_THEME_SUBCATEGORIES
    },
    {
      slug: "media",
      title: (0, import_i18n207.__)("Media"),
      blocks: ["core/post-featured-image"]
    },
    {
      slug: "widgets",
      title: (0, import_i18n207.__)("Widgets"),
      blocks: []
    },
    {
      slug: "embed",
      title: (0, import_i18n207.__)("Embeds"),
      include: []
    }
  ];
  var STYLE_BOOK_ALL_BLOCKS_SUBCATEGORIES = [
    ...STYLE_BOOK_THEME_SUBCATEGORIES,
    {
      slug: "media",
      title: (0, import_i18n207.__)("Media"),
      blocks: ["core/post-featured-image"]
    },
    {
      slug: "widgets",
      title: (0, import_i18n207.__)("Widgets"),
      blocks: []
    },
    {
      slug: "embed",
      title: (0, import_i18n207.__)("Embeds"),
      include: []
    }
  ];
  var STYLE_BOOK_PREVIEW_CATEGORIES = [
    {
      slug: "overview",
      title: (0, import_i18n207.__)("Overview"),
      blocks: []
    },
    {
      slug: "text",
      title: (0, import_i18n207.__)("Text"),
      blocks: [
        "core/post-content",
        "core/home-link",
        "core/navigation-link"
      ]
    },
    {
      slug: "colors",
      title: (0, import_i18n207.__)("Colors"),
      blocks: []
    },
    {
      slug: "blocks",
      title: (0, import_i18n207.__)("All Blocks"),
      blocks: [],
      subcategories: STYLE_BOOK_ALL_BLOCKS_SUBCATEGORIES
    }
  ];
  var ROOT_CONTAINER = `
	.is-root-container {
		display: flow-root;
	}
`;
  var STYLE_BOOK_IFRAME_STYLES = `
	body {
		position: relative;
		padding: 32px !important;
	}

	${ROOT_CONTAINER}

	.editor-style-book__examples {
		max-width: 1200px;
		margin: 0 auto;
	}

	.editor-style-book__example {
	    max-width: 900px;
		border-radius: 2px;
		cursor: var(--wpds-cursor-control, pointer);
		display: flex;
		flex-direction: column;
		gap: 40px;
		padding: 16px;
		width: 100%;
		box-sizing: border-box;
		scroll-margin-top: 32px;
		scroll-margin-bottom: 32px;
		margin: 0 auto 40px auto;
	}

	.editor-style-book__example.is-selected {
		box-shadow: 0 0 0 1px var(--wp-components-color-accent, var(--wp-admin-theme-color, #007cba));
	}

	.editor-style-book__example.is-disabled-example {
		pointer-events: none;
	}

	.editor-style-book__example:focus:not(:disabled) {
		box-shadow: 0 0 0 var(--wp-admin-border-width-focus) var(--wp-components-color-accent, var(--wp-admin-theme-color, #007cba));
		outline: 3px solid transparent;
	}

	.editor-style-book__duotone-example > div:first-child {
		display: flex;
		aspect-ratio: 16 / 9;
		grid-row: span 1;
		grid-column: span 2;
	}
	.editor-style-book__duotone-example img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}
	.editor-style-book__duotone-example > div:not(:first-child) {
		height: 20px;
		border: 1px solid color-mix( in srgb, currentColor 10%, transparent );
	}

	.editor-style-book__color-example {
		border: 1px solid color-mix( in srgb, currentColor 10%, transparent );
	}

	.editor-style-book__subcategory-title,
	.editor-style-book__example-title {
		font-family: -apple-system, system-ui, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
		font-size: 13px;
		font-weight: normal;
		line-height: normal;
		margin: 0;
		text-align: left;
		padding-top: 8px;
		border-top: 1px solid color-mix( in srgb, currentColor 10%, transparent );
		color: color-mix( in srgb, currentColor 60%, transparent );
	}

	.editor-style-book__subcategory-title {
		font-size: 16px;
		margin-bottom: 40px;
    	padding-bottom: 8px;
	}

	.editor-style-book__example-preview {
		width: 100%;
	}

	.editor-style-book__example-preview .block-editor-block-list__insertion-point,
	.editor-style-book__example-preview .block-list-appender {
		display: none;
	}
	:where(.is-root-container > .wp-block:first-child) {
		margin-top: 0;
	}
	:where(.is-root-container > .wp-block:last-child) {
		margin-bottom: 0;
	}
`;

  // packages/editor/build-module/components/style-book/categories.mjs
  var import_blocks21 = __toESM(require_blocks(), 1);
  function getExamplesByCategory(categoryDefinition, examples) {
    if (!categoryDefinition?.slug || !examples?.length) {
      return;
    }
    const categories = categoryDefinition?.subcategories ?? [];
    if (categories.length) {
      return categories.reduce(
        (acc, subcategoryDefinition) => {
          const subcategoryExamples = getExamplesByCategory(
            subcategoryDefinition,
            examples
          );
          if (subcategoryExamples) {
            if (!acc.subcategories) {
              acc.subcategories = [];
            }
            acc.subcategories = [
              ...acc.subcategories,
              subcategoryExamples
            ];
          }
          return acc;
        },
        {
          title: categoryDefinition.title,
          slug: categoryDefinition.slug
        }
      );
    }
    const blocksToInclude = categoryDefinition?.blocks || [];
    const blocksToExclude = categoryDefinition?.exclude || [];
    const categoryExamples = examples.filter((example) => {
      return !blocksToExclude.includes(example.name) && (example.category === categoryDefinition.slug || blocksToInclude.includes(example.name));
    });
    if (!categoryExamples.length) {
      return;
    }
    return {
      title: categoryDefinition.title,
      slug: categoryDefinition.slug,
      examples: categoryExamples
    };
  }
  function getTopLevelStyleBookCategories() {
    const reservedCategories = [
      ...STYLE_BOOK_THEME_SUBCATEGORIES,
      ...STYLE_BOOK_CATEGORIES
    ].map(({ slug }) => slug);
    const extraCategories = (0, import_blocks21.getCategories)();
    const extraCategoriesFiltered = extraCategories.filter(
      ({ slug }) => !reservedCategories.includes(slug)
    );
    return [...STYLE_BOOK_CATEGORIES, ...extraCategoriesFiltered];
  }

  // packages/editor/build-module/components/style-book/examples.mjs
  var import_i18n208 = __toESM(require_i18n(), 1);
  var import_blocks22 = __toESM(require_blocks(), 1);

  // packages/editor/build-module/components/style-book/color-examples.mjs
  var import_components156 = __toESM(require_components(), 1);
  var import_block_editor37 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime377 = __toESM(require_jsx_runtime(), 1);
  var ColorExamples = ({
    colors: colors2,
    type,
    templateColumns = "1fr 1fr",
    itemHeight = "52px"
  }) => {
    if (!colors2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime377.jsx)(import_components156.__experimentalGrid, { templateColumns, rowGap: 8, columnGap: 16, children: colors2.map((color) => {
      const className = type === "gradients" ? (0, import_block_editor37.__experimentalGetGradientClass)(color.slug) : (0, import_block_editor37.getColorClassName)("background-color", color.slug);
      const classes = clsx_default(
        "editor-style-book__color-example",
        className
      );
      return /* @__PURE__ */ (0, import_jsx_runtime377.jsx)(
        "div",
        {
          className: classes,
          style: { height: itemHeight }
        },
        color.slug
      );
    }) });
  };
  var color_examples_default = ColorExamples;

  // packages/editor/build-module/components/style-book/duotone-examples.mjs
  var import_components157 = __toESM(require_components(), 1);
  var import_jsx_runtime378 = __toESM(require_jsx_runtime(), 1);
  var DuotoneExamples = ({ duotones }) => {
    if (!duotones) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime378.jsx)(import_components157.__experimentalGrid, { columns: 2, rowGap: 16, columnGap: 16, children: duotones.map((duotone) => {
      return /* @__PURE__ */ (0, import_jsx_runtime378.jsxs)(
        import_components157.__experimentalGrid,
        {
          className: "editor-style-book__duotone-example",
          columns: 2,
          rowGap: 8,
          columnGap: 8,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime378.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime378.jsx)(
              "img",
              {
                alt: `Duotone example: ${duotone.slug}`,
                src: "https://s.w.org/images/core/5.3/MtBlanc1.jpg",
                style: {
                  filter: `url(#wp-duotone-${duotone.slug})`
                }
              }
            ) }),
            duotone.colors.map((color) => {
              return /* @__PURE__ */ (0, import_jsx_runtime378.jsx)(
                "div",
                {
                  className: "editor-style-book__color-example",
                  style: { backgroundColor: color }
                },
                color
              );
            })
          ]
        },
        duotone.slug
      );
    }) });
  };
  var duotone_examples_default = DuotoneExamples;

  // packages/editor/build-module/components/style-book/examples.mjs
  var import_jsx_runtime379 = __toESM(require_jsx_runtime(), 1);
  function getColorExamples(colors2) {
    if (!colors2) {
      return [];
    }
    const examples = [];
    STYLE_BOOK_COLOR_GROUPS.forEach((group) => {
      const palette = colors2[group.type];
      const paletteFiltered = Array.isArray(palette) ? palette.find(
        (origin) => origin.slug === group.origin
      ) : void 0;
      if (paletteFiltered?.[group.type]) {
        const example = {
          name: group.slug,
          title: group.title,
          category: "colors"
        };
        if (group.type === "duotones") {
          example.content = /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
            duotone_examples_default,
            {
              duotones: paletteFiltered[group.type]
            }
          );
          examples.push(example);
        } else {
          example.content = /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
            color_examples_default,
            {
              colors: paletteFiltered[group.type],
              type: group.type
            }
          );
          examples.push(example);
        }
      }
    });
    return examples;
  }
  function getOverviewBlockExamples(colors2) {
    const examples = [];
    const themePalette = Array.isArray(colors2?.colors) ? colors2.colors.find(
      (origin) => origin.slug === "theme"
    ) : void 0;
    if (themePalette) {
      const themeColorexample = {
        name: "theme-colors",
        title: (0, import_i18n208.__)("Colors"),
        category: "overview",
        content: /* @__PURE__ */ (0, import_jsx_runtime379.jsx)(
          color_examples_default,
          {
            colors: themePalette.colors,
            type: "colors",
            templateColumns: "repeat(auto-fill, minmax( 200px, 1fr ))",
            itemHeight: "32px"
          }
        )
      };
      examples.push(themeColorexample);
    }
    const typographyBlockExamples = [];
    if ((0, import_blocks22.getBlockType)("core/heading")) {
      const headingBlock = (0, import_blocks22.createBlock)("core/heading", {
        // translators: Typography example. Your local alphabet, numbers and some common special characters.
        content: (0, import_i18n208.__)(
          `AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789X{(\u2026)},.-<>?!*&:/A@HELFO\u2122\xA9`
        ),
        level: 1
      });
      typographyBlockExamples.push(headingBlock);
    }
    if ((0, import_blocks22.getBlockType)("core/paragraph")) {
      const firstParagraphBlock = (0, import_blocks22.createBlock)("core/paragraph", {
        content: (0, import_i18n208.__)(
          `A paragraph in a website refers to a distinct block of text that is used to present and organize information. It is a fundamental unit of content in web design and is typically composed of a group of related sentences or thoughts focused on a particular topic or idea. Paragraphs play a crucial role in improving the readability and user experience of a website. They break down the text into smaller, manageable chunks, allowing readers to scan the content more easily.`
        )
      });
      const secondParagraphBlock = (0, import_blocks22.createBlock)("core/paragraph", {
        content: (0, import_i18n208.__)(
          `Additionally, paragraphs help structure the flow of information and provide logical breaks between different concepts or pieces of information. In terms of formatting, paragraphs in websites are commonly denoted by a vertical gap or indentation between each block of text. This visual separation helps visually distinguish one paragraph from another, creating a clear and organized layout that guides the reader through the content smoothly.`
        )
      });
      if ((0, import_blocks22.getBlockType)("core/group")) {
        const groupBlock = (0, import_blocks22.createBlock)(
          "core/group",
          {
            layout: {
              type: "grid",
              columnCount: 2,
              minimumColumnWidth: "12rem"
            },
            style: {
              spacing: {
                blockGap: "1.5rem"
              }
            }
          },
          [firstParagraphBlock, secondParagraphBlock]
        );
        typographyBlockExamples.push(groupBlock);
      } else {
        typographyBlockExamples.push(firstParagraphBlock);
      }
    }
    if (!!typographyBlockExamples.length) {
      examples.push({
        name: "typography",
        title: (0, import_i18n208.__)("Typography"),
        category: "overview",
        blocks: typographyBlockExamples
      });
    }
    const otherBlockExamples = [
      "core/image",
      "core/separator",
      "core/buttons",
      "core/pullquote",
      "core/search"
    ];
    otherBlockExamples.forEach((blockName) => {
      const blockType = (0, import_blocks22.getBlockType)(blockName);
      if (blockType && blockType.example) {
        const blockExample = {
          name: blockName,
          title: blockType.title,
          category: "overview",
          /*
           * CSS generated from style attributes will take precedence over global styles CSS,
           * so remove the style attribute from the example to ensure the example
           * demonstrates changes to global styles.
           */
          blocks: (0, import_blocks22.getBlockFromExample)(blockName, {
            ...blockType.example,
            attributes: {
              ...blockType.example.attributes,
              style: void 0
            }
          })
        };
        examples.push(blockExample);
      }
    });
    return examples;
  }
  function getExamples(colors2) {
    const nonHeadingBlockExamples = (0, import_blocks22.getBlockTypes)().filter((blockType) => {
      const { name: name2, example, supports } = blockType;
      return name2 !== "core/heading" && !!example && supports?.inserter !== false;
    }).map((blockType) => ({
      name: blockType.name,
      title: blockType.title,
      category: blockType.category,
      /*
       * CSS generated from style attributes will take precedence over global styles CSS,
       * so remove the style attribute from the example to ensure the example
       * demonstrates changes to global styles.
       */
      blocks: (0, import_blocks22.getBlockFromExample)(blockType.name, {
        ...blockType.example,
        attributes: {
          ...blockType.example?.attributes,
          style: void 0
        }
      })
    }));
    const isHeadingBlockRegistered = !!(0, import_blocks22.getBlockType)("core/heading");
    if (!isHeadingBlockRegistered) {
      return nonHeadingBlockExamples;
    }
    const headingsExample = {
      name: "core/heading",
      title: (0, import_i18n208.__)("Headings"),
      category: "text",
      blocks: [1, 2, 3, 4, 5, 6].map((level) => {
        return (0, import_blocks22.createBlock)("core/heading", {
          content: (0, import_i18n208.sprintf)(
            // translators: %d: heading level e.g: "1", "2", "3"
            (0, import_i18n208.__)("Heading %d"),
            level
          ),
          level
        });
      })
    };
    const colorExamples = getColorExamples(colors2);
    const overviewBlockExamples = getOverviewBlockExamples(colors2);
    return [
      headingsExample,
      ...colorExamples,
      ...nonHeadingBlockExamples,
      ...overviewBlockExamples
    ];
  }

  // packages/editor/build-module/components/global-styles-renderer/index.mjs
  var import_element222 = __toESM(require_element(), 1);
  var import_data93 = __toESM(require_data(), 1);

  // packages/editor/build-module/hooks/use-global-styles-output.mjs
  var import_blocks23 = __toESM(require_blocks(), 1);
  var import_data92 = __toESM(require_data(), 1);
  var import_element221 = __toESM(require_element(), 1);
  function useGlobalStylesOutputWithConfig(mergedConfig = {}, disableRootPadding = false) {
    const blockGap = useSetting2("spacing.blockGap");
    const hasBlockGapSupport = blockGap !== null;
    const hasFallbackGapSupport = !hasBlockGapSupport;
    const { disableLayoutStyles, getBlockStyles } = (0, import_data92.useSelect)((select9) => {
      const { getEditorSettings: getEditorSettings2 } = select9(store);
      const { getBlockStyles: getBlockStylesSelector } = select9(import_blocks23.store);
      const settings = getEditorSettings2();
      return {
        disableLayoutStyles: !!settings?.disableLayoutStyles,
        getBlockStyles: getBlockStylesSelector
      };
    }, []);
    return (0, import_element221.useMemo)(() => {
      if (!mergedConfig?.styles || !mergedConfig?.settings) {
        return [[], {}];
      }
      const blockTypes = (0, import_blocks23.getBlockTypes)();
      return generateGlobalStyles(mergedConfig, blockTypes, {
        hasBlockGapSupport,
        hasFallbackGapSupport,
        disableLayoutStyles,
        disableRootPadding,
        getBlockStyles
      });
    }, [
      hasBlockGapSupport,
      hasFallbackGapSupport,
      mergedConfig,
      disableLayoutStyles,
      disableRootPadding,
      getBlockStyles
    ]);
  }
  function useGlobalStylesOutput(disableRootPadding = false) {
    const { merged: mergedConfig } = useGlobalStyles();
    return useGlobalStylesOutputWithConfig(mergedConfig, disableRootPadding);
  }

  // packages/editor/build-module/components/global-styles-renderer/index.mjs
  function useGlobalStylesRenderer(disableRootPadding) {
    const [styles, settings] = useGlobalStylesOutput(disableRootPadding);
    const { getEditorSettings: getEditorSettings2 } = (0, import_data93.useSelect)(store);
    const { updateEditorSettings: updateEditorSettings2 } = (0, import_data93.useDispatch)(store);
    (0, import_element222.useEffect)(() => {
      if (!styles || !settings) {
        return;
      }
      const currentStoreSettings = getEditorSettings2();
      const nonGlobalStyles = Object.values(
        currentStoreSettings.styles ?? []
      ).filter((style) => !style.isGlobalStyles);
      updateEditorSettings2({
        ...currentStoreSettings,
        styles: [...nonGlobalStyles, ...styles],
        __experimentalFeatures: settings
      });
    }, [styles, settings, updateEditorSettings2, getEditorSettings2]);
  }
  function GlobalStylesRenderer({ disableRootPadding }) {
    useGlobalStylesRenderer(disableRootPadding);
    return null;
  }

  // packages/editor/build-module/components/style-book/index.mjs
  var import_jsx_runtime380 = __toESM(require_jsx_runtime(), 1);
  var { ExperimentalBlockEditorProvider: ExperimentalBlockEditorProvider2 } = unlock(import_block_editor38.privateApis);
  function isObjectEmpty(object) {
    return !object || Object.keys(object).length === 0;
  }
  var scrollToSection = (anchorId, iframe) => {
    if (!anchorId || !iframe || !iframe?.contentDocument) {
      return;
    }
    const element = anchorId === "top" ? iframe.contentDocument.body : iframe.contentDocument.getElementById(anchorId);
    if (element) {
      element.scrollIntoView({
        behavior: "smooth"
      });
    }
  };
  var getStyleBookNavigationFromPath = (path) => {
    if (path && typeof path === "string") {
      if (path === "/" || path.startsWith("/typography") || path.startsWith("/colors") || path.startsWith("/blocks")) {
        return {
          top: true
        };
      }
    }
    return null;
  };
  function useMultiOriginPalettes() {
    const { colors: colors2, gradients } = (0, import_block_editor38.__experimentalUseMultipleOriginColorsAndGradients)();
    const [
      shouldDisplayDefaultDuotones,
      customDuotones,
      themeDuotones,
      defaultDuotones
    ] = (0, import_block_editor38.useSettings)(
      "color.defaultDuotone",
      "color.duotone.custom",
      "color.duotone.theme",
      "color.duotone.default"
    );
    const palettes = (0, import_element223.useMemo)(() => {
      const result = { colors: colors2, gradients, duotones: [] };
      if (themeDuotones && themeDuotones.length) {
        result.duotones.push({
          name: (0, import_i18n209._x)(
            "Theme",
            "Indicates these duotone filters come from the theme."
          ),
          slug: "theme",
          duotones: themeDuotones
        });
      }
      if (shouldDisplayDefaultDuotones && defaultDuotones && defaultDuotones.length) {
        result.duotones.push({
          name: (0, import_i18n209._x)(
            "Default",
            "Indicates these duotone filters come from WordPress."
          ),
          slug: "default",
          duotones: defaultDuotones
        });
      }
      if (customDuotones && customDuotones.length) {
        result.duotones.push({
          name: (0, import_i18n209._x)(
            "Custom",
            "Indicates these doutone filters are created by the user."
          ),
          slug: "custom",
          duotones: customDuotones
        });
      }
      return result;
    }, [
      colors2,
      gradients,
      customDuotones,
      themeDuotones,
      defaultDuotones,
      shouldDisplayDefaultDuotones
    ]);
    return palettes;
  }
  function getExamplesForSinglePageUse(examples) {
    const examplesForSinglePageUse = [];
    const overviewCategoryExamples = getExamplesByCategory(
      { slug: "overview" },
      examples
    );
    examplesForSinglePageUse.push(...overviewCategoryExamples.examples);
    const otherExamples = examples.filter((example) => {
      return example.category !== "overview" && !overviewCategoryExamples.examples.find(
        (overviewExample) => overviewExample.name === example.name
      );
    });
    examplesForSinglePageUse.push(...otherExamples);
    return examplesForSinglePageUse;
  }
  function applyBlockVariationsToExamples(examples, variation) {
    if (!variation) {
      return examples;
    }
    return examples.map((example) => {
      return {
        ...example,
        variation,
        blocks: Array.isArray(example.blocks) ? example.blocks.map((block) => ({
          ...block,
          attributes: {
            ...block.attributes,
            style: void 0,
            className: `is-style-${variation}`
          }
        })) : {
          ...example.blocks,
          attributes: {
            ...example.blocks.attributes,
            style: void 0,
            className: `is-style-${variation}`
          }
        }
      };
    });
  }
  function StyleBook({
    isSelected: isSelected2,
    onClick,
    onSelect,
    showTabs = true,
    userConfig = {},
    path = ""
  }, ref) {
    const textColor = useStyle2("color.text");
    const backgroundColor = useStyle2("color.background");
    const colors2 = useMultiOriginPalettes();
    const examples = (0, import_element223.useMemo)(() => getExamples(colors2), [colors2]);
    const tabs = (0, import_element223.useMemo)(
      () => getTopLevelStyleBookCategories().filter(
        (category) => examples.some(
          (example) => example.category === category.slug
        )
      ),
      [examples]
    );
    const examplesForSinglePageUse = getExamplesForSinglePageUse(examples);
    const { base: baseConfig } = useGlobalStyles();
    const goTo = getStyleBookNavigationFromPath(path);
    const mergedConfig = (0, import_element223.useMemo)(() => {
      if (!isObjectEmpty(userConfig) && !isObjectEmpty(baseConfig)) {
        return mergeGlobalStyles(baseConfig, userConfig);
      }
      return {};
    }, [baseConfig, userConfig]);
    const originalSettings = (0, import_data94.useSelect)(
      (select9) => select9(import_block_editor38.store).getSettings(),
      []
    );
    const [globalStyles] = useGlobalStylesOutputWithConfig(mergedConfig);
    const settings = (0, import_element223.useMemo)(
      () => ({
        ...originalSettings,
        styles: !isObjectEmpty(globalStyles) && !isObjectEmpty(userConfig) ? globalStyles : originalSettings.styles,
        isPreviewMode: true
      }),
      [globalStyles, originalSettings, userConfig]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
      "div",
      {
        ref,
        className: clsx_default("editor-style-book", {
          "is-button": !!onClick
        }),
        style: {
          color: textColor,
          background: backgroundColor
        },
        children: showTabs ? /* @__PURE__ */ (0, import_jsx_runtime380.jsxs)(
          tabs_exports.Root,
          {
            className: "editor-style-book__tabs",
            defaultValue: tabs[0]?.slug,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime380.jsx)("div", { className: "editor-style-book__tablist-container", children: /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(tabs_exports.List, { children: tabs.map((tab) => /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(tabs_exports.Tab, { value: tab.slug, children: tab.title }, tab.slug)) }) }),
              tabs.map((tab) => {
                const categoryDefinition = tab.slug ? getTopLevelStyleBookCategories().find(
                  (_category) => _category.slug === tab.slug
                ) : null;
                const filteredExamples = categoryDefinition ? getExamplesByCategory(
                  categoryDefinition,
                  examples
                ) : { examples };
                return /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
                  tabs_exports.Panel,
                  {
                    value: tab.slug,
                    tabIndex: -1,
                    className: "editor-style-book__tabpanel",
                    children: /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
                      StyleBookBody,
                      {
                        category: tab.slug,
                        examples: filteredExamples,
                        isSelected: isSelected2,
                        onSelect,
                        settings,
                        title: tab.title,
                        goTo
                      }
                    )
                  },
                  tab.slug
                );
              })
            ]
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
          StyleBookBody,
          {
            examples: { examples: examplesForSinglePageUse },
            isSelected: isSelected2,
            onClick,
            onSelect,
            settings,
            goTo
          }
        )
      }
    );
  }
  var StyleBookPreview = ({
    userConfig = {},
    isStatic = false,
    path,
    onPathChange,
    settings: settingsProp
  }) => {
    const editorSettings2 = (0, import_data94.useSelect)(
      (select9) => settingsProp ?? select9(store).getEditorSettings(),
      [settingsProp]
    );
    const canUserUploadMedia = (0, import_data94.useSelect)(
      (select9) => select9(import_core_data62.store).canUser("create", {
        kind: "postType",
        name: "attachment"
      }),
      []
    );
    (0, import_element223.useEffect)(() => {
      (0, import_data94.dispatch)(import_block_editor38.store).updateSettings({
        ...editorSettings2,
        mediaUpload: canUserUploadMedia ? import_media_utils7.uploadMedia : void 0
      });
    }, [editorSettings2, canUserUploadMedia]);
    const [internalPath, setInternalPath] = (0, import_element223.useState)("/");
    const section = path ?? internalPath;
    const onChangeSection = onPathChange ?? setInternalPath;
    const isSelected2 = (blockName) => {
      return section === `/blocks/${encodeURIComponent(blockName)}` || section.startsWith(
        `/blocks/${encodeURIComponent(blockName)}/`
      );
    };
    const onSelect = (blockName, isBlockVariation = false) => {
      if (STYLE_BOOK_COLOR_GROUPS.find(
        (group) => group.slug === blockName
      )) {
        onChangeSection("/colors/palette");
        return;
      }
      if (blockName === "typography") {
        onChangeSection("/typography");
        return;
      }
      if (isBlockVariation) {
        return;
      }
      onChangeSection(`/blocks/${encodeURIComponent(blockName)}`);
    };
    const colors2 = useMultiOriginPalettes();
    const examples = getExamples(colors2);
    const examplesForSinglePageUse = getExamplesForSinglePageUse(examples);
    let previewCategory = null;
    let blockVariation = null;
    if (section.includes("/colors")) {
      previewCategory = "colors";
    } else if (section.includes("/typography")) {
      previewCategory = "text";
    } else if (section.includes("/blocks")) {
      previewCategory = "blocks";
      let blockName = decodeURIComponent(section).split("/blocks/")[1];
      if (blockName?.includes("/variations")) {
        [blockName, blockVariation] = blockName.split("/variations/");
      }
      if (blockName && examples.find((example) => example.name === blockName)) {
        previewCategory = blockName;
      }
    } else if (!isStatic) {
      previewCategory = "overview";
    }
    const categoryDefinition = STYLE_BOOK_PREVIEW_CATEGORIES.find(
      (category) => category.slug === previewCategory
    );
    const filteredExamples = (0, import_element223.useMemo)(() => {
      if (!categoryDefinition) {
        return {
          examples: [
            examples.find(
              (example) => example.name === previewCategory
            )
          ]
        };
      }
      return getExamplesByCategory(categoryDefinition, examples);
    }, [categoryDefinition, examples, previewCategory]);
    const displayedExamples = (0, import_element223.useMemo)(() => {
      if (!previewCategory) {
        return { examples: examplesForSinglePageUse };
      }
      if (blockVariation && filteredExamples?.examples?.length) {
        return {
          examples: applyBlockVariationsToExamples(
            filteredExamples.examples,
            blockVariation
          )
        };
      }
      return filteredExamples;
    }, [
      previewCategory,
      examplesForSinglePageUse,
      blockVariation,
      filteredExamples
    ]);
    const { base: baseConfig } = useGlobalStyles();
    const goTo = getStyleBookNavigationFromPath(section);
    const mergedConfig = (0, import_element223.useMemo)(() => {
      if (!isObjectEmpty(userConfig) && !isObjectEmpty(baseConfig)) {
        return mergeGlobalStyles(baseConfig, userConfig);
      }
      return {};
    }, [baseConfig, userConfig]);
    const [globalStyles] = useGlobalStylesOutputWithConfig(mergedConfig);
    const settings = (0, import_element223.useMemo)(
      () => ({
        ...editorSettings2,
        styles: !isObjectEmpty(globalStyles) && !isObjectEmpty(userConfig) ? globalStyles : editorSettings2.styles,
        isPreviewMode: true
      }),
      [globalStyles, editorSettings2, userConfig]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime380.jsx)("div", { className: "editor-style-book", children: /* @__PURE__ */ (0, import_jsx_runtime380.jsxs)(import_block_editor38.BlockEditorProvider, { settings, children: [
      /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(GlobalStylesRenderer, { disableRootPadding: true }),
      /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
        StyleBookBody,
        {
          examples: displayedExamples,
          settings,
          goTo,
          isSelected: !isStatic ? isSelected2 : null,
          onSelect: !isStatic ? onSelect : null
        }
      )
    ] }) });
  };
  var StyleBookBody = ({
    examples,
    isSelected: isSelected2,
    onClick,
    onSelect,
    settings,
    title,
    goTo
  }) => {
    const [isFocused, setIsFocused] = (0, import_element223.useState)(false);
    const [hasIframeLoaded, setHasIframeLoaded] = (0, import_element223.useState)(false);
    const iframeRef = (0, import_element223.useRef)(null);
    const buttonModeProps = {
      role: "button",
      onFocus: () => setIsFocused(true),
      onBlur: () => setIsFocused(false),
      onKeyDown: (event) => {
        if (event.defaultPrevented) {
          return;
        }
        const { keyCode } = event;
        if (onClick && (keyCode === import_keycodes8.ENTER || keyCode === import_keycodes8.SPACE)) {
          event.preventDefault();
          onClick(event);
        }
      },
      onClick: (event) => {
        if (event.defaultPrevented) {
          return;
        }
        if (onClick) {
          event.preventDefault();
          onClick(event);
        }
      },
      readonly: true
    };
    const handleLoad = () => setHasIframeLoaded(true);
    (0, import_element223.useLayoutEffect)(() => {
      if (hasIframeLoaded && iframeRef.current && goTo?.top) {
        scrollToSection("top", iframeRef.current);
      }
    }, [goTo?.top, hasIframeLoaded]);
    return /* @__PURE__ */ (0, import_jsx_runtime380.jsxs)(
      import_block_editor38.__unstableIframe,
      {
        onLoad: handleLoad,
        ref: iframeRef,
        className: clsx_default("editor-style-book__iframe", {
          "is-focused": isFocused && !!onClick,
          "is-button": !!onClick
        }),
        name: "style-book-canvas",
        tabIndex: 0,
        ...onClick ? buttonModeProps : {},
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(import_block_editor38.__unstableEditorStyles, { styles: settings.styles }),
          /* @__PURE__ */ (0, import_jsx_runtime380.jsxs)("style", { children: [
            STYLE_BOOK_IFRAME_STYLES,
            !!onClick && "body { cursor: var(--wpds-cursor-control, pointer); } body * { pointer-events: none; }"
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
            Examples,
            {
              className: "editor-style-book__examples",
              filteredExamples: examples,
              label: title ? (0, import_i18n209.sprintf)(
                // translators: %s: Category of blocks, e.g. Text.
                (0, import_i18n209.__)("Examples of blocks in the %s category"),
                title
              ) : (0, import_i18n209.__)("Examples of blocks"),
              isSelected: isSelected2,
              onSelect
            },
            title
          )
        ]
      }
    );
  };
  var Examples = (0, import_element223.memo)(
    ({ className, filteredExamples, label, isSelected: isSelected2, onSelect }) => {
      return /* @__PURE__ */ (0, import_jsx_runtime380.jsxs)(
        import_components158.Composite,
        {
          orientation: "vertical",
          className,
          "aria-label": label,
          role: "grid",
          children: [
            !!filteredExamples?.examples?.length && filteredExamples.examples.map((example) => /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
              Example,
              {
                id: `example-${example.name}`,
                title: example.title,
                content: example.content,
                blocks: example.blocks,
                isSelected: isSelected2?.(example.name),
                onClick: !!onSelect ? () => onSelect(
                  example.name,
                  !!example.variation
                ) : null
              },
              example.name
            )),
            !!filteredExamples?.subcategories?.length && filteredExamples.subcategories.map((subcategory) => /* @__PURE__ */ (0, import_jsx_runtime380.jsxs)(
              import_components158.Composite.Group,
              {
                className: "editor-style-book__subcategory",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(import_components158.Composite.GroupLabel, { children: /* @__PURE__ */ (0, import_jsx_runtime380.jsx)("h2", { className: "editor-style-book__subcategory-title", children: subcategory.title }) }),
                  /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
                    Subcategory,
                    {
                      examples: subcategory.examples,
                      isSelected: isSelected2,
                      onSelect
                    }
                  )
                ]
              },
              `subcategory-${subcategory.slug}`
            ))
          ]
        }
      );
    }
  );
  var Subcategory = ({ examples, isSelected: isSelected2, onSelect }) => {
    return !!examples?.length && examples.map((example) => /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
      Example,
      {
        id: `example-${example.name}`,
        title: example.title,
        content: example.content,
        blocks: example.blocks,
        isSelected: isSelected2?.(example.name),
        onClick: !!onSelect ? () => onSelect(example.name) : null
      },
      example.name
    ));
  };
  var disabledExamples = ["example-duotones"];
  var Example = ({ id, title, blocks, isSelected: isSelected2, onClick, content }) => {
    const originalSettings = (0, import_data94.useSelect)(
      (select9) => select9(import_block_editor38.store).getSettings(),
      []
    );
    const settings = (0, import_element223.useMemo)(
      () => ({
        ...originalSettings,
        focusMode: false,
        // Disable "Spotlight mode".
        isPreviewMode: true
      }),
      [originalSettings]
    );
    const renderedBlocks = (0, import_element223.useMemo)(
      () => Array.isArray(blocks) ? blocks : [blocks],
      [blocks]
    );
    const disabledProps = disabledExamples.includes(id) || !onClick ? {
      disabled: true,
      accessibleWhenDisabled: !!onClick
    } : {};
    return /* @__PURE__ */ (0, import_jsx_runtime380.jsx)("div", { role: "row", children: /* @__PURE__ */ (0, import_jsx_runtime380.jsx)("div", { role: "gridcell", children: /* @__PURE__ */ (0, import_jsx_runtime380.jsxs)(
      import_components158.Composite.Item,
      {
        className: clsx_default("editor-style-book__example", {
          "is-selected": isSelected2,
          "is-disabled-example": !!disabledProps?.disabled
        }),
        id,
        "aria-label": !!onClick ? (0, import_i18n209.sprintf)(
          // translators: %s: Title of a block, e.g. Heading.
          (0, import_i18n209.__)("Open %s styles in Styles panel"),
          title
        ) : void 0,
        render: /* @__PURE__ */ (0, import_jsx_runtime380.jsx)("div", {}),
        role: !!onClick ? "button" : null,
        onClick,
        ...disabledProps,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime380.jsx)("span", { className: "editor-style-book__example-title", children: title }),
          /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(
            "div",
            {
              className: "editor-style-book__example-preview",
              "aria-hidden": true,
              children: /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(import_components158.Disabled, { className: "editor-style-book__example-preview__content", children: content ? content : /* @__PURE__ */ (0, import_jsx_runtime380.jsxs)(
                ExperimentalBlockEditorProvider2,
                {
                  value: renderedBlocks,
                  settings,
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(import_block_editor38.__unstableEditorStyles, {}),
                    /* @__PURE__ */ (0, import_jsx_runtime380.jsx)(import_block_editor38.BlockList, { renderAppender: false })
                  ]
                }
              ) })
            }
          )
        ]
      }
    ) }) });
  };
  var style_book_default = (0, import_element223.forwardRef)(StyleBook);

  // packages/editor/build-module/components/styles-canvas/style-book.mjs
  var import_jsx_runtime381 = __toESM(require_jsx_runtime(), 1);
  function StyleBookWithNavigation({
    path,
    onPathChange,
    userConfig,
    forwardedRef
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
      style_book_default,
      {
        ref: forwardedRef,
        path,
        userConfig,
        isSelected: (blockName) => (
          // Match '/blocks/core%2Fbutton' and
          // '/blocks/core%2Fbutton/typography', but not
          // '/blocks/core%2Fbuttons'.
          path === `/blocks/${encodeURIComponent(blockName)}` || path?.startsWith(
            `/blocks/${encodeURIComponent(blockName)}/`
          )
        ),
        onSelect: (blockName) => {
          if (STYLE_BOOK_COLOR_GROUPS.find(
            (group) => group.slug === blockName
          )) {
            onPathChange?.("/colors/palette");
            return;
          }
          if (blockName === "typography") {
            onPathChange?.("/typography");
            return;
          }
          onPathChange?.("/blocks/" + encodeURIComponent(blockName));
        }
      }
    );
  }
  function StylesCanvasRevisionStyleBook({ path, onPathChange, forwardedRef }) {
    const { user: userConfig } = useGlobalStyles();
    const { revisions, isLoading } = useGlobalStylesRevisions();
    const revisionId2 = (0, import_element224.useMemo)(() => {
      const match3 = path?.match(/^\/revisions\/(.+)$/);
      return match3 ? match3[1] : null;
    }, [path]);
    const selectedRevision = (0, import_element224.useMemo)(() => {
      if (!revisionId2 || !revisions.length) {
        return null;
      }
      return revisions.find(
        (revision) => String(revision.id) === String(revisionId2)
      );
    }, [revisionId2, revisions]);
    if (isLoading) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
      StyleBookWithNavigation,
      {
        forwardedRef,
        path,
        onPathChange,
        userConfig: selectedRevision || userConfig
      }
    );
  }
  function StylesCanvasStyleBook({ path, onPathChange }, ref) {
    if (path?.startsWith("/revisions")) {
      return /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
        StylesCanvasRevisionStyleBook,
        {
          forwardedRef: ref,
          path,
          onPathChange
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime381.jsx)(
      StyleBookWithNavigation,
      {
        forwardedRef: ref,
        path,
        onPathChange
      }
    );
  }
  var style_book_default2 = (0, import_element224.forwardRef)(StylesCanvasStyleBook);

  // packages/editor/build-module/components/styles-canvas/revisions.mjs
  var import_components159 = __toESM(require_components(), 1);
  var import_block_editor39 = __toESM(require_block_editor(), 1);
  var import_data95 = __toESM(require_data(), 1);
  var import_element225 = __toESM(require_element(), 1);
  var import_jsx_runtime382 = __toESM(require_jsx_runtime(), 1);
  var {
    ExperimentalBlockEditorProvider: ExperimentalBlockEditorProvider3,
    BlockStyleVariationOverridesWithConfig
  } = unlock(import_block_editor39.privateApis);
  function isObjectEmpty2(object) {
    return !object || Object.keys(object).length === 0;
  }
  function StylesCanvasRevisions({ path }, ref) {
    const blocks = (0, import_data95.useSelect)((select9) => {
      return select9(import_block_editor39.store).getBlocks();
    }, []);
    const { user: userConfig, base: baseConfig } = useGlobalStyles();
    const { revisions, isLoading } = useGlobalStylesRevisions();
    const revisionId2 = (0, import_element225.useMemo)(() => {
      const match3 = path?.match(/^\/revisions\/(.+)$/);
      return match3 ? match3[1] : null;
    }, [path]);
    const selectedRevision = (0, import_element225.useMemo)(() => {
      if (!revisionId2 || !revisions.length) {
        return null;
      }
      return revisions.find(
        (rev) => String(rev.id) === String(revisionId2)
      );
    }, [revisionId2, revisions]);
    const displayConfig = selectedRevision || userConfig;
    const mergedConfig = (0, import_element225.useMemo)(() => {
      if (!isObjectEmpty2(displayConfig) && !isObjectEmpty2(baseConfig)) {
        return mergeGlobalStyles(baseConfig, displayConfig);
      }
      return {};
    }, [baseConfig, displayConfig]);
    const renderedBlocksArray = (0, import_element225.useMemo)(
      () => Array.isArray(blocks) ? blocks : [blocks],
      [blocks]
    );
    const originalSettings = (0, import_data95.useSelect)(
      (select9) => select9(import_block_editor39.store).getSettings(),
      []
    );
    const settings = (0, import_element225.useMemo)(
      () => ({
        ...originalSettings,
        isPreviewMode: true
      }),
      [originalSettings]
    );
    const [globalStyles] = useGlobalStylesOutputWithConfig(mergedConfig);
    const editorStyles = !isObjectEmpty2(globalStyles) && !isObjectEmpty2(displayConfig) ? globalStyles : settings.styles;
    if (isLoading) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime382.jsxs)(
      import_block_editor39.__unstableIframe,
      {
        ref,
        className: "editor-revisions__iframe",
        name: "revisions",
        tabIndex: 0,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime382.jsx)("style", {
            // Forming a "block formatting context" to prevent margin collapsing.
            // @see https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context
            children: `.is-root-container { display: flow-root; }`
          }),
          /* @__PURE__ */ (0, import_jsx_runtime382.jsx)(import_components159.Disabled, { className: "editor-revisions__example-preview__content", children: /* @__PURE__ */ (0, import_jsx_runtime382.jsxs)(
            ExperimentalBlockEditorProvider3,
            {
              value: renderedBlocksArray,
              settings,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime382.jsx)(import_block_editor39.BlockList, { renderAppender: false }),
                /* @__PURE__ */ (0, import_jsx_runtime382.jsx)(import_block_editor39.__unstableEditorStyles, { styles: editorStyles }),
                /* @__PURE__ */ (0, import_jsx_runtime382.jsx)(
                  BlockStyleVariationOverridesWithConfig,
                  {
                    config: mergedConfig
                  }
                )
              ]
            }
          ) })
        ]
      }
    );
  }
  var revisions_default = (0, import_element225.forwardRef)(StylesCanvasRevisions);

  // packages/editor/build-module/components/resizable-editor/index.mjs
  var import_data96 = __toESM(require_data(), 1);
  var import_element226 = __toESM(require_element(), 1);
  var import_components161 = __toESM(require_components(), 1);
  var import_compose36 = __toESM(require_compose(), 1);

  // packages/editor/build-module/components/resizable-editor/resize-handle.mjs
  var import_i18n210 = __toESM(require_i18n(), 1);
  var import_keycodes9 = __toESM(require_keycodes(), 1);
  var import_components160 = __toESM(require_components(), 1);
  var import_jsx_runtime383 = __toESM(require_jsx_runtime(), 1);
  var DELTA_DISTANCE = 20;
  function ResizeHandle({ direction, resizeWidthBy }) {
    function handleKeyDown(event) {
      const { keyCode } = event;
      if (keyCode !== import_keycodes9.LEFT && keyCode !== import_keycodes9.RIGHT) {
        return;
      }
      event.preventDefault();
      if (direction === "left" && keyCode === import_keycodes9.LEFT || direction === "right" && keyCode === import_keycodes9.RIGHT) {
        resizeWidthBy(DELTA_DISTANCE);
      } else if (direction === "left" && keyCode === import_keycodes9.RIGHT || direction === "right" && keyCode === import_keycodes9.LEFT) {
        resizeWidthBy(-DELTA_DISTANCE);
      }
    }
    const resizeHandleVariants = {
      active: {
        opacity: 1,
        scaleY: 1.3
      }
    };
    const resizableHandleHelpId = `resizable-editor__resize-help-${direction}`;
    return /* @__PURE__ */ (0, import_jsx_runtime383.jsxs)(import_jsx_runtime383.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime383.jsxs)(tooltip_exports.Root, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
          tooltip_exports.Trigger,
          {
            render: /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(
              import_components160.__unstableMotion.button,
              {
                className: `editor-resizable-editor__resize-handle is-${direction}`,
                "aria-label": (0, import_i18n210.__)("Drag to resize"),
                "aria-describedby": resizableHandleHelpId,
                onKeyDown: handleKeyDown,
                variants: resizeHandleVariants,
                whileFocus: "active",
                whileHover: "active",
                whileTap: "active",
                role: "separator",
                "aria-orientation": "vertical"
              },
              "handle"
            )
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(tooltip_exports.Popup, { children: (0, import_i18n210.__)("Drag to resize") })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime383.jsx)(VisuallyHidden, { id: resizableHandleHelpId, children: (0, import_i18n210.__)("Use left and right arrow keys to resize the canvas.") })
    ] });
  }

  // packages/editor/build-module/components/resizable-editor/index.mjs
  var import_jsx_runtime384 = __toESM(require_jsx_runtime(), 1);
  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
  };
  function isAtMaxWidth(currentWidth, containerWidth, tolerance = 0) {
    return containerWidth > 0 && currentWidth >= containerWidth - tolerance;
  }
  function ResizableEditor({
    className,
    enableResizing,
    width = "100%",
    height = "100%",
    children
  }) {
    const [isResizing, setIsResizing] = (0, import_element226.useState)(false);
    const disableMotion = (0, import_compose36.useReducedMotion)();
    const { setCanvasWidth: setCanvasWidth2 } = unlock((0, import_data96.useDispatch)(store));
    const resizableRef = (0, import_element226.useRef)();
    const resizeWidthBy = (0, import_element226.useCallback)(
      (deltaPixels) => {
        if (resizableRef.current) {
          const _isAtMaxWidth = isAtMaxWidth(
            resizableRef.current.offsetWidth + deltaPixels,
            resizableRef.current.parentElement?.offsetWidth ?? 0,
            80
          );
          setCanvasWidth2(
            _isAtMaxWidth ? void 0 : resizableRef.current.offsetWidth + deltaPixels
          );
        }
      },
      [setCanvasWidth2]
    );
    const updateCanvasWidth = (0, import_element226.useCallback)(
      (element, isResizeEnd) => {
        const currentWidth = element.offsetWidth;
        const containerWidth = element.parentElement?.offsetWidth ?? 0;
        setCanvasWidth2(
          isResizeEnd && isAtMaxWidth(currentWidth, containerWidth, 80) ? void 0 : currentWidth
        );
      },
      [setCanvasWidth2]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime384.jsx)(
      import_components161.ResizableBox,
      {
        as: import_components161.__unstableMotion.div,
        initial: false,
        animate: { height },
        transition: {
          type: "tween",
          duration: isResizing || disableMotion ? 0 : 0.2,
          ease: "easeOut"
        },
        className: clsx_default("editor-resizable-editor", className, {
          "is-resizable": enableResizing,
          "is-resizing": isResizing
        }),
        ref: (api) => {
          resizableRef.current = api?.resizable;
        },
        size: {
          width,
          height
        },
        onResizeStart: () => {
          setIsResizing(true);
        },
        onResize: (event, direction, element) => {
          updateCanvasWidth(element);
        },
        onResizeStop: (event, direction, element) => {
          updateCanvasWidth(element, true);
          setIsResizing(false);
        },
        minWidth: 300,
        maxWidth: "100%",
        maxHeight: "100%",
        enable: {
          left: enableResizing,
          right: enableResizing
        },
        showHandle: enableResizing,
        resizeRatio: 2,
        handleComponent: {
          left: /* @__PURE__ */ (0, import_jsx_runtime384.jsx)(
            ResizeHandle,
            {
              direction: "left",
              resizeWidthBy
            }
          ),
          right: /* @__PURE__ */ (0, import_jsx_runtime384.jsx)(
            ResizeHandle,
            {
              direction: "right",
              resizeWidthBy
            }
          )
        },
        handleClasses: void 0,
        handleStyles: {
          left: HANDLE_STYLES_OVERRIDE,
          right: HANDLE_STYLES_OVERRIDE
        },
        children
      }
    );
  }
  var resizable_editor_default = ResizableEditor;

  // packages/editor/build-module/components/styles-canvas/index.mjs
  var import_jsx_runtime385 = __toESM(require_jsx_runtime(), 1);
  function getStylesCanvasTitle(path, showStylebook2) {
    if (showStylebook2) {
      return (0, import_i18n211.__)("Style Book");
    }
    if (path?.startsWith("/revisions")) {
      return (0, import_i18n211.__)("Style Revisions");
    }
    return "";
  }
  function StylesCanvas() {
    const { stylesPath: stylesPath2, showStylebook: showStylebook2, showListViewByDefault } = (0, import_data97.useSelect)(
      (select9) => {
        const { getStylesPath: getStylesPath2, getShowStylebook: getShowStylebook2 } = unlock(
          select9(store)
        );
        const _showListViewByDefault = select9(import_preferences11.store).get(
          "core",
          "showListViewByDefault"
        );
        return {
          stylesPath: getStylesPath2(),
          showStylebook: getShowStylebook2(),
          showListViewByDefault: _showListViewByDefault
        };
      },
      []
    );
    const { resetStylesNavigation: resetStylesNavigation2, setStylesPath: setStylesPath2 } = unlock(
      (0, import_data97.useDispatch)(store)
    );
    const { setIsListViewOpened: setIsListViewOpened2 } = (0, import_data97.useDispatch)(store);
    const focusOnMountRef = (0, import_compose37.useFocusOnMount)("firstElement");
    const sectionFocusReturnRef = (0, import_compose37.useFocusReturn)();
    let content = null;
    if (showStylebook2) {
      content = /* @__PURE__ */ (0, import_jsx_runtime385.jsx)(
        style_book_default2,
        {
          path: stylesPath2,
          onPathChange: setStylesPath2,
          ref: sectionFocusReturnRef
        }
      );
    } else if (stylesPath2?.startsWith("/revisions")) {
      content = /* @__PURE__ */ (0, import_jsx_runtime385.jsx)(
        revisions_default,
        {
          path: stylesPath2,
          ref: sectionFocusReturnRef
        }
      );
    }
    const title = getStylesCanvasTitle(stylesPath2, showStylebook2);
    const onCloseCanvas = () => {
      setIsListViewOpened2(showListViewByDefault);
      resetStylesNavigation2();
    };
    const closeOnEscape = (event) => {
      if (event.keyCode === import_keycodes10.ESCAPE && !event.defaultPrevented) {
        event.preventDefault();
        onCloseCanvas();
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime385.jsx)("div", { className: "editor-styles-canvas", children: /* @__PURE__ */ (0, import_jsx_runtime385.jsx)(resizable_editor_default, { enableResizing: false, children: /* @__PURE__ */ (0, import_jsx_runtime385.jsxs)(
      "section",
      {
        className: "editor-styles-canvas__section",
        ref: focusOnMountRef,
        onKeyDown: closeOnEscape,
        "aria-label": title,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime385.jsx)(
            import_components162.Button,
            {
              size: "compact",
              className: "editor-styles-canvas__close-button",
              icon: close_small_default,
              label: (0, import_i18n211.__)("Close"),
              onClick: onCloseCanvas
            }
          ),
          content
        ]
      }
    ) }) });
  }

  // packages/editor/build-module/components/document-bar/useEditedSectionDetails.mjs
  var import_data98 = __toESM(require_data(), 1);
  var import_html_entities15 = __toESM(require_html_entities(), 1);
  var import_block_editor40 = __toESM(require_block_editor(), 1);
  var import_core_data63 = __toESM(require_core_data(), 1);
  function useEditedSectionDetails() {
    return (0, import_data98.useSelect)((select9) => {
      const {
        getBlockAttributes: getBlockAttributes2,
        getBlockName: getBlockName2,
        __experimentalGetParsedPattern
      } = select9(import_block_editor40.store);
      const { getEditedEntityRecord, getCurrentTheme } = select9(import_core_data63.store);
      const { getEditedContentOnlySection } = unlock(
        select9(import_block_editor40.store)
      );
      const editedSectionId = getEditedContentOnlySection();
      if (!editedSectionId) {
        return null;
      }
      const attributes = getBlockAttributes2(editedSectionId);
      const patternName = attributes?.metadata?.patternName;
      if (patternName) {
        const pattern = typeof __experimentalGetParsedPattern === "function" ? __experimentalGetParsedPattern(patternName) : null;
        return {
          patternName,
          patternTitle: pattern?.title || attributes?.metadata?.name,
          type: "pattern"
        };
      }
      const blockName = getBlockName2(editedSectionId);
      if (blockName === "core/block" && !!attributes?.ref) {
        const entity = getEditedEntityRecord(
          "postType",
          "wp_block",
          attributes.ref
        );
        if (entity?.title) {
          return {
            patternName: attributes.ref,
            patternTitle: (0, import_html_entities15.decodeEntities)(entity.title),
            type: "synced-pattern"
          };
        }
      }
      if (blockName === "core/template-part" && !!attributes?.slug) {
        const theme2 = attributes.theme || getCurrentTheme()?.stylesheet;
        const templatePartId = theme2 ? `${theme2}//${attributes.slug}` : null;
        if (templatePartId) {
          const entity = getEditedEntityRecord(
            "postType",
            "wp_template_part",
            templatePartId
          );
          if (entity?.title) {
            return {
              patternName: attributes.slug,
              patternTitle: (0, import_html_entities15.decodeEntities)(entity.title),
              type: "template-part"
            };
          }
        }
      }
      return null;
    }, []);
  }

  // packages/editor/build-module/components/document-bar/index.mjs
  var import_jsx_runtime386 = __toESM(require_jsx_runtime(), 1);
  var MotionButton = import_components163.__unstableMotion.create(import_components163.Button);
  function DocumentBar(props) {
    const { stopEditingContentOnlySection } = unlock(
      (0, import_data99.useDispatch)(import_block_editor41.store)
    );
    const unlockedPatternInfo = useEditedSectionDetails();
    const {
      postId: postId2,
      postType: postType2,
      postTypeLabel,
      documentTitle,
      isNotFound,
      templateTitle,
      onNavigateToPreviousEntityRecord,
      isTemplatePreview,
      stylesCanvasTitle
    } = (0, import_data99.useSelect)((select9) => {
      const {
        getCurrentPostType: getCurrentPostType2,
        getCurrentPostId: getCurrentPostId2,
        getEditorSettings: getEditorSettings2,
        getRenderingMode: getRenderingMode2
      } = select9(store);
      const {
        getEditedEntityRecord,
        getPostType,
        getCurrentTheme,
        isResolving: isResolvingSelector
      } = select9(import_core_data64.store);
      const _postType = getCurrentPostType2();
      const _postId = getCurrentPostId2();
      const _document = getEditedEntityRecord(
        "postType",
        _postType,
        _postId
      );
      const { default_template_types: templateTypes = [] } = getCurrentTheme() ?? {};
      const _templateInfo = getTemplateInfo({
        templateTypes,
        template: _document
      });
      const _postTypeLabel = getPostType(_postType)?.labels?.singular_name;
      const { getStylesPath: getStylesPath2, getShowStylebook: getShowStylebook2 } = unlock(
        select9(store)
      );
      const _stylesPath = getStylesPath2();
      const _showStylebook = getShowStylebook2();
      const _stylesCanvasTitle = getStylesCanvasTitle(
        _stylesPath,
        _showStylebook
      );
      return {
        postId: _postId,
        postType: _postType,
        postTypeLabel: _postTypeLabel,
        documentTitle: _document.title,
        isNotFound: !_document && !isResolvingSelector(
          "getEditedEntityRecord",
          "postType",
          _postType,
          _postId
        ),
        templateTitle: _templateInfo.title,
        onNavigateToPreviousEntityRecord: getEditorSettings2().onNavigateToPreviousEntityRecord,
        isTemplatePreview: getRenderingMode2() === "template-locked",
        stylesCanvasTitle: _stylesCanvasTitle
      };
    }, []);
    const { open: openCommandCenter } = (0, import_data99.useDispatch)(import_commands3.store);
    const isReducedMotion = (0, import_compose38.useReducedMotion)();
    const isTemplate2 = TEMPLATE_POST_TYPES.includes(postType2);
    const hasBackButton = !!onNavigateToPreviousEntityRecord || !!unlockedPatternInfo;
    const entityTitle = isTemplate2 ? templateTitle : documentTitle;
    const title = unlockedPatternInfo?.patternTitle || props.title || stylesCanvasTitle || entityTitle;
    const icon = props.icon;
    const handleBackClick = (event) => {
      event.stopPropagation();
      if (unlockedPatternInfo) {
        stopEditingContentOnlySection();
      } else if (onNavigateToPreviousEntityRecord) {
        onNavigateToPreviousEntityRecord();
      }
    };
    const pageTypeBadge = usePageTypeBadge(postId2);
    const mountedRef = (0, import_element227.useRef)(false);
    (0, import_element227.useEffect)(() => {
      mountedRef.current = true;
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime386.jsxs)(
      "div",
      {
        className: clsx_default("editor-document-bar", {
          "has-back-button": hasBackButton
        }),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime386.jsx)(import_components163.__unstableAnimatePresence, { children: hasBackButton && /* @__PURE__ */ (0, import_jsx_runtime386.jsx)(
            MotionButton,
            {
              className: "editor-document-bar__back",
              icon: (0, import_i18n212.isRTL)() ? chevron_right_small_default : chevron_left_small_default,
              onClick: handleBackClick,
              size: "compact",
              initial: mountedRef.current ? { opacity: 0, transform: "translateX(15%)" } : false,
              animate: { opacity: 1, transform: "translateX(0%)" },
              exit: { opacity: 0, transform: "translateX(15%)" },
              transition: isReducedMotion ? { duration: 0 } : void 0,
              children: (0, import_i18n212.__)("Back")
            }
          ) }),
          !isTemplate2 && isTemplatePreview && !hasBackButton && /* @__PURE__ */ (0, import_jsx_runtime386.jsx)(
            import_block_editor41.BlockIcon,
            {
              icon: layout_default,
              className: "editor-document-bar__icon-layout"
            }
          ),
          isNotFound ? /* @__PURE__ */ (0, import_jsx_runtime386.jsx)(import_components163.__experimentalText, { children: (0, import_i18n212.__)("Document not found") }) : /* @__PURE__ */ (0, import_jsx_runtime386.jsx)(
            import_components163.Button,
            {
              className: "editor-document-bar__command",
              onClick: () => openCommandCenter(),
              size: "compact",
              children: /* @__PURE__ */ (0, import_jsx_runtime386.jsxs)(
                import_components163.__unstableMotion.div,
                {
                  className: "editor-document-bar__title",
                  initial: mountedRef.current ? {
                    opacity: 0,
                    transform: hasBackButton ? "translateX(15%)" : "translateX(-15%)"
                  } : false,
                  animate: {
                    opacity: 1,
                    transform: "translateX(0%)"
                  },
                  transition: isReducedMotion ? { duration: 0 } : void 0,
                  children: [
                    icon && /* @__PURE__ */ (0, import_jsx_runtime386.jsx)(import_block_editor41.BlockIcon, { icon }),
                    /* @__PURE__ */ (0, import_jsx_runtime386.jsxs)(import_components163.__experimentalText, { size: "body", as: "h1", children: [
                      /* @__PURE__ */ (0, import_jsx_runtime386.jsx)("span", { className: "editor-document-bar__post-title", children: title ? (0, import_dom23.__unstableStripHTML)(title) : (0, import_i18n212.__)("No title") }),
                      unlockedPatternInfo && /* @__PURE__ */ (0, import_jsx_runtime386.jsx)("span", { className: "editor-document-bar__post-type-label", children: unlockedPatternInfo.type === "template-part" ? `\xB7 ${(0, import_i18n212.__)("Template Part")}` : `\xB7 ${(0, import_i18n212.__)("Pattern")}` }),
                      !unlockedPatternInfo && pageTypeBadge && /* @__PURE__ */ (0, import_jsx_runtime386.jsx)("span", { className: "editor-document-bar__post-type-label", children: `\xB7 ${pageTypeBadge}` }),
                      !unlockedPatternInfo && postTypeLabel && !props.title && !pageTypeBadge && /* @__PURE__ */ (0, import_jsx_runtime386.jsx)("span", { className: "editor-document-bar__post-type-label", children: `\xB7 ${(0, import_html_entities16.decodeEntities)(
                        postTypeLabel
                      )}` })
                    ] })
                  ]
                },
                hasBackButton
              )
            }
          )
        ]
      }
    );
  }

  // packages/editor/build-module/components/document-outline/index.mjs
  var import_i18n213 = __toESM(require_i18n(), 1);
  var import_data100 = __toESM(require_data(), 1);
  var import_element228 = __toESM(require_element(), 1);
  var import_rich_text5 = __toESM(require_rich_text(), 1);
  var import_block_editor42 = __toESM(require_block_editor(), 1);
  var import_core_data65 = __toESM(require_core_data(), 1);
  var import_components164 = __toESM(require_components(), 1);

  // packages/editor/build-module/components/document-outline/item.mjs
  var import_jsx_runtime387 = __toESM(require_jsx_runtime(), 1);
  var TableOfContentsItem = ({
    children,
    isValid: isValid2,
    isDisabled,
    level,
    href,
    onSelect
  }) => {
    function handleClick(event) {
      if (isDisabled) {
        event.preventDefault();
        return;
      }
      onSelect();
    }
    return /* @__PURE__ */ (0, import_jsx_runtime387.jsx)(
      "li",
      {
        className: clsx_default(
          "document-outline__item",
          `is-${level.toLowerCase()}`,
          {
            "is-invalid": !isValid2,
            "is-disabled": isDisabled
          }
        ),
        children: /* @__PURE__ */ (0, import_jsx_runtime387.jsxs)(
          "a",
          {
            href,
            className: "document-outline__button",
            "aria-disabled": isDisabled,
            onClick: handleClick,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime387.jsx)(
                "span",
                {
                  className: "document-outline__emdash",
                  "aria-hidden": "true"
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime387.jsx)("strong", { className: "document-outline__level", children: level }),
              /* @__PURE__ */ (0, import_jsx_runtime387.jsx)("span", { className: "document-outline__item-content", children })
            ]
          }
        )
      }
    );
  };
  var item_default = TableOfContentsItem;

  // packages/editor/build-module/components/document-outline/index.mjs
  var import_jsx_runtime388 = __toESM(require_jsx_runtime(), 1);
  var emptyHeadingContent = /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("em", { children: (0, import_i18n213.__)("(Empty heading)") });
  var incorrectLevelContent = [
    /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("br", {}, "incorrect-break"),
    /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("em", { children: (0, import_i18n213.__)("(Incorrect heading level)") }, "incorrect-message")
  ];
  var singleH1Headings = [
    /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("br", {}, "incorrect-break-h1"),
    /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("em", { children: (0, import_i18n213.__)("(Your theme may already use a H1 for the post title)") }, "incorrect-message-h1")
  ];
  var multipleH1Headings = [
    /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("br", {}, "incorrect-break-multiple-h1"),
    /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("em", { children: (0, import_i18n213.__)("(Multiple H1 headings are not recommended)") }, "incorrect-message-multiple-h1")
  ];
  function EmptyOutlineIllustration() {
    return /* @__PURE__ */ (0, import_jsx_runtime388.jsxs)(
      import_components164.SVG,
      {
        width: "138",
        height: "148",
        viewBox: "0 0 138 148",
        fill: "none",
        xmlns: "http://www.w3.org/2000/svg",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components164.Rect, { width: "138", height: "148", rx: "4", fill: "#F0F6FC" }),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components164.Line, { x1: "44", y1: "28", x2: "24", y2: "28", stroke: "#DDDDDD" }),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components164.Rect, { x: "48", y: "16", width: "27", height: "23", rx: "4", fill: "#DDDDDD" }),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(
            import_components164.Path,
            {
              d: "M54.7585 32V23.2727H56.6037V26.8736H60.3494V23.2727H62.1903V32H60.3494V28.3949H56.6037V32H54.7585ZM67.4574 23.2727V32H65.6122V25.0241H65.5611L63.5625 26.277V24.6406L65.723 23.2727H67.4574Z",
              fill: "black"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components164.Line, { x1: "55", y1: "59", x2: "24", y2: "59", stroke: "#DDDDDD" }),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components164.Rect, { x: "59", y: "47", width: "29", height: "23", rx: "4", fill: "#DDDDDD" }),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(
            import_components164.Path,
            {
              d: "M65.7585 63V54.2727H67.6037V57.8736H71.3494V54.2727H73.1903V63H71.3494V59.3949H67.6037V63H65.7585ZM74.6605 63V61.6705L77.767 58.794C78.0313 58.5384 78.2528 58.3082 78.4318 58.1037C78.6136 57.8991 78.7514 57.6989 78.8452 57.5028C78.9389 57.304 78.9858 57.0895 78.9858 56.8594C78.9858 56.6037 78.9276 56.3835 78.8111 56.1989C78.6946 56.0114 78.5355 55.8679 78.3338 55.7685C78.1321 55.6662 77.9034 55.6151 77.6477 55.6151C77.3807 55.6151 77.1477 55.669 76.9489 55.777C76.75 55.8849 76.5966 56.0398 76.4886 56.2415C76.3807 56.4432 76.3267 56.6832 76.3267 56.9616H74.5753C74.5753 56.3906 74.7045 55.8949 74.9631 55.4744C75.2216 55.054 75.5838 54.7287 76.0497 54.4986C76.5156 54.2685 77.0526 54.1534 77.6605 54.1534C78.2855 54.1534 78.8295 54.2642 79.2926 54.4858C79.7585 54.7045 80.1207 55.0085 80.3793 55.3977C80.6378 55.7869 80.767 56.233 80.767 56.7358C80.767 57.0653 80.7017 57.3906 80.571 57.7116C80.4432 58.0327 80.2145 58.3892 79.8849 58.7812C79.5554 59.1705 79.0909 59.6378 78.4915 60.1832L77.2173 61.4318V61.4915H80.8821V63H74.6605Z",
              fill: "black"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components164.Line, { x1: "80", y1: "90", x2: "24", y2: "90", stroke: "#DDDDDD" }),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components164.Rect, { x: "84", y: "78", width: "30", height: "23", rx: "4", fill: "#F0B849" }),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(
            import_components164.Path,
            {
              d: "M90.7585 94V85.2727H92.6037V88.8736H96.3494V85.2727H98.1903V94H96.3494V90.3949H92.6037V94H90.7585ZM99.5284 92.4659V91.0128L103.172 85.2727H104.425V87.2841H103.683L101.386 90.919V90.9872H106.564V92.4659H99.5284ZM103.717 94V92.0227L103.751 91.3793V85.2727H105.482V94H103.717Z",
              fill: "black"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components164.Line, { x1: "66", y1: "121", x2: "24", y2: "121", stroke: "#DDDDDD" }),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(import_components164.Rect, { x: "70", y: "109", width: "29", height: "23", rx: "4", fill: "#DDDDDD" }),
          /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(
            import_components164.Path,
            {
              d: "M76.7585 125V116.273H78.6037V119.874H82.3494V116.273H84.1903V125H82.3494V121.395H78.6037V125H76.7585ZM88.8864 125.119C88.25 125.119 87.6832 125.01 87.1861 124.791C86.6918 124.57 86.3011 124.266 86.0142 123.879C85.7301 123.49 85.5838 123.041 85.5753 122.533H87.4332C87.4446 122.746 87.5142 122.933 87.642 123.095C87.7727 123.254 87.946 123.378 88.1619 123.466C88.3778 123.554 88.6207 123.598 88.8906 123.598C89.1719 123.598 89.4205 123.548 89.6364 123.449C89.8523 123.349 90.0213 123.212 90.1435 123.036C90.2656 122.859 90.3267 122.656 90.3267 122.426C90.3267 122.193 90.2614 121.987 90.1307 121.808C90.0028 121.626 89.8182 121.484 89.5767 121.382C89.3381 121.28 89.054 121.229 88.7244 121.229H87.9105V119.874H88.7244C89.0028 119.874 89.2486 119.825 89.4616 119.729C89.6776 119.632 89.8452 119.499 89.9645 119.328C90.0838 119.155 90.1435 118.953 90.1435 118.723C90.1435 118.504 90.0909 118.312 89.9858 118.148C89.8835 117.98 89.7386 117.849 89.5511 117.756C89.3665 117.662 89.1506 117.615 88.9034 117.615C88.6534 117.615 88.4247 117.661 88.2173 117.751C88.0099 117.839 87.8438 117.966 87.7188 118.131C87.5938 118.295 87.527 118.489 87.5185 118.71H85.75C85.7585 118.207 85.902 117.764 86.1804 117.381C86.4588 116.997 86.8338 116.697 87.3054 116.482C87.7798 116.263 88.3153 116.153 88.9119 116.153C89.5142 116.153 90.0412 116.263 90.4929 116.482C90.9446 116.7 91.2955 116.996 91.5455 117.368C91.7983 117.737 91.9233 118.152 91.9205 118.612C91.9233 119.101 91.7713 119.509 91.4645 119.835C91.1605 120.162 90.7642 120.369 90.2756 120.457V120.526C90.9176 120.608 91.4063 120.831 91.7415 121.195C92.0795 121.555 92.2472 122.007 92.2443 122.55C92.2472 123.047 92.1037 123.489 91.8139 123.875C91.527 124.261 91.1307 124.565 90.625 124.787C90.1193 125.009 89.5398 125.119 88.8864 125.119Z",
              fill: "black"
            }
          )
        ]
      }
    );
  }
  var computeOutlineHeadings = (blocks = []) => {
    return blocks.filter((block) => block.name === "core/heading").map((block) => ({
      ...block,
      level: block.attributes.level,
      isEmpty: isEmptyHeading(block)
    }));
  };
  var isEmptyHeading = (heading) => !heading.attributes.content || heading.attributes.content.trim().length === 0;
  function DocumentOutline({
    onSelect,
    hasOutlineItemsDisabled
  }) {
    const { selectBlock: selectBlock2 } = (0, import_data100.useDispatch)(import_block_editor42.store);
    const { title, isTitleSupported } = (0, import_data100.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
      const { getPostType } = select9(import_core_data65.store);
      const postType2 = getPostType(getEditedPostAttribute2("type"));
      return {
        title: getEditedPostAttribute2("title"),
        isTitleSupported: postType2?.supports?.title ?? false
      };
    });
    const blocks = (0, import_data100.useSelect)((select9) => {
      const { getClientIdsWithDescendants: getClientIdsWithDescendants2, getBlock: getBlock2 } = select9(import_block_editor42.store);
      const clientIds = getClientIdsWithDescendants2();
      return clientIds.map((id) => getBlock2(id));
    });
    const contentBlocks = (0, import_data100.useSelect)((select9) => {
      if (select9(store).getRenderingMode() === "post-only") {
        return void 0;
      }
      const { getBlocksByName, getClientIdsOfDescendants: getClientIdsOfDescendants2 } = select9(import_block_editor42.store);
      const [postContentClientId] = getBlocksByName("core/post-content");
      if (!postContentClientId) {
        return void 0;
      }
      return getClientIdsOfDescendants2(postContentClientId);
    }, []);
    const prevHeadingLevelRef = (0, import_element228.useRef)(1);
    const headings = (0, import_element228.useMemo)(
      () => computeOutlineHeadings(blocks),
      [blocks]
    );
    if (headings.length < 1) {
      return /* @__PURE__ */ (0, import_jsx_runtime388.jsxs)("div", { className: "editor-document-outline has-no-headings", children: [
        /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(EmptyOutlineIllustration, {}),
        /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("p", { children: (0, import_i18n213.__)(
          "Navigate the structure of your document and address issues like empty or incorrect heading levels."
        ) })
      ] });
    }
    const titleNode = document.querySelector(".editor-post-title__input");
    const hasTitle = isTitleSupported && title && titleNode;
    const countByLevel = headings.reduce(
      (acc, heading) => ({
        ...acc,
        [heading.level]: (acc[heading.level] || 0) + 1
      }),
      {}
    );
    const hasMultipleH1 = countByLevel[1] > 1;
    function isContentBlock(clientId) {
      return Array.isArray(contentBlocks) ? contentBlocks.includes(clientId) : true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime388.jsx)("div", { className: "document-outline", children: /* @__PURE__ */ (0, import_jsx_runtime388.jsxs)("ul", { children: [
      hasTitle && /* @__PURE__ */ (0, import_jsx_runtime388.jsx)(
        item_default,
        {
          level: (0, import_i18n213.__)("Title"),
          isValid: true,
          onSelect,
          href: `#${titleNode.id}`,
          isDisabled: hasOutlineItemsDisabled,
          children: title
        }
      ),
      headings.map((item) => {
        const isIncorrectLevel = item.level > prevHeadingLevelRef.current + 1;
        const isValid2 = !item.isEmpty && !isIncorrectLevel && !!item.level && (item.level !== 1 || !hasMultipleH1 && !hasTitle);
        prevHeadingLevelRef.current = item.level;
        return /* @__PURE__ */ (0, import_jsx_runtime388.jsxs)(
          item_default,
          {
            level: `H${item.level}`,
            isValid: isValid2,
            isDisabled: hasOutlineItemsDisabled || !isContentBlock(item.clientId),
            href: `#block-${item.clientId}`,
            onSelect: () => {
              selectBlock2(item.clientId);
              onSelect?.();
            },
            children: [
              item.isEmpty ? emptyHeadingContent : (0, import_rich_text5.getTextContent)(
                (0, import_rich_text5.create)({
                  html: item.attributes.content
                })
              ),
              isIncorrectLevel && incorrectLevelContent,
              item.level === 1 && hasMultipleH1 && multipleH1Headings,
              hasTitle && item.level === 1 && !hasMultipleH1 && singleH1Headings
            ]
          },
          item.clientId
        );
      })
    ] }) });
  }

  // packages/editor/build-module/components/document-outline/check.mjs
  var import_data101 = __toESM(require_data(), 1);
  var import_block_editor43 = __toESM(require_block_editor(), 1);
  function DocumentOutlineCheck({ children }) {
    const hasHeadings = (0, import_data101.useSelect)((select9) => {
      const { getGlobalBlockCount: getGlobalBlockCount2 } = select9(import_block_editor43.store);
      return getGlobalBlockCount2("core/heading") > 0;
    });
    if (!hasHeadings) {
      return null;
    }
    return children;
  }

  // packages/editor/build-module/components/global-keyboard-shortcuts/register-shortcuts.mjs
  var import_element229 = __toESM(require_element(), 1);
  var import_data102 = __toESM(require_data(), 1);
  var import_i18n214 = __toESM(require_i18n(), 1);
  var import_block_editor44 = __toESM(require_block_editor(), 1);
  var import_keyboard_shortcuts5 = __toESM(require_keyboard_shortcuts(), 1);
  var import_keycodes11 = __toESM(require_keycodes(), 1);
  var import_jsx_runtime389 = __toESM(require_jsx_runtime(), 1);
  function EditorKeyboardShortcutsRegister() {
    const { registerShortcut } = (0, import_data102.useDispatch)(import_keyboard_shortcuts5.store);
    (0, import_element229.useEffect)(() => {
      registerShortcut({
        name: "core/editor/toggle-mode",
        category: "global",
        description: (0, import_i18n214.__)("Switch between visual editor and code editor."),
        keyCombination: {
          modifier: "secondary",
          character: "m"
        }
      });
      registerShortcut({
        name: "core/editor/save",
        category: "global",
        description: (0, import_i18n214.__)("Save your changes."),
        keyCombination: {
          modifier: "primary",
          character: "s"
        }
      });
      registerShortcut({
        name: "core/editor/undo",
        category: "global",
        description: (0, import_i18n214.__)("Undo your last changes."),
        keyCombination: {
          modifier: "primary",
          character: "z"
        }
      });
      registerShortcut({
        name: "core/editor/redo",
        category: "global",
        description: (0, import_i18n214.__)("Redo your last undo."),
        keyCombination: {
          modifier: "primaryShift",
          character: "z"
        },
        // Disable on Apple OS because it conflicts with the browser's
        // history shortcut. It's a fine alias for both Windows and Linux.
        // Since there's no conflict for Ctrl+Shift+Z on both Windows and
        // Linux, we keep it as the default for consistency.
        aliases: (0, import_keycodes11.isAppleOS)() ? [] : [
          {
            modifier: "primary",
            character: "y"
          }
        ]
      });
      registerShortcut({
        name: "core/editor/toggle-list-view",
        category: "global",
        description: (0, import_i18n214.__)("Show or hide the List View."),
        keyCombination: {
          modifier: "access",
          character: "o"
        }
      });
      registerShortcut({
        name: "core/editor/toggle-distraction-free",
        category: "global",
        description: (0, import_i18n214.__)("Enter or exit distraction free mode."),
        keyCombination: {
          modifier: "primaryShift",
          character: "\\"
        }
      });
      registerShortcut({
        name: "core/editor/toggle-sidebar",
        category: "global",
        description: (0, import_i18n214.__)("Show or hide the Settings panel."),
        keyCombination: {
          modifier: "primaryShift",
          character: ","
        }
      });
      registerShortcut({
        name: "core/editor/keyboard-shortcuts",
        category: "main",
        description: (0, import_i18n214.__)("Display these keyboard shortcuts."),
        keyCombination: {
          modifier: "access",
          character: "h"
        }
      });
      registerShortcut({
        name: "core/editor/new-note",
        category: "block",
        description: (0, import_i18n214.__)("Add a new note."),
        keyCombination: {
          modifier: "primaryAlt",
          character: "m"
        }
      });
      registerShortcut({
        name: "core/editor/next-region",
        category: "global",
        description: (0, import_i18n214.__)("Navigate to the next part of the editor."),
        keyCombination: {
          modifier: "ctrl",
          character: "`"
        },
        aliases: [
          {
            modifier: "access",
            character: "n"
          }
        ]
      });
      registerShortcut({
        name: "core/editor/previous-region",
        category: "global",
        description: (0, import_i18n214.__)("Navigate to the previous part of the editor."),
        keyCombination: {
          modifier: "ctrlShift",
          character: "`"
        },
        aliases: [
          {
            modifier: "access",
            character: "p"
          },
          {
            modifier: "ctrlShift",
            character: "~"
          }
        ]
      });
    }, [registerShortcut]);
    return /* @__PURE__ */ (0, import_jsx_runtime389.jsx)(import_block_editor44.BlockEditorKeyboardShortcuts.Register, {});
  }
  var register_shortcuts_default = EditorKeyboardShortcutsRegister;

  // packages/editor/build-module/components/editor-history/redo.mjs
  var import_i18n215 = __toESM(require_i18n(), 1);
  var import_components165 = __toESM(require_components(), 1);
  var import_data103 = __toESM(require_data(), 1);
  var import_keycodes12 = __toESM(require_keycodes(), 1);
  var import_element230 = __toESM(require_element(), 1);
  var import_jsx_runtime390 = __toESM(require_jsx_runtime(), 1);
  function EditorHistoryRedo(props, ref) {
    const shortcut = (0, import_keycodes12.isAppleOS)() ? import_keycodes12.displayShortcut.primaryShift("z") : import_keycodes12.displayShortcut.primary("y");
    const hasRedo = (0, import_data103.useSelect)(
      (select9) => select9(store).hasEditorRedo(),
      []
    );
    const { redo: redo2 } = (0, import_data103.useDispatch)(store);
    return /* @__PURE__ */ (0, import_jsx_runtime390.jsx)(
      import_components165.Button,
      {
        __next40pxDefaultSize: true,
        ...props,
        ref,
        icon: !(0, import_i18n215.isRTL)() ? redo_default : undo_default,
        label: (0, import_i18n215.__)("Redo"),
        shortcut,
        "aria-disabled": !hasRedo,
        onClick: hasRedo ? redo2 : void 0,
        className: "editor-history__redo"
      }
    );
  }
  var redo_default2 = (0, import_element230.forwardRef)(EditorHistoryRedo);

  // packages/editor/build-module/components/editor-history/undo.mjs
  var import_i18n216 = __toESM(require_i18n(), 1);
  var import_components166 = __toESM(require_components(), 1);
  var import_data104 = __toESM(require_data(), 1);
  var import_keycodes13 = __toESM(require_keycodes(), 1);
  var import_element231 = __toESM(require_element(), 1);
  var import_jsx_runtime391 = __toESM(require_jsx_runtime(), 1);
  function EditorHistoryUndo(props, ref) {
    const hasUndo = (0, import_data104.useSelect)(
      (select9) => select9(store).hasEditorUndo(),
      []
    );
    const { undo: undo2 } = (0, import_data104.useDispatch)(store);
    return /* @__PURE__ */ (0, import_jsx_runtime391.jsx)(
      import_components166.Button,
      {
        __next40pxDefaultSize: true,
        ...props,
        ref,
        icon: !(0, import_i18n216.isRTL)() ? undo_default : redo_default,
        label: (0, import_i18n216.__)("Undo"),
        shortcut: import_keycodes13.displayShortcut.primary("z"),
        "aria-disabled": !hasUndo,
        onClick: hasUndo ? undo2 : void 0,
        className: "editor-history__undo"
      }
    );
  }
  var undo_default2 = (0, import_element231.forwardRef)(EditorHistoryUndo);

  // packages/editor/build-module/components/editor-notices/index.mjs
  var import_deprecated10 = __toESM(require_deprecated(), 1);
  var import_data106 = __toESM(require_data(), 1);
  var import_block_editor46 = __toESM(require_block_editor(), 1);
  var import_notices21 = __toESM(require_notices(), 1);

  // packages/editor/build-module/components/template-validation-notice/index.mjs
  var import_components167 = __toESM(require_components(), 1);
  var import_i18n217 = __toESM(require_i18n(), 1);
  var import_data105 = __toESM(require_data(), 1);
  var import_element232 = __toESM(require_element(), 1);
  var import_block_editor45 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime392 = __toESM(require_jsx_runtime(), 1);
  function TemplateValidationNotice() {
    const [showConfirmDialog, setShowConfirmDialog] = (0, import_element232.useState)(false);
    const isValid2 = (0, import_data105.useSelect)((select9) => {
      return select9(import_block_editor45.store).isValidTemplate();
    }, []);
    const { setTemplateValidity: setTemplateValidity2, synchronizeTemplate: synchronizeTemplate2 } = (0, import_data105.useDispatch)(import_block_editor45.store);
    if (isValid2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime392.jsxs)(import_jsx_runtime392.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(
        import_components167.Notice,
        {
          className: "editor-template-validation-notice",
          isDismissible: false,
          status: "warning",
          actions: [
            {
              label: (0, import_i18n217.__)("Keep it as is"),
              onClick: () => setTemplateValidity2(true)
            },
            {
              label: (0, import_i18n217.__)("Reset the template"),
              onClick: () => setShowConfirmDialog(true)
            }
          ],
          children: (0, import_i18n217.__)(
            "The content of your post doesn\u2019t match the template assigned to your post type."
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime392.jsx)(
        import_components167.__experimentalConfirmDialog,
        {
          isOpen: showConfirmDialog,
          confirmButtonText: (0, import_i18n217.__)("Reset"),
          onConfirm: () => {
            setShowConfirmDialog(false);
            synchronizeTemplate2();
          },
          onCancel: () => setShowConfirmDialog(false),
          size: "medium",
          children: (0, import_i18n217.__)(
            "Resetting the template may result in loss of content, do you want to continue?"
          )
        }
      )
    ] });
  }

  // packages/editor/build-module/components/editor-notices/index.mjs
  var import_jsx_runtime393 = __toESM(require_jsx_runtime(), 1);
  function EditorNotices() {
    (0, import_deprecated10.default)("wp.editor.EditorNotices", {
      since: "7.0",
      version: "7.2",
      alternative: "wp.notices.InlineNotices"
    });
    const isValidTemplate2 = (0, import_data106.useSelect)((select9) => {
      return select9(import_block_editor46.store).isValidTemplate();
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime393.jsx)(
      import_notices21.InlineNotices,
      {
        pinnedNoticesClassName: "components-editor-notices__pinned",
        dismissibleNoticesClassName: "components-editor-notices__dismissible",
        children: !isValidTemplate2 && /* @__PURE__ */ (0, import_jsx_runtime393.jsx)(TemplateValidationNotice, {})
      }
    );
  }
  var editor_notices_default = EditorNotices;

  // packages/editor/build-module/components/editor-snackbars/index.mjs
  var import_deprecated11 = __toESM(require_deprecated(), 1);
  var import_notices22 = __toESM(require_notices(), 1);
  var import_jsx_runtime394 = __toESM(require_jsx_runtime(), 1);
  function EditorSnackbars() {
    (0, import_deprecated11.default)("wp.editor.EditorSnackbars", {
      since: "7.0",
      version: "7.2",
      alternative: "wp.notices.SnackbarNotices"
    });
    return /* @__PURE__ */ (0, import_jsx_runtime394.jsx)(import_notices22.SnackbarNotices, { className: "components-editor-notices__snackbar" });
  }

  // packages/editor/build-module/components/entities-saved-states/index.mjs
  var import_components170 = __toESM(require_components(), 1);
  var import_i18n220 = __toESM(require_i18n(), 1);
  var import_element234 = __toESM(require_element(), 1);
  var import_compose39 = __toESM(require_compose(), 1);
  var import_data110 = __toESM(require_data(), 1);

  // packages/editor/build-module/components/entities-saved-states/entity-type-list.mjs
  var import_i18n219 = __toESM(require_i18n(), 1);
  var import_data108 = __toESM(require_data(), 1);
  var import_components169 = __toESM(require_components(), 1);
  var import_core_data67 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/entities-saved-states/entity-record-item.mjs
  var import_components168 = __toESM(require_components(), 1);
  var import_i18n218 = __toESM(require_i18n(), 1);
  var import_data107 = __toESM(require_data(), 1);
  var import_core_data66 = __toESM(require_core_data(), 1);
  var import_html_entities17 = __toESM(require_html_entities(), 1);
  var import_jsx_runtime395 = __toESM(require_jsx_runtime(), 1);
  function EntityRecordItem({ record, checked, onChange }) {
    const { name: name2, kind, title, key } = record;
    const { entityRecordTitle, hasPostMetaChanges: hasPostMetaChanges2 } = (0, import_data107.useSelect)(
      (select9) => {
        if ("postType" !== kind || "wp_template" !== name2) {
          return {
            entityRecordTitle: title,
            hasPostMetaChanges: unlock(
              select9(store)
            ).hasPostMetaChanges(name2, key)
          };
        }
        const template2 = select9(import_core_data66.store).getEditedEntityRecord(
          kind,
          name2,
          key
        );
        const { default_template_types: templateTypes = [] } = select9(import_core_data66.store).getCurrentTheme() ?? {};
        return {
          entityRecordTitle: getTemplateInfo({
            template: template2,
            templateTypes
          }).title,
          hasPostMetaChanges: unlock(
            select9(store)
          ).hasPostMetaChanges(name2, key)
        };
      },
      [name2, kind, title, key]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime395.jsxs)(import_jsx_runtime395.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime395.jsx)(import_components168.PanelRow, { children: /* @__PURE__ */ (0, import_jsx_runtime395.jsx)(
        import_components168.CheckboxControl,
        {
          label: (0, import_html_entities17.decodeEntities)(entityRecordTitle) || (0, import_i18n218.__)("Untitled"),
          checked,
          onChange,
          className: "entities-saved-states__change-control"
        }
      ) }),
      hasPostMetaChanges2 && /* @__PURE__ */ (0, import_jsx_runtime395.jsx)("ul", { className: "entities-saved-states__changes", children: /* @__PURE__ */ (0, import_jsx_runtime395.jsx)("li", { children: (0, import_i18n218.__)("Post Meta.") }) })
    ] });
  }

  // packages/editor/build-module/components/entities-saved-states/entity-type-list.mjs
  var import_jsx_runtime396 = __toESM(require_jsx_runtime(), 1);
  function getEntityDescription(entity, count) {
    switch (entity) {
      case "site":
        return 1 === count ? (0, import_i18n219.__)("This change will affect your whole site.") : (0, import_i18n219.__)("These changes will affect your whole site.");
      case "wp_template":
        return (0, import_i18n219.__)(
          "This change will affect other parts of your site that use this template."
        );
      case "page":
      case "post":
        return (0, import_i18n219.__)("The following has been modified.");
    }
  }
  function GlobalStylesDescription({ record }) {
    const { editedRecord, savedRecord } = (0, import_data108.useSelect)(
      (select9) => {
        const { getEditedEntityRecord, getEntityRecord } = select9(import_core_data67.store);
        return {
          editedRecord: getEditedEntityRecord(
            record.kind,
            record.name,
            record.key
          ),
          savedRecord: getEntityRecord(
            record.kind,
            record.name,
            record.key
          )
        };
      },
      [record.kind, record.name, record.key]
    );
    const globalStylesChanges = getGlobalStylesChanges(
      editedRecord,
      savedRecord,
      {
        maxResults: 10
      }
    );
    return globalStylesChanges.length ? /* @__PURE__ */ (0, import_jsx_runtime396.jsx)("ul", { className: "entities-saved-states__changes", children: globalStylesChanges.map((change) => /* @__PURE__ */ (0, import_jsx_runtime396.jsx)("li", { children: change }, change)) }) : null;
  }
  function EntityDescription({ record, count }) {
    if ("globalStyles" === record?.name) {
      return null;
    }
    const description = getEntityDescription(record?.name, count);
    return description ? /* @__PURE__ */ (0, import_jsx_runtime396.jsx)(import_components169.PanelRow, { children: description }) : null;
  }
  function EntityTypeList({
    list,
    unselectedEntities,
    setUnselectedEntities
  }) {
    const count = list.length;
    const firstRecord = list[0];
    const entityConfig = (0, import_data108.useSelect)(
      (select9) => select9(import_core_data67.store).getEntityConfig(
        firstRecord.kind,
        firstRecord.name
      ),
      [firstRecord.kind, firstRecord.name]
    );
    let entityLabel = entityConfig.label;
    if (firstRecord?.name === "wp_template_part") {
      entityLabel = 1 === count ? (0, import_i18n219.__)("Template Part") : (0, import_i18n219.__)("Template Parts");
    }
    return /* @__PURE__ */ (0, import_jsx_runtime396.jsxs)(
      import_components169.PanelBody,
      {
        title: entityLabel,
        initialOpen: true,
        className: "entities-saved-states__panel-body",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime396.jsx)(EntityDescription, { record: firstRecord, count }),
          list.map((record) => {
            return /* @__PURE__ */ (0, import_jsx_runtime396.jsx)(
              EntityRecordItem,
              {
                record,
                checked: !unselectedEntities.some(
                  (elt) => elt.kind === record.kind && elt.name === record.name && elt.key === record.key && elt.property === record.property
                ),
                onChange: (value) => setUnselectedEntities(record, value)
              },
              record.key || record.property
            );
          }),
          "globalStyles" === firstRecord?.name && /* @__PURE__ */ (0, import_jsx_runtime396.jsx)(GlobalStylesDescription, { record: firstRecord })
        ]
      }
    );
  }

  // packages/editor/build-module/components/entities-saved-states/hooks/use-is-dirty.mjs
  var import_data109 = __toESM(require_data(), 1);
  var import_core_data68 = __toESM(require_core_data(), 1);
  var import_element233 = __toESM(require_element(), 1);
  var useIsDirty = () => {
    const { editedEntities, siteEdits, siteEntityConfig } = (0, import_data109.useSelect)(
      (select9) => {
        const {
          __experimentalGetDirtyEntityRecords,
          getEntityRecordEdits,
          getEntityConfig
        } = select9(import_core_data68.store);
        return {
          editedEntities: __experimentalGetDirtyEntityRecords(),
          siteEdits: getEntityRecordEdits("root", "site"),
          siteEntityConfig: getEntityConfig("root", "site")
        };
      },
      []
    );
    const dirtyEntityRecords = (0, import_element233.useMemo)(() => {
      const editedEntitiesWithoutSite = editedEntities.filter(
        (record) => !(record.kind === "root" && record.name === "site")
      );
      const siteEntityLabels = siteEntityConfig?.meta?.labels ?? {};
      const {
        title: siteTitleEdit,
        description: siteDescriptionEdit,
        site_logo: siteLogoEdit,
        site_icon: siteIconEdit,
        ...otherSiteEdits
      } = siteEdits ?? {};
      const orderedSiteProperties = [
        siteTitleEdit !== void 0 && "title",
        siteDescriptionEdit !== void 0 && "description",
        siteLogoEdit !== void 0 && "site_logo",
        siteIconEdit !== void 0 && "site_icon",
        ...Object.keys(otherSiteEdits)
      ].filter(Boolean);
      const editedSiteEntities = orderedSiteProperties.map(
        (property) => ({
          kind: "root",
          name: "site",
          title: siteEntityLabels[property] || property,
          property
        })
      );
      return [...editedEntitiesWithoutSite, ...editedSiteEntities];
    }, [editedEntities, siteEdits, siteEntityConfig]);
    const [unselectedEntities, _setUnselectedEntities] = (0, import_element233.useState)([]);
    const setUnselectedEntities = ({ kind, name: name2, key, property }, checked) => {
      if (checked) {
        _setUnselectedEntities(
          unselectedEntities.filter(
            (elt) => elt.kind !== kind || elt.name !== name2 || elt.key !== key || elt.property !== property
          )
        );
      } else {
        _setUnselectedEntities([
          ...unselectedEntities,
          { kind, name: name2, key, property }
        ]);
      }
    };
    const isDirty = dirtyEntityRecords.length - unselectedEntities.length > 0;
    return {
      dirtyEntityRecords,
      isDirty,
      setUnselectedEntities,
      unselectedEntities
    };
  };

  // packages/editor/build-module/components/entities-saved-states/index.mjs
  var import_jsx_runtime397 = __toESM(require_jsx_runtime(), 1);
  function EntitiesSavedStates({
    close,
    renderDialog,
    variant
  }) {
    const isDirtyProps = useIsDirty();
    return /* @__PURE__ */ (0, import_jsx_runtime397.jsx)(
      EntitiesSavedStatesExtensible,
      {
        close,
        renderDialog,
        variant,
        ...isDirtyProps
      }
    );
  }
  function EntitiesSavedStatesExtensible({
    additionalPrompt = void 0,
    close,
    onSave = void 0,
    saveEnabled: saveEnabledProp = void 0,
    saveLabel = (0, import_i18n220.__)("Save"),
    renderDialog,
    dirtyEntityRecords,
    isDirty,
    setUnselectedEntities,
    unselectedEntities,
    variant = "default",
    successNoticeContent
  }) {
    const saveButtonRef = (0, import_element234.useRef)();
    const { saveDirtyEntities: saveDirtyEntities2 } = unlock((0, import_data110.useDispatch)(store));
    const partitionedSavables = dirtyEntityRecords.reduce((acc, record) => {
      const { name: name2 } = record;
      if (!acc[name2]) {
        acc[name2] = [];
      }
      acc[name2].push(record);
      return acc;
    }, {});
    const {
      site: siteSavables,
      wp_template: templateSavables,
      wp_template_part: templatePartSavables,
      ...contentSavables
    } = partitionedSavables;
    const sortedPartitionedSavables = [
      siteSavables,
      templateSavables,
      templatePartSavables,
      ...Object.values(contentSavables)
    ].filter(Array.isArray);
    const saveEnabled = saveEnabledProp ?? isDirty;
    const dismissPanel = (0, import_element234.useCallback)(() => close(), [close]);
    const [saveDialogRef, saveDialogProps] = (0, import_compose39.__experimentalUseDialog)({
      onClose: () => dismissPanel()
    });
    const dialogLabelId = (0, import_compose39.useInstanceId)(
      EntitiesSavedStatesExtensible,
      "entities-saved-states__panel-label"
    );
    const dialogDescriptionId = (0, import_compose39.useInstanceId)(
      EntitiesSavedStatesExtensible,
      "entities-saved-states__panel-description"
    );
    const selectItemsToSaveDescription = !!dirtyEntityRecords.length ? (0, import_i18n220.__)("Select the items you want to save.") : void 0;
    const isInline = variant === "inline";
    const actionButtons = /* @__PURE__ */ (0, import_jsx_runtime397.jsxs)(import_jsx_runtime397.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime397.jsx)(
        import_components170.FlexItem,
        {
          isBlock: isInline ? false : true,
          as: import_components170.Button,
          variant: isInline ? "tertiary" : "secondary",
          size: isInline ? void 0 : "compact",
          onClick: dismissPanel,
          children: (0, import_i18n220.__)("Cancel")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime397.jsx)(
        import_components170.FlexItem,
        {
          isBlock: isInline ? false : true,
          as: import_components170.Button,
          ref: saveButtonRef,
          variant: "primary",
          size: isInline ? void 0 : "compact",
          disabled: !saveEnabled,
          accessibleWhenDisabled: true,
          onClick: () => saveDirtyEntities2({
            onSave,
            dirtyEntityRecords,
            entitiesToSkip: unselectedEntities,
            close,
            successNoticeContent
          }),
          className: "editor-entities-saved-states__save-button",
          children: saveLabel
        }
      )
    ] });
    return /* @__PURE__ */ (0, import_jsx_runtime397.jsxs)(
      "div",
      {
        ref: renderDialog ? saveDialogRef : void 0,
        ...renderDialog && saveDialogProps,
        className: clsx_default("entities-saved-states__panel", {
          "is-inline": isInline
        }),
        role: renderDialog ? "dialog" : void 0,
        "aria-labelledby": renderDialog ? dialogLabelId : void 0,
        "aria-describedby": renderDialog ? dialogDescriptionId : void 0,
        children: [
          !isInline && /* @__PURE__ */ (0, import_jsx_runtime397.jsx)(import_components170.Flex, { className: "entities-saved-states__panel-header", gap: 2, children: actionButtons }),
          /* @__PURE__ */ (0, import_jsx_runtime397.jsxs)("div", { className: "entities-saved-states__text-prompt", children: [
            /* @__PURE__ */ (0, import_jsx_runtime397.jsx)("div", { className: "entities-saved-states__text-prompt--header-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime397.jsx)(
              "strong",
              {
                id: renderDialog ? dialogLabelId : void 0,
                className: "entities-saved-states__text-prompt--header",
                children: (0, import_i18n220.__)("Are you ready to save?")
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime397.jsxs)("div", { id: renderDialog ? dialogDescriptionId : void 0, children: [
              additionalPrompt,
              /* @__PURE__ */ (0, import_jsx_runtime397.jsx)("p", { className: "entities-saved-states__text-prompt--changes-count", children: isDirty ? (0, import_element234.createInterpolateElement)(
                (0, import_i18n220.sprintf)(
                  /* translators: %d: number of site changes waiting to be saved. */
                  (0, import_i18n220._n)(
                    "There is <strong>%d site change</strong> waiting to be saved.",
                    "There are <strong>%d site changes</strong> waiting to be saved.",
                    dirtyEntityRecords.length
                  ),
                  dirtyEntityRecords.length
                ),
                { strong: /* @__PURE__ */ (0, import_jsx_runtime397.jsx)("strong", {}) }
              ) : selectItemsToSaveDescription })
            ] })
          ] }),
          sortedPartitionedSavables.map((list) => {
            return /* @__PURE__ */ (0, import_jsx_runtime397.jsx)(
              EntityTypeList,
              {
                list,
                unselectedEntities,
                setUnselectedEntities
              },
              list[0].name
            );
          }),
          isInline && /* @__PURE__ */ (0, import_jsx_runtime397.jsx)(
            import_components170.Flex,
            {
              direction: "row",
              justify: "flex-end",
              className: "entities-saved-states__panel-footer",
              children: actionButtons
            }
          )
        ]
      }
    );
  }

  // packages/editor/build-module/components/error-boundary/index.mjs
  var import_element235 = __toESM(require_element(), 1);
  var import_i18n221 = __toESM(require_i18n(), 1);
  var import_components171 = __toESM(require_components(), 1);
  var import_data111 = __toESM(require_data(), 1);
  var import_compose40 = __toESM(require_compose(), 1);
  var import_hooks43 = __toESM(require_hooks(), 1);
  var import_jsx_runtime398 = __toESM(require_jsx_runtime(), 1);
  function getContent() {
    try {
      return (0, import_data111.select)(store).getEditedPostContent();
    } catch {
    }
  }
  function CopyButton({ text, children, variant = "secondary" }) {
    const ref = (0, import_compose40.useCopyToClipboard)(text);
    return /* @__PURE__ */ (0, import_jsx_runtime398.jsx)(import_components171.Button, { __next40pxDefaultSize: true, variant, ref, children });
  }
  var ErrorBoundary = class extends import_element235.Component {
    constructor() {
      super(...arguments);
      this.state = {
        error: null
      };
    }
    componentDidCatch(error2) {
      (0, import_hooks43.doAction)("editor.ErrorBoundary.errorLogged", error2);
    }
    static getDerivedStateFromError(error2) {
      return { error: error2 };
    }
    render() {
      const { error: error2 } = this.state;
      const { canCopyContent = false } = this.props;
      if (!error2) {
        return this.props.children;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime398.jsxs)(
        import_components171.__experimentalHStack,
        {
          className: "editor-error-boundary",
          alignment: "baseline",
          spacing: 4,
          justify: "space-between",
          expanded: false,
          wrap: true,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime398.jsx)(import_components171.__experimentalText, { as: "p", children: (0, import_i18n221.__)("The editor has encountered an unexpected error.") }),
            /* @__PURE__ */ (0, import_jsx_runtime398.jsxs)(import_components171.__experimentalHStack, { expanded: false, children: [
              canCopyContent && /* @__PURE__ */ (0, import_jsx_runtime398.jsx)(CopyButton, { text: getContent, children: (0, import_i18n221.__)("Copy contents") }),
              /* @__PURE__ */ (0, import_jsx_runtime398.jsx)(CopyButton, { variant: "primary", text: error2?.stack, children: (0, import_i18n221.__)("Copy error") })
            ] })
          ]
        }
      );
    }
  };
  var error_boundary_default = ErrorBoundary;

  // packages/editor/build-module/components/local-autosave-monitor/index.mjs
  var import_element236 = __toESM(require_element(), 1);
  var import_compose41 = __toESM(require_compose(), 1);
  var import_data112 = __toESM(require_data(), 1);
  var import_i18n222 = __toESM(require_i18n(), 1);
  var import_blocks24 = __toESM(require_blocks(), 1);
  var import_notices23 = __toESM(require_notices(), 1);
  var import_jsx_runtime399 = __toESM(require_jsx_runtime(), 1);
  var requestIdleCallback = window.requestIdleCallback ? window.requestIdleCallback : window.requestAnimationFrame;
  var hasStorageSupport;
  var hasSessionStorageSupport = () => {
    if (hasStorageSupport !== void 0) {
      return hasStorageSupport;
    }
    try {
      window.sessionStorage.setItem("__wpEditorTestSessionStorage", "");
      window.sessionStorage.removeItem("__wpEditorTestSessionStorage");
      hasStorageSupport = true;
    } catch {
      hasStorageSupport = false;
    }
    return hasStorageSupport;
  };
  function useAutosaveNotice() {
    const registry = (0, import_data112.useRegistry)();
    const { postId: postId2, isEditedPostNew: isEditedPostNew2 } = (0, import_data112.useSelect)(
      (select9) => ({
        postId: select9(store).getCurrentPostId(),
        isEditedPostNew: select9(store).isEditedPostNew()
      }),
      []
    );
    (0, import_element236.useEffect)(() => {
      let localAutosave = localAutosaveGet(postId2, isEditedPostNew2);
      if (!localAutosave) {
        return;
      }
      try {
        localAutosave = JSON.parse(localAutosave);
      } catch {
        return;
      }
      const { post_title: title, content, excerpt } = localAutosave;
      const edits = { title, content, excerpt };
      const { getEditedPostAttribute: getEditedPostAttribute2, getEditorSettings: getEditorSettings2 } = registry.select(store);
      const hasDifference = Object.keys(edits).some((key) => {
        return edits[key] !== getEditedPostAttribute2(key);
      });
      if (!hasDifference) {
        localAutosaveClear(postId2, isEditedPostNew2);
        return;
      }
      const hasRemoteAutosave = !!getEditorSettings2().autosave;
      if (hasRemoteAutosave) {
        return;
      }
      const { createWarningNotice, removeNotice } = registry.dispatch(import_notices23.store);
      const { editPost: editPost2, resetEditorBlocks: resetEditorBlocks2 } = registry.dispatch(store);
      const id = "wpEditorAutosaveRestore";
      createWarningNotice(
        (0, import_i18n222.__)(
          "The backup of this post in your browser is different from the version below."
        ),
        {
          id,
          actions: [
            {
              label: (0, import_i18n222.__)("Restore the backup"),
              onClick() {
                const {
                  content: editsContent,
                  ...editsWithoutContent
                } = edits;
                editPost2(editsWithoutContent);
                resetEditorBlocks2((0, import_blocks24.parse)(edits.content));
                removeNotice(id);
              }
            }
          ]
        }
      );
    }, [registry, postId2, isEditedPostNew2]);
  }
  function useAutosavePurge() {
    const { postId: postId2, isEditedPostNew: isEditedPostNew2, isDirty, isAutosaving, didError } = (0, import_data112.useSelect)(
      (select9) => ({
        postId: select9(store).getCurrentPostId(),
        isEditedPostNew: select9(store).isEditedPostNew(),
        isDirty: select9(store).isEditedPostDirty(),
        isAutosaving: select9(store).isAutosavingPost(),
        didError: select9(store).didPostSaveRequestFail()
      }),
      []
    );
    const lastIsDirtyRef = (0, import_element236.useRef)(isDirty);
    const lastIsAutosavingRef = (0, import_element236.useRef)(isAutosaving);
    (0, import_element236.useEffect)(() => {
      if (!didError && (lastIsAutosavingRef.current && !isAutosaving || lastIsDirtyRef.current && !isDirty)) {
        localAutosaveClear(postId2, isEditedPostNew2);
      }
      lastIsDirtyRef.current = isDirty;
      lastIsAutosavingRef.current = isAutosaving;
    }, [isDirty, isAutosaving, didError]);
    const wasEditedPostNew = (0, import_compose41.usePrevious)(isEditedPostNew2);
    const prevPostId = (0, import_compose41.usePrevious)(postId2);
    (0, import_element236.useEffect)(() => {
      if (prevPostId === postId2 && wasEditedPostNew && !isEditedPostNew2) {
        localAutosaveClear(postId2, true);
      }
    }, [isEditedPostNew2, postId2]);
  }
  function LocalAutosaveMonitor() {
    const { autosave: autosave2 } = (0, import_data112.useDispatch)(store);
    const deferredAutosave = (0, import_element236.useCallback)(() => {
      requestIdleCallback(() => autosave2({ local: true }));
    }, []);
    useAutosaveNotice();
    useAutosavePurge();
    const localAutosaveInterval = (0, import_data112.useSelect)(
      (select9) => select9(store).getEditorSettings().localAutosaveInterval,
      []
    );
    return /* @__PURE__ */ (0, import_jsx_runtime399.jsx)(
      AutosaveMonitor,
      {
        interval: localAutosaveInterval,
        autosave: deferredAutosave
      }
    );
  }
  var local_autosave_monitor_default = (0, import_compose41.ifCondition)(hasSessionStorageSupport)(LocalAutosaveMonitor);

  // packages/editor/build-module/components/page-attributes/check.mjs
  var import_data113 = __toESM(require_data(), 1);
  var import_core_data69 = __toESM(require_core_data(), 1);
  function PageAttributesCheck({ children }) {
    const supportsPageAttributes = (0, import_data113.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
      const { getPostType } = select9(import_core_data69.store);
      const postType2 = getPostType(getEditedPostAttribute2("type"));
      return !!postType2?.supports?.["page-attributes"];
    }, []);
    if (!supportsPageAttributes) {
      return null;
    }
    return children;
  }
  var check_default2 = PageAttributesCheck;

  // packages/editor/build-module/components/page-attributes/order.mjs
  var import_i18n223 = __toESM(require_i18n(), 1);
  var import_components172 = __toESM(require_components(), 1);
  var import_data115 = __toESM(require_data(), 1);
  var import_element237 = __toESM(require_element(), 1);

  // packages/editor/build-module/components/post-type-support-check/index.mjs
  var import_data114 = __toESM(require_data(), 1);
  var import_core_data70 = __toESM(require_core_data(), 1);
  function checkSupport(supports = {}, key) {
    if (supports[key] !== void 0) {
      return !!supports[key];
    }
    const [topKey, subKey] = key.split(".");
    const [subProperties] = Array.isArray(supports[topKey]) ? supports[topKey] : [];
    return Array.isArray(subProperties) ? subProperties.includes(subKey) : !!subProperties?.[subKey];
  }
  function PostTypeSupportCheck({ children, supportKeys }) {
    const postType2 = (0, import_data114.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
      const { getPostType } = select9(import_core_data70.store);
      return getPostType(getEditedPostAttribute2("type"));
    }, []);
    let isSupported = !!postType2;
    if (postType2) {
      isSupported = (Array.isArray(supportKeys) ? supportKeys : [supportKeys]).some((key) => checkSupport(postType2.supports, key));
    }
    if (!isSupported) {
      return null;
    }
    return children;
  }
  var post_type_support_check_default = PostTypeSupportCheck;

  // packages/editor/build-module/components/page-attributes/order.mjs
  var import_jsx_runtime400 = __toESM(require_jsx_runtime(), 1);
  function PageAttributesOrder() {
    const order = (0, import_data115.useSelect)(
      (select9) => select9(store).getEditedPostAttribute("menu_order") ?? 0,
      []
    );
    const { editPost: editPost2 } = (0, import_data115.useDispatch)(store);
    const [orderInput, setOrderInput] = (0, import_element237.useState)(null);
    const setUpdatedOrder = (value2) => {
      setOrderInput(value2);
      const newOrder = Number(value2);
      if (Number.isInteger(newOrder) && value2.trim?.() !== "") {
        editPost2({ menu_order: newOrder });
      }
    };
    const value = orderInput ?? order;
    return /* @__PURE__ */ (0, import_jsx_runtime400.jsx)(import_components172.Flex, { children: /* @__PURE__ */ (0, import_jsx_runtime400.jsx)(import_components172.FlexBlock, { children: /* @__PURE__ */ (0, import_jsx_runtime400.jsx)(
      import_components172.__experimentalNumberControl,
      {
        label: (0, import_i18n223.__)("Order"),
        help: (0, import_i18n223.__)("Set the page order."),
        value,
        onChange: setUpdatedOrder,
        hideLabelFromVision: true,
        onBlur: () => {
          setOrderInput(null);
        }
      }
    ) }) });
  }
  function PageAttributesOrderWithChecks() {
    return /* @__PURE__ */ (0, import_jsx_runtime400.jsx)(post_type_support_check_default, { supportKeys: "page-attributes", children: /* @__PURE__ */ (0, import_jsx_runtime400.jsx)(PageAttributesOrder, {}) });
  }

  // packages/editor/build-module/components/page-attributes/panel.mjs
  var import_data117 = __toESM(require_data(), 1);
  var import_core_data72 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/page-attributes/parent.mjs
  var import_remove_accents4 = __toESM(require_remove_accents(), 1);
  var import_i18n224 = __toESM(require_i18n(), 1);
  var import_components174 = __toESM(require_components(), 1);
  var import_compose42 = __toESM(require_compose(), 1);
  var import_element239 = __toESM(require_element(), 1);
  var import_data116 = __toESM(require_data(), 1);
  var import_html_entities19 = __toESM(require_html_entities(), 1);
  var import_core_data71 = __toESM(require_core_data(), 1);
  var import_block_editor47 = __toESM(require_block_editor(), 1);
  var import_url16 = __toESM(require_url(), 1);

  // packages/editor/build-module/components/post-panel-row/index.mjs
  var import_components173 = __toESM(require_components(), 1);
  var import_element238 = __toESM(require_element(), 1);
  var import_jsx_runtime401 = __toESM(require_jsx_runtime(), 1);
  var PostPanelRow = (0, import_element238.forwardRef)(({ className, label, children }, ref) => {
    return /* @__PURE__ */ (0, import_jsx_runtime401.jsxs)(
      import_components173.__experimentalHStack,
      {
        className: clsx_default("editor-post-panel__row", className),
        ref,
        children: [
          label && /* @__PURE__ */ (0, import_jsx_runtime401.jsx)("div", { className: "editor-post-panel__row-label", children: label }),
          /* @__PURE__ */ (0, import_jsx_runtime401.jsx)("div", { className: "editor-post-panel__row-control", children })
        ]
      }
    );
  });
  var post_panel_row_default = PostPanelRow;

  // packages/editor/build-module/utils/terms.mjs
  var import_html_entities18 = __toESM(require_html_entities(), 1);
  function buildTermsTree2(flatTerms) {
    const flatTermsWithParentAndChildren = flatTerms.map((term) => {
      return {
        children: [],
        parent: void 0,
        ...term
      };
    });
    if (flatTermsWithParentAndChildren.some(
      ({ parent }) => parent === void 0
    )) {
      return flatTermsWithParentAndChildren;
    }
    const termsByParent = flatTermsWithParentAndChildren.reduce(
      (acc, term) => {
        const { parent } = term;
        if (!acc[parent]) {
          acc[parent] = [];
        }
        acc[parent].push(term);
        return acc;
      },
      {}
    );
    const fillWithChildren = (terms) => {
      return terms.map((term) => {
        const children = termsByParent[term.id];
        return {
          ...term,
          children: children && children.length ? fillWithChildren(children) : []
        };
      });
    };
    return fillWithChildren(termsByParent["0"] || []);
  }
  var unescapeString = (arg) => {
    return (0, import_html_entities18.decodeEntities)(arg);
  };
  var unescapeTerm = (term) => {
    return {
      ...term,
      name: unescapeString(term.name)
    };
  };
  var unescapeTerms = (terms) => {
    return (terms ?? []).map(unescapeTerm);
  };

  // packages/editor/build-module/components/page-attributes/parent.mjs
  var import_jsx_runtime402 = __toESM(require_jsx_runtime(), 1);
  function getTitle(post2) {
    return post2?.title?.rendered ? (0, import_html_entities19.decodeEntities)(post2.title.rendered) : `#${post2.id} (${(0, import_i18n224.__)("no title")})`;
  }
  var getItemPriority2 = (name2, searchValue) => {
    const normalizedName = (0, import_remove_accents4.default)(name2 || "").toLowerCase();
    const normalizedSearch = (0, import_remove_accents4.default)(searchValue || "").toLowerCase();
    if (normalizedName === normalizedSearch) {
      return 0;
    }
    if (normalizedName.startsWith(normalizedSearch)) {
      return normalizedName.length;
    }
    return Infinity;
  };
  function PageAttributesParent2() {
    const { editPost: editPost2 } = (0, import_data116.useDispatch)(store);
    const [fieldValue, setFieldValue] = (0, import_element239.useState)("");
    const {
      isHierarchical,
      parentPostId,
      parentPostTitle,
      pageItems,
      isLoading
    } = (0, import_data116.useSelect)(
      (select9) => {
        const {
          getPostType,
          getEntityRecords,
          getEntityRecord,
          isResolving
        } = select9(import_core_data71.store);
        const { getCurrentPostId: getCurrentPostId2, getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
        const postTypeSlug = getEditedPostAttribute2("type");
        const pageId = getEditedPostAttribute2("parent");
        const pType = getPostType(postTypeSlug);
        const postId2 = getCurrentPostId2();
        const postIsHierarchical = pType?.hierarchical ?? false;
        const query = {
          per_page: 100,
          exclude: postId2,
          parent_exclude: postId2,
          orderby: "menu_order",
          order: "asc",
          _fields: "id,title,parent"
        };
        if (!!fieldValue) {
          query.search = fieldValue;
          query.orderby = "relevance";
          query.search_columns = ["post_title"];
        }
        const parentPost = pageId ? getEntityRecord("postType", postTypeSlug, pageId) : null;
        return {
          isHierarchical: postIsHierarchical,
          parentPostId: pageId,
          parentPostTitle: parentPost ? getTitle(parentPost) : "",
          pageItems: postIsHierarchical ? getEntityRecords("postType", postTypeSlug, query) : null,
          isLoading: postIsHierarchical ? isResolving("getEntityRecords", [
            "postType",
            postTypeSlug,
            query
          ]) : false
        };
      },
      [fieldValue]
    );
    const parentOptions = (0, import_element239.useMemo)(() => {
      const getOptionsFromTree = (tree2, level = 0) => {
        const mappedNodes = tree2.map((treeNode) => [
          {
            value: treeNode.id,
            label: "\u2014 ".repeat(level) + (0, import_html_entities19.decodeEntities)(treeNode.name),
            rawName: treeNode.name
          },
          ...getOptionsFromTree(treeNode.children || [], level + 1)
        ]);
        const sortedNodes = mappedNodes.sort(([a3], [b3]) => {
          const priorityA = getItemPriority2(a3.rawName, fieldValue);
          const priorityB = getItemPriority2(b3.rawName, fieldValue);
          return priorityA >= priorityB ? 1 : -1;
        });
        return sortedNodes.flat();
      };
      if (!pageItems) {
        return [];
      }
      let tree = pageItems.map((item) => ({
        id: item.id,
        parent: item.parent,
        name: getTitle(item)
      }));
      if (!fieldValue) {
        tree = buildTermsTree2(tree);
      }
      const opts = getOptionsFromTree(tree);
      const optsHasParent = opts.find(
        (item) => item.value === parentPostId
      );
      if (parentPostTitle && !optsHasParent) {
        opts.unshift({
          value: parentPostId,
          label: parentPostTitle
        });
      }
      return opts;
    }, [pageItems, fieldValue, parentPostTitle, parentPostId]);
    if (!isHierarchical) {
      return null;
    }
    const handleKeydown = (inputValue) => {
      setFieldValue(inputValue);
    };
    const handleChange = (selectedPostId) => {
      editPost2({ parent: selectedPostId });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime402.jsx)(
      import_components174.ComboboxControl,
      {
        className: "editor-page-attributes__parent",
        label: (0, import_i18n224.__)("Parent"),
        help: (0, import_i18n224.__)("Choose a parent page."),
        value: parentPostId,
        options: parentOptions,
        onFilterValueChange: (0, import_compose42.debounce)(handleKeydown, 300),
        onChange: handleChange,
        hideLabelFromVision: true,
        isLoading
      }
    );
  }
  function PostParentToggle({ isOpen: isOpen2, onClick }) {
    const parentPost = (0, import_data116.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
      const parentPostId = getEditedPostAttribute2("parent");
      if (!parentPostId) {
        return null;
      }
      const { getEntityRecord } = select9(import_core_data71.store);
      const postTypeSlug = getEditedPostAttribute2("type");
      return getEntityRecord("postType", postTypeSlug, parentPostId);
    }, []);
    const parentTitle = (0, import_element239.useMemo)(
      () => !parentPost ? (0, import_i18n224.__)("None") : getTitle(parentPost),
      [parentPost]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime402.jsx)(
      import_components174.Button,
      {
        size: "compact",
        className: "editor-post-parent__panel-toggle",
        variant: "tertiary",
        "aria-expanded": isOpen2,
        "aria-label": (
          // translators: %s: Current post parent.
          (0, import_i18n224.sprintf)((0, import_i18n224.__)("Change parent: %s"), parentTitle)
        ),
        onClick,
        children: parentTitle
      }
    );
  }
  function ParentRow() {
    const homeUrl = (0, import_data116.useSelect)((select9) => {
      return select9(import_core_data71.store).getEntityRecord("root", "__unstableBase")?.home;
    }, []);
    const [popoverAnchor, setPopoverAnchor] = (0, import_element239.useState)(null);
    const popoverProps = (0, import_element239.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]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime402.jsx)(post_panel_row_default, { label: (0, import_i18n224.__)("Parent"), ref: setPopoverAnchor, children: /* @__PURE__ */ (0, import_jsx_runtime402.jsx)(
      import_components174.Dropdown,
      {
        popoverProps,
        className: "editor-post-parent__panel-dropdown",
        contentClassName: "editor-post-parent__panel-dialog",
        focusOnMount: true,
        renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime402.jsx)(PostParentToggle, { isOpen: isOpen2, onClick: onToggle }),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime402.jsxs)("div", { className: "editor-post-parent", children: [
          /* @__PURE__ */ (0, import_jsx_runtime402.jsx)(
            import_block_editor47.__experimentalInspectorPopoverHeader,
            {
              title: (0, import_i18n224.__)("Parent"),
              onClose
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime402.jsxs)("div", { children: [
            (0, import_element239.createInterpolateElement)(
              (0, import_i18n224.sprintf)(
                /* translators: %s: The home URL of the WordPress installation without the scheme. */
                (0, import_i18n224.__)(
                  'Child pages inherit characteristics from their parent, such as URL structure. For instance, if "Pricing" is a child of "Services", its URL would be %s<wbr />/services<wbr />/pricing.'
                ),
                (0, import_url16.filterURLForDisplay)(homeUrl).replace(
                  /([/.])/g,
                  "<wbr />$1"
                )
              ),
              {
                wbr: /* @__PURE__ */ (0, import_jsx_runtime402.jsx)("wbr", {})
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime402.jsx)("p", { children: (0, import_element239.createInterpolateElement)(
              (0, import_i18n224.__)(
                "They also show up as sub-items in the default navigation menu. <a>Learn more.</a>"
              ),
              {
                a: /* @__PURE__ */ (0, import_jsx_runtime402.jsx)(
                  import_components174.ExternalLink,
                  {
                    href: (0, import_i18n224.__)(
                      "https://wordpress.org/documentation/article/page-post-settings-sidebar/#page-attributes"
                    )
                  }
                )
              }
            ) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime402.jsx)(PageAttributesParent2, {})
        ] })
      }
    ) });
  }
  var parent_default2 = PageAttributesParent2;

  // packages/editor/build-module/components/page-attributes/panel.mjs
  var import_jsx_runtime403 = __toESM(require_jsx_runtime(), 1);
  var PANEL_NAME = "page-attributes";
  function AttributesPanel() {
    const { isEnabled, postType: postType2 } = (0, import_data117.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2, isEditorPanelEnabled: isEditorPanelEnabled2 } = select9(store);
      const { getPostType } = select9(import_core_data72.store);
      return {
        isEnabled: isEditorPanelEnabled2(PANEL_NAME),
        postType: getPostType(getEditedPostAttribute2("type"))
      };
    }, []);
    if (!isEnabled || !postType2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime403.jsx)(ParentRow, {});
  }
  function PageAttributesPanel() {
    return /* @__PURE__ */ (0, import_jsx_runtime403.jsx)(check_default2, { children: /* @__PURE__ */ (0, import_jsx_runtime403.jsx)(AttributesPanel, {}) });
  }

  // packages/editor/build-module/components/post-template/classic-theme.mjs
  var import_i18n227 = __toESM(require_i18n(), 1);
  var import_components176 = __toESM(require_components(), 1);
  var import_data120 = __toESM(require_data(), 1);
  var import_core_data74 = __toESM(require_core_data(), 1);
  var import_block_editor48 = __toESM(require_block_editor(), 1);
  var import_element242 = __toESM(require_element(), 1);
  var import_notices24 = __toESM(require_notices(), 1);

  // packages/editor/build-module/components/post-template/create-new-template-modal.mjs
  var import_data118 = __toESM(require_data(), 1);
  var import_element240 = __toESM(require_element(), 1);
  var import_blocks25 = __toESM(require_blocks(), 1);
  var import_components175 = __toESM(require_components(), 1);
  var import_i18n225 = __toESM(require_i18n(), 1);
  var import_jsx_runtime404 = __toESM(require_jsx_runtime(), 1);
  var DEFAULT_TITLE = (0, import_i18n225.__)("Custom Template");
  function CreateNewTemplateModal({ onClose }) {
    const { defaultBlockTemplate, onNavigateToEntityRecord } = (0, import_data118.useSelect)(
      (select9) => {
        const { getEditorSettings: getEditorSettings2, getCurrentTemplateId: getCurrentTemplateId2 } = select9(store);
        return {
          defaultBlockTemplate: getEditorSettings2().defaultBlockTemplate,
          onNavigateToEntityRecord: getEditorSettings2().onNavigateToEntityRecord,
          getTemplateId: getCurrentTemplateId2
        };
      }
    );
    const { createTemplate: createTemplate2 } = unlock((0, import_data118.useDispatch)(store));
    const [title, setTitle] = (0, import_element240.useState)("");
    const [isBusy, setIsBusy] = (0, import_element240.useState)(false);
    const cancel = () => {
      setTitle("");
      onClose();
    };
    const submit = async (event) => {
      event.preventDefault();
      if (isBusy) {
        return;
      }
      setIsBusy(true);
      const newTemplateContent = defaultBlockTemplate ?? (0, import_blocks25.serialize)([
        (0, import_blocks25.createBlock)(
          "core/group",
          {
            tagName: "header",
            layout: { inherit: true }
          },
          [
            (0, import_blocks25.createBlock)("core/site-title"),
            (0, import_blocks25.createBlock)("core/site-tagline")
          ]
        ),
        (0, import_blocks25.createBlock)("core/separator"),
        (0, import_blocks25.createBlock)(
          "core/group",
          {
            tagName: "main"
          },
          [
            (0, import_blocks25.createBlock)(
              "core/group",
              {
                layout: { inherit: true }
              },
              [(0, import_blocks25.createBlock)("core/post-title")]
            ),
            (0, import_blocks25.createBlock)("core/post-content", {
              layout: { inherit: true }
            })
          ]
        )
      ]);
      const newTemplate = await createTemplate2({
        slug: paramCase(title || DEFAULT_TITLE) || "wp-custom-template",
        content: newTemplateContent,
        title: title || DEFAULT_TITLE,
        status: "publish"
      });
      setIsBusy(false);
      onNavigateToEntityRecord({
        postId: newTemplate.id,
        postType: "wp_template"
      });
      cancel();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
      import_components175.Modal,
      {
        title: (0, import_i18n225.__)("Create custom template"),
        onRequestClose: cancel,
        focusOnMount: "firstContentElement",
        size: "small",
        overlayClassName: "editor-post-template__create-template-modal",
        children: /* @__PURE__ */ (0, import_jsx_runtime404.jsx)("form", { onSubmit: submit, children: /* @__PURE__ */ (0, import_jsx_runtime404.jsxs)(import_components175.__experimentalVStack, { spacing: "3", children: [
          /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
            import_components175.TextControl,
            {
              label: (0, import_i18n225.__)("Name"),
              value: title,
              onChange: setTitle,
              placeholder: DEFAULT_TITLE,
              disabled: isBusy,
              help: (0, import_i18n225.__)(
                // 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_runtime404.jsxs)(import_components175.__experimentalHStack, { justify: "right", children: [
            /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
              import_components175.Button,
              {
                __next40pxDefaultSize: true,
                variant: "tertiary",
                onClick: cancel,
                children: (0, import_i18n225.__)("Cancel")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime404.jsx)(
              import_components175.Button,
              {
                __next40pxDefaultSize: true,
                variant: "primary",
                type: "submit",
                isBusy,
                "aria-disabled": isBusy,
                children: (0, import_i18n225.__)("Create")
              }
            )
          ] })
        ] }) })
      }
    );
  }

  // packages/editor/build-module/components/post-template/hooks.mjs
  var import_data119 = __toESM(require_data(), 1);
  var import_element241 = __toESM(require_element(), 1);
  var import_core_data73 = __toESM(require_core_data(), 1);
  var import_i18n226 = __toESM(require_i18n(), 1);
  function useEditedPostContext() {
    return (0, import_data119.useSelect)((select9) => {
      const { getCurrentPostId: getCurrentPostId2, getCurrentPostType: getCurrentPostType2 } = select9(store);
      return {
        postId: getCurrentPostId2(),
        postType: getCurrentPostType2()
      };
    }, []);
  }
  function useAllowSwitchingTemplates() {
    const { postType: postType2, postId: postId2 } = useEditedPostContext();
    return (0, import_data119.useSelect)(
      (select9) => {
        const { canUser, getEntityRecord, getEntityRecords } = select9(import_core_data73.store);
        const siteSettings = canUser("read", {
          kind: "root",
          name: "site"
        }) ? getEntityRecord("root", "site") : void 0;
        const isPostsPage = +postId2 === siteSettings?.page_for_posts;
        const isFrontPage = postType2 === "page" && +postId2 === siteSettings?.page_on_front;
        const templates = isFrontPage ? getEntityRecords("postType", "wp_template", {
          per_page: -1
        }) : [];
        const hasFrontPage = isFrontPage && !!templates?.some(({ slug }) => slug === "front-page");
        return !isPostsPage && !hasFrontPage;
      },
      [postId2, postType2]
    );
  }
  function useTemplates(postType2) {
    return (0, import_data119.useSelect)(
      (select9) => select9(import_core_data73.store).getEntityRecords("postType", "wp_template", {
        per_page: -1,
        post_type: postType2
        // We look at the combined templates for now (old endpoint)
        // because posts only accept slugs for templates, not IDs.
      }),
      [postType2]
    );
  }
  function useAvailableTemplates() {
    const { postType: postType2, postId: postId2 } = useEditedPostContext();
    const [postSlug] = (0, import_core_data73.useEntityProp)("postType", postType2, "slug", postId2);
    const currentTemplateSlug = useCurrentTemplateSlug();
    const allowSwitchingTemplate = useAllowSwitchingTemplates();
    const templates = useTemplates(postType2);
    const defaultTemplate = (0, import_data119.useSelect)(
      (select9) => {
        if (!window?.__experimentalDataFormInspector) {
          return null;
        }
        if (!currentTemplateSlug) {
          return null;
        }
        const { getDefaultTemplateId, getEntityRecord } = select9(import_core_data73.store);
        let slug;
        if (postSlug) {
          slug = postType2 === "page" ? `${postType2}-${postSlug}` : `single-${postType2}-${postSlug}`;
        } else {
          slug = postType2 === "page" ? "page" : `single-${postType2}`;
        }
        const templateId2 = getDefaultTemplateId({ slug });
        if (!templateId2) {
          return null;
        }
        return getEntityRecord("postType", "wp_template", templateId2);
      },
      [currentTemplateSlug, postSlug, postType2]
    );
    return (0, import_element241.useMemo)(
      () => allowSwitchingTemplate && [
        ...(templates || []).filter(
          (template2) => template2.is_custom && template2.slug !== currentTemplateSlug && !!template2.content.raw
          // Skip empty templates.
        ),
        defaultTemplate && {
          ...defaultTemplate,
          title: {
            rendered: (0, import_i18n226.sprintf)(
              // translators: %s: Template name
              (0, import_i18n226.__)("%s (default)"),
              defaultTemplate.title.rendered
            )
          },
          // That's extra custom prop in order to update to an empty template
          // when we select the default template.
          isDefault: true
        }
      ].filter(Boolean),
      [
        templates,
        defaultTemplate,
        currentTemplateSlug,
        allowSwitchingTemplate
      ]
    );
  }
  function usePostTemplatePanelMode() {
    return (0, import_data119.useSelect)((select9) => {
      const { getEditorSettings: getEditorSettings2, getCurrentTemplateId: getCurrentTemplateId2, getCurrentPostType: getCurrentPostType2 } = select9(store);
      const { getPostType, canUser } = select9(import_core_data73.store);
      const postTypeSlug = getCurrentPostType2();
      const postType2 = getPostType(postTypeSlug);
      const settings = getEditorSettings2();
      const isBlockTheme = settings.__unstableIsBlockBasedTheme;
      const hasTemplates = !!settings.availableTemplates && Object.keys(settings.availableTemplates).length > 0;
      let isVisible2;
      if (!postType2?.viewable) {
        isVisible2 = false;
      } else if (hasTemplates) {
        isVisible2 = true;
      } else if (!settings.supportsTemplateMode) {
        isVisible2 = false;
      } else {
        isVisible2 = canUser("create", {
          kind: "postType",
          name: "wp_template"
        }) ?? false;
      }
      const canViewTemplates = isVisible2 ? !!canUser("read", {
        kind: "postType",
        name: "wp_template"
      }) : false;
      if ((!isBlockTheme || !canViewTemplates) && isVisible2) {
        return "classic";
      }
      if (isBlockTheme && !!getCurrentTemplateId2()) {
        return "block-theme";
      }
      return null;
    }, []);
  }
  function useCurrentTemplateSlug() {
    const { postType: postType2, postId: postId2 } = useEditedPostContext();
    const templates = useTemplates(postType2);
    const entityTemplate = (0, import_data119.useSelect)(
      (select9) => {
        const post2 = select9(import_core_data73.store).getEditedEntityRecord(
          "postType",
          postType2,
          postId2
        );
        return post2?.template;
      },
      [postType2, postId2]
    );
    if (!entityTemplate) {
      return;
    }
    return templates?.find((template2) => template2.slug === entityTemplate)?.slug;
  }

  // packages/editor/build-module/components/post-template/classic-theme.mjs
  var import_jsx_runtime405 = __toESM(require_jsx_runtime(), 1);
  function PostTemplateToggle({ isOpen: isOpen2, onClick }) {
    const templateTitle = (0, import_data120.useSelect)((select9) => {
      const templateSlug = select9(store).getEditedPostAttribute("template");
      const { supportsTemplateMode, availableTemplates } = select9(store).getEditorSettings();
      if (!supportsTemplateMode && availableTemplates[templateSlug]) {
        return availableTemplates[templateSlug];
      }
      const template2 = select9(import_core_data74.store).canUser("create", {
        kind: "postType",
        name: "wp_template"
      }) && select9(store).getCurrentTemplateId();
      return template2?.title || template2?.slug || availableTemplates?.[templateSlug];
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
      import_components176.Button,
      {
        __next40pxDefaultSize: true,
        variant: "tertiary",
        "aria-expanded": isOpen2,
        "aria-label": (0, import_i18n227.__)("Template options"),
        onClick,
        children: templateTitle ?? (0, import_i18n227.__)("Default template")
      }
    );
  }
  function PostTemplateDropdownContent({ onClose }) {
    const allowSwitchingTemplate = useAllowSwitchingTemplates();
    const {
      availableTemplates,
      fetchedTemplates,
      selectedTemplateSlug,
      canCreate,
      canEdit,
      currentTemplateId,
      onNavigateToEntityRecord,
      getEditorSettings: getEditorSettings2
    } = (0, import_data120.useSelect)(
      (select9) => {
        const { canUser, getEntityRecords } = select9(import_core_data74.store);
        const editorSettings2 = select9(store).getEditorSettings();
        const canCreateTemplates = canUser("create", {
          kind: "postType",
          name: "wp_template"
        });
        const _currentTemplateId = select9(store).getCurrentTemplateId();
        return {
          availableTemplates: editorSettings2.availableTemplates,
          fetchedTemplates: canCreateTemplates ? getEntityRecords("postType", "wp_template", {
            post_type: select9(store).getCurrentPostType(),
            per_page: -1
          }) : void 0,
          selectedTemplateSlug: select9(store).getEditedPostAttribute("template"),
          canCreate: allowSwitchingTemplate && canCreateTemplates && editorSettings2.supportsTemplateMode,
          canEdit: allowSwitchingTemplate && canCreateTemplates && editorSettings2.supportsTemplateMode && !!_currentTemplateId,
          currentTemplateId: _currentTemplateId,
          onNavigateToEntityRecord: editorSettings2.onNavigateToEntityRecord,
          getEditorSettings: select9(store).getEditorSettings
        };
      },
      [allowSwitchingTemplate]
    );
    const options = (0, import_element242.useMemo)(
      () => Object.entries({
        ...availableTemplates,
        ...Object.fromEntries(
          (fetchedTemplates ?? []).map(({ slug, title }) => [
            slug,
            title.rendered
          ])
        )
      }).map(([slug, title]) => ({ value: slug, label: title })),
      [availableTemplates, fetchedTemplates]
    );
    const selectedOption = options.find((option) => option.value === selectedTemplateSlug) ?? options.find((option) => !option.value);
    const { editPost: editPost2 } = (0, import_data120.useDispatch)(store);
    const { createSuccessNotice } = (0, import_data120.useDispatch)(import_notices24.store);
    const [isCreateModalOpen, setIsCreateModalOpen] = (0, import_element242.useState)(false);
    return /* @__PURE__ */ (0, import_jsx_runtime405.jsxs)("div", { className: "editor-post-template__classic-theme-dropdown", children: [
      /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
        import_block_editor48.__experimentalInspectorPopoverHeader,
        {
          title: (0, import_i18n227.__)("Template"),
          help: (0, import_i18n227.__)(
            "Templates define the way content is displayed when viewing your site."
          ),
          actions: canCreate ? [
            {
              icon: add_template_default,
              label: (0, import_i18n227.__)("Add template"),
              onClick: () => setIsCreateModalOpen(true)
            }
          ] : [],
          onClose
        }
      ),
      !allowSwitchingTemplate ? /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(import_components176.Notice, { status: "warning", isDismissible: false, children: (0, import_i18n227.__)("The posts page template cannot be changed.") }) : /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
        import_components176.SelectControl,
        {
          hideLabelFromVision: true,
          label: (0, import_i18n227.__)("Template"),
          value: selectedOption?.value ?? "",
          options,
          onChange: (slug) => editPost2({ template: slug || "" })
        }
      ),
      canEdit && onNavigateToEntityRecord && /* @__PURE__ */ (0, import_jsx_runtime405.jsx)("p", { children: /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
        import_components176.Button,
        {
          __next40pxDefaultSize: true,
          variant: "link",
          onClick: () => {
            onNavigateToEntityRecord({
              postId: currentTemplateId,
              postType: "wp_template"
            });
            onClose();
            createSuccessNotice(
              (0, import_i18n227.__)(
                "Editing template. Changes made here affect all posts and pages that use the template."
              ),
              {
                type: "snackbar",
                actions: [
                  {
                    label: (0, import_i18n227.__)("Go back"),
                    onClick: () => getEditorSettings2().onNavigateToPreviousEntityRecord()
                  }
                ]
              }
            );
          },
          children: (0, import_i18n227.__)("Edit template")
        }
      ) }),
      isCreateModalOpen && /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
        CreateNewTemplateModal,
        {
          onClose: () => setIsCreateModalOpen(false)
        }
      )
    ] });
  }
  function ClassicThemeControl() {
    const [popoverAnchor, setPopoverAnchor] = (0, import_element242.useState)(null);
    const popoverProps = (0, import_element242.useMemo)(
      () => ({
        // Anchor the popover to the middle of the entire row so that it doesn't
        // move around when the label changes.
        anchor: popoverAnchor,
        className: "editor-post-template__dropdown",
        placement: "left-start",
        offset: 36,
        shift: true
      }),
      [popoverAnchor]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(post_panel_row_default, { label: (0, import_i18n227.__)("Template"), ref: setPopoverAnchor, children: /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
      import_components176.Dropdown,
      {
        popoverProps,
        focusOnMount: true,
        renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(
          PostTemplateToggle,
          {
            isOpen: isOpen2,
            onClick: onToggle
          }
        ),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime405.jsx)(PostTemplateDropdownContent, { onClose })
      }
    ) });
  }
  var classic_theme_default = ClassicThemeControl;

  // packages/editor/build-module/components/plugin-document-setting-panel/index.mjs
  var import_components178 = __toESM(require_components(), 1);
  var import_plugins4 = __toESM(require_plugins(), 1);
  var import_data122 = __toESM(require_data(), 1);
  var import_warning2 = __toESM(require_warning(), 1);

  // packages/editor/build-module/components/preferences-modal/enable-plugin-document-setting-panel.mjs
  var import_components177 = __toESM(require_components(), 1);

  // packages/editor/build-module/components/preferences-modal/enable-panel.mjs
  var import_data121 = __toESM(require_data(), 1);
  var import_preferences12 = __toESM(require_preferences(), 1);
  var import_jsx_runtime406 = __toESM(require_jsx_runtime(), 1);
  var { PreferenceBaseOption } = unlock(import_preferences12.privateApis);
  function EnablePanelOption(props) {
    const { toggleEditorPanelEnabled: toggleEditorPanelEnabled2 } = (0, import_data121.useDispatch)(store);
    const { isChecked, isRemoved } = (0, import_data121.useSelect)(
      (select9) => {
        const { isEditorPanelEnabled: isEditorPanelEnabled2, isEditorPanelRemoved: isEditorPanelRemoved2 } = select9(store);
        return {
          isChecked: isEditorPanelEnabled2(props.panelName),
          isRemoved: isEditorPanelRemoved2(props.panelName)
        };
      },
      [props.panelName]
    );
    if (isRemoved) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime406.jsx)(
      PreferenceBaseOption,
      {
        isChecked,
        onChange: () => toggleEditorPanelEnabled2(props.panelName),
        ...props
      }
    );
  }

  // packages/editor/build-module/components/preferences-modal/enable-plugin-document-setting-panel.mjs
  var import_jsx_runtime407 = __toESM(require_jsx_runtime(), 1);
  var { Fill: Fill4, Slot: Slot4 } = (0, import_components177.createSlotFill)(
    "EnablePluginDocumentSettingPanelOption"
  );
  var EnablePluginDocumentSettingPanelOption = ({ label, panelName }) => /* @__PURE__ */ (0, import_jsx_runtime407.jsx)(Fill4, { children: /* @__PURE__ */ (0, import_jsx_runtime407.jsx)(EnablePanelOption, { label, panelName }) });
  EnablePluginDocumentSettingPanelOption.Slot = Slot4;
  var enable_plugin_document_setting_panel_default = EnablePluginDocumentSettingPanelOption;

  // packages/editor/build-module/components/plugin-document-setting-panel/index.mjs
  var import_jsx_runtime408 = __toESM(require_jsx_runtime(), 1);
  var { Fill: Fill5, Slot: Slot5 } = (0, import_components178.createSlotFill)("PluginDocumentSettingPanel");
  var PluginDocumentSettingPanel = ({
    name: name2,
    className,
    title,
    icon,
    children
  }) => {
    const { name: pluginName } = (0, import_plugins4.usePluginContext)();
    const panelName = `${pluginName}/${name2}`;
    const { opened, isEnabled } = (0, import_data122.useSelect)(
      (select9) => {
        const { isEditorPanelOpened: isEditorPanelOpened2, isEditorPanelEnabled: isEditorPanelEnabled2 } = select9(store);
        return {
          opened: isEditorPanelOpened2(panelName),
          isEnabled: isEditorPanelEnabled2(panelName)
        };
      },
      [panelName]
    );
    const { toggleEditorPanelOpened: toggleEditorPanelOpened2 } = (0, import_data122.useDispatch)(store);
    if (void 0 === name2) {
      (0, import_warning2.default)("PluginDocumentSettingPanel requires a name property.");
    }
    return /* @__PURE__ */ (0, import_jsx_runtime408.jsxs)(import_jsx_runtime408.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime408.jsx)(
        enable_plugin_document_setting_panel_default,
        {
          label: title,
          panelName
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime408.jsx)(Fill5, { children: isEnabled && /* @__PURE__ */ (0, import_jsx_runtime408.jsx)(
        import_components178.PanelBody,
        {
          className,
          title,
          icon,
          opened,
          onToggle: () => toggleEditorPanelOpened2(panelName),
          children
        }
      ) })
    ] });
  };
  PluginDocumentSettingPanel.Slot = Slot5;
  var plugin_document_setting_panel_default = PluginDocumentSettingPanel;

  // packages/editor/build-module/components/block-settings-menu/plugin-block-settings-menu-item.mjs
  var import_block_editor49 = __toESM(require_block_editor(), 1);
  var import_components179 = __toESM(require_components(), 1);
  var import_compose43 = __toESM(require_compose(), 1);
  var import_jsx_runtime409 = __toESM(require_jsx_runtime(), 1);
  var isEverySelectedBlockAllowed = (selected, allowed) => selected.filter((id) => !allowed.includes(id)).length === 0;
  var shouldRenderItem = (selectedBlocks, allowedBlocks) => !Array.isArray(allowedBlocks) || isEverySelectedBlockAllowed(selectedBlocks, allowedBlocks);
  var PluginBlockSettingsMenuItem = ({
    allowedBlocks,
    icon,
    label,
    onClick,
    small,
    role
  }) => /* @__PURE__ */ (0, import_jsx_runtime409.jsx)(import_block_editor49.BlockSettingsMenuControls, { children: ({ selectedBlocks, onClose }) => {
    if (!shouldRenderItem(selectedBlocks, allowedBlocks)) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime409.jsx)(
      import_components179.MenuItem,
      {
        onClick: (0, import_compose43.compose)(onClick, onClose),
        icon,
        label: small ? label : void 0,
        role,
        children: !small && label
      }
    );
  } });
  var plugin_block_settings_menu_item_default = PluginBlockSettingsMenuItem;

  // packages/editor/build-module/components/plugin-more-menu-item/index.mjs
  var import_components180 = __toESM(require_components(), 1);
  var import_plugins5 = __toESM(require_plugins(), 1);
  var import_jsx_runtime410 = __toESM(require_jsx_runtime(), 1);
  function PluginMoreMenuItem(props) {
    const context = (0, import_plugins5.usePluginContext)();
    return /* @__PURE__ */ (0, import_jsx_runtime410.jsx)(
      action_item_default,
      {
        name: "core/plugin-more-menu",
        as: props.as ?? import_components180.MenuItem,
        icon: props.icon || context.icon,
        ...props
      }
    );
  }

  // packages/editor/build-module/components/plugin-post-publish-panel/index.mjs
  var import_plugins6 = __toESM(require_plugins(), 1);
  var import_components181 = __toESM(require_components(), 1);
  var import_jsx_runtime411 = __toESM(require_jsx_runtime(), 1);
  var { Fill: Fill6, Slot: Slot6 } = (0, import_components181.createSlotFill)("PluginPostPublishPanel");
  var PluginPostPublishPanel = ({
    children,
    className,
    title,
    initialOpen = false,
    icon
  }) => {
    const { icon: pluginIcon } = (0, import_plugins6.usePluginContext)();
    return /* @__PURE__ */ (0, import_jsx_runtime411.jsx)(Fill6, { children: /* @__PURE__ */ (0, import_jsx_runtime411.jsx)(
      import_components181.PanelBody,
      {
        className,
        initialOpen: initialOpen || !title,
        title,
        icon: icon ?? pluginIcon,
        children
      }
    ) });
  };
  PluginPostPublishPanel.Slot = Slot6;
  var plugin_post_publish_panel_default = PluginPostPublishPanel;

  // packages/editor/build-module/components/plugin-post-status-info/index.mjs
  var import_components182 = __toESM(require_components(), 1);
  var import_jsx_runtime412 = __toESM(require_jsx_runtime(), 1);
  var { Fill: Fill7, Slot: Slot7 } = (0, import_components182.createSlotFill)("PluginPostStatusInfo");
  var PluginPostStatusInfo = ({ children, className }) => /* @__PURE__ */ (0, import_jsx_runtime412.jsx)(Fill7, { children: /* @__PURE__ */ (0, import_jsx_runtime412.jsx)(import_components182.PanelRow, { className, children }) });
  PluginPostStatusInfo.Slot = Slot7;
  var plugin_post_status_info_default = PluginPostStatusInfo;

  // packages/editor/build-module/components/plugin-pre-publish-panel/index.mjs
  var import_components183 = __toESM(require_components(), 1);
  var import_plugins7 = __toESM(require_plugins(), 1);
  var import_jsx_runtime413 = __toESM(require_jsx_runtime(), 1);
  var { Fill: Fill8, Slot: Slot8 } = (0, import_components183.createSlotFill)("PluginPrePublishPanel");
  var PluginPrePublishPanel = ({
    children,
    className,
    title,
    initialOpen = false,
    icon
  }) => {
    const { icon: pluginIcon } = (0, import_plugins7.usePluginContext)();
    return /* @__PURE__ */ (0, import_jsx_runtime413.jsx)(Fill8, { children: /* @__PURE__ */ (0, import_jsx_runtime413.jsx)(
      import_components183.PanelBody,
      {
        className,
        initialOpen: initialOpen || !title,
        title,
        icon: icon ?? pluginIcon,
        children
      }
    ) });
  };
  PluginPrePublishPanel.Slot = Slot8;
  var plugin_pre_publish_panel_default = PluginPrePublishPanel;

  // packages/editor/build-module/components/plugin-preview-menu-item/index.mjs
  var import_components184 = __toESM(require_components(), 1);
  var import_plugins8 = __toESM(require_plugins(), 1);
  var import_jsx_runtime414 = __toESM(require_jsx_runtime(), 1);
  function PluginPreviewMenuItem(props) {
    const context = (0, import_plugins8.usePluginContext)();
    return /* @__PURE__ */ (0, import_jsx_runtime414.jsx)(
      action_item_default,
      {
        name: "core/plugin-preview-menu",
        as: props.as ?? import_components184.MenuItem,
        icon: props.icon || context.icon,
        ...props
      }
    );
  }

  // packages/editor/build-module/components/plugin-sidebar/index.mjs
  var import_jsx_runtime415 = __toESM(require_jsx_runtime(), 1);
  function PluginSidebar({ className, ...props }) {
    return /* @__PURE__ */ (0, import_jsx_runtime415.jsx)(
      complementary_area_default,
      {
        panelClassName: className,
        className: "editor-sidebar",
        scope: "core",
        ...props
      }
    );
  }

  // packages/editor/build-module/components/plugin-sidebar-more-menu-item/index.mjs
  var import_jsx_runtime416 = __toESM(require_jsx_runtime(), 1);
  function PluginSidebarMoreMenuItem(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime416.jsx)(
      ComplementaryAreaMoreMenuItem,
      {
        __unstableExplicitMenuItem: true,
        scope: "core",
        ...props
      }
    );
  }

  // packages/editor/build-module/components/post-template/block-theme.mjs
  var import_data126 = __toESM(require_data(), 1);
  var import_html_entities21 = __toESM(require_html_entities(), 1);
  var import_components188 = __toESM(require_components(), 1);
  var import_element245 = __toESM(require_element(), 1);
  var import_i18n231 = __toESM(require_i18n(), 1);
  var import_core_data78 = __toESM(require_core_data(), 1);
  var import_notices25 = __toESM(require_notices(), 1);
  var import_preferences13 = __toESM(require_preferences(), 1);

  // packages/editor/build-module/components/post-template/swap-template-button.mjs
  var import_element243 = __toESM(require_element(), 1);
  var import_html_entities20 = __toESM(require_html_entities(), 1);
  var import_block_editor50 = __toESM(require_block_editor(), 1);
  var import_components185 = __toESM(require_components(), 1);
  var import_i18n228 = __toESM(require_i18n(), 1);
  var import_data123 = __toESM(require_data(), 1);
  var import_core_data75 = __toESM(require_core_data(), 1);
  var import_blocks26 = __toESM(require_blocks(), 1);

  // packages/editor/build-module/utils/search-templates.mjs
  var import_remove_accents5 = __toESM(require_remove_accents(), 1);
  function normalizeSearchInput3(input = "") {
    input = (0, import_remove_accents5.default)(input);
    input = input.trim().toLowerCase();
    return input;
  }
  function getTemplateSearchRank(template2, searchValue) {
    const normalizedSearchValue = normalizeSearchInput3(searchValue);
    const normalizedTitle = normalizeSearchInput3(template2.title);
    let rank = 0;
    if (normalizedSearchValue === normalizedTitle) {
      rank += 30;
    } else if (normalizedTitle.startsWith(normalizedSearchValue)) {
      rank += 20;
    } else {
      const searchTerms = normalizedSearchValue.split(" ");
      const hasMatchedTerms = searchTerms.every(
        (searchTerm) => normalizedTitle.includes(searchTerm)
      );
      if (hasMatchedTerms) {
        rank += 10;
      }
    }
    return rank;
  }
  function searchTemplates(templates = [], searchValue = "") {
    if (!searchValue) {
      return templates;
    }
    const rankedTemplates = templates.map((template2) => {
      return [template2, getTemplateSearchRank(template2, searchValue)];
    }).filter(([, rank]) => rank > 0);
    rankedTemplates.sort(([, rank1], [, rank2]) => rank2 - rank1);
    return rankedTemplates.map(([template2]) => template2);
  }

  // packages/editor/build-module/components/post-template/swap-template-button.mjs
  var import_jsx_runtime417 = __toESM(require_jsx_runtime(), 1);
  function SwapTemplateModal({ onRequestClose, onSelect }) {
    const { postType: postType2, postId: postId2 } = useEditedPostContext();
    const { editEntityRecord } = (0, import_data123.useDispatch)(import_core_data75.store);
    const onTemplateSelect = async (template2) => {
      editEntityRecord(
        "postType",
        postType2,
        postId2,
        // Since we append the default template we need to properly
        // update to an empty string.
        { template: template2.isDefault ? "" : template2.name },
        { undoIgnore: true }
      );
      onRequestClose();
      onSelect?.();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime417.jsx)(
      import_components185.Modal,
      {
        title: (0, import_i18n228.__)("Choose a template"),
        onRequestClose,
        overlayClassName: "editor-post-template__swap-template-modal",
        isFullScreen: true,
        children: /* @__PURE__ */ (0, import_jsx_runtime417.jsx)("div", { className: "editor-post-template__swap-template-modal-content", children: /* @__PURE__ */ (0, import_jsx_runtime417.jsx)(TemplatesList, { onSelect: onTemplateSelect }) })
      }
    );
  }
  function SwapTemplateButton({ onClick }) {
    const [showModal, setShowModal] = (0, import_element243.useState)(false);
    const availableTemplates = useAvailableTemplates();
    return /* @__PURE__ */ (0, import_jsx_runtime417.jsxs)(import_jsx_runtime417.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime417.jsx)(
        import_components185.MenuItem,
        {
          disabled: !availableTemplates?.length,
          accessibleWhenDisabled: true,
          onClick: () => setShowModal(true),
          children: (0, import_i18n228.__)("Change template")
        }
      ),
      showModal && /* @__PURE__ */ (0, import_jsx_runtime417.jsx)(
        SwapTemplateModal,
        {
          onRequestClose: () => setShowModal(false),
          onSelect: onClick
        }
      )
    ] });
  }
  function TemplatesList({ onSelect }) {
    const [searchValue, setSearchValue] = (0, import_element243.useState)("");
    const availableTemplates = useAvailableTemplates();
    const templatesAsPatterns = (0, import_element243.useMemo)(
      () => availableTemplates.map((template2) => ({
        name: template2.slug,
        blocks: (0, import_blocks26.parse)(template2.content.raw),
        title: (0, import_html_entities20.decodeEntities)(template2.title.rendered),
        id: template2.id,
        isDefault: template2.isDefault
      })),
      [availableTemplates]
    );
    const filteredBlockTemplates = (0, import_element243.useMemo)(() => {
      return searchTemplates(templatesAsPatterns, searchValue);
    }, [templatesAsPatterns, searchValue]);
    return /* @__PURE__ */ (0, import_jsx_runtime417.jsxs)(import_jsx_runtime417.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime417.jsx)(
        import_components185.SearchControl,
        {
          onChange: setSearchValue,
          value: searchValue,
          label: (0, import_i18n228.__)("Search"),
          placeholder: (0, import_i18n228.__)("Search"),
          className: "editor-post-template__swap-template-search"
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime417.jsx)(
        import_block_editor50.__experimentalBlockPatternsList,
        {
          label: (0, import_i18n228.__)("Templates"),
          blockPatterns: filteredBlockTemplates,
          onClickPattern: onSelect
        }
      )
    ] });
  }

  // packages/editor/build-module/components/post-template/reset-default-template.mjs
  var import_components186 = __toESM(require_components(), 1);
  var import_i18n229 = __toESM(require_i18n(), 1);
  var import_data124 = __toESM(require_data(), 1);
  var import_core_data76 = __toESM(require_core_data(), 1);
  var import_jsx_runtime418 = __toESM(require_jsx_runtime(), 1);
  function ResetDefaultTemplate({ onClick }) {
    const currentTemplateSlug = useCurrentTemplateSlug();
    const allowSwitchingTemplate = useAllowSwitchingTemplates();
    const { postType: postType2, postId: postId2 } = useEditedPostContext();
    const { editEntityRecord } = (0, import_data124.useDispatch)(import_core_data76.store);
    if (!currentTemplateSlug || !allowSwitchingTemplate) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime418.jsx)(
      import_components186.MenuItem,
      {
        onClick: () => {
          editEntityRecord(
            "postType",
            postType2,
            postId2,
            { template: "" },
            { undoIgnore: true }
          );
          onClick();
        },
        children: (0, import_i18n229.__)("Use default template")
      }
    );
  }

  // packages/editor/build-module/components/post-template/create-new-template.mjs
  var import_components187 = __toESM(require_components(), 1);
  var import_i18n230 = __toESM(require_i18n(), 1);
  var import_data125 = __toESM(require_data(), 1);
  var import_core_data77 = __toESM(require_core_data(), 1);
  var import_element244 = __toESM(require_element(), 1);
  var import_jsx_runtime419 = __toESM(require_jsx_runtime(), 1);
  function CreateNewTemplate() {
    const { canCreateTemplates } = (0, import_data125.useSelect)((select9) => {
      const { canUser } = select9(import_core_data77.store);
      return {
        canCreateTemplates: canUser("create", {
          kind: "postType",
          name: "wp_template"
        })
      };
    }, []);
    const [isCreateModalOpen, setIsCreateModalOpen] = (0, import_element244.useState)(false);
    const allowSwitchingTemplate = useAllowSwitchingTemplates();
    if (!canCreateTemplates || !allowSwitchingTemplate) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime419.jsxs)(import_jsx_runtime419.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime419.jsx)(
        import_components187.MenuItem,
        {
          onClick: () => {
            setIsCreateModalOpen(true);
          },
          children: (0, import_i18n230.__)("Create new template")
        }
      ),
      isCreateModalOpen && /* @__PURE__ */ (0, import_jsx_runtime419.jsx)(
        CreateNewTemplateModal,
        {
          onClose: () => {
            setIsCreateModalOpen(false);
          }
        }
      )
    ] });
  }

  // packages/editor/build-module/components/post-template/block-theme.mjs
  var import_jsx_runtime420 = __toESM(require_jsx_runtime(), 1);
  function BlockThemeControl() {
    const {
      isTemplateHidden,
      onNavigateToEntityRecord,
      getEditorSettings: getEditorSettings2,
      hasGoBack,
      hasSpecificTemplate,
      id
    } = (0, import_data126.useSelect)((select9) => {
      const {
        getRenderingMode: getRenderingMode2,
        getEditorSettings: _getEditorSettings,
        getCurrentPost: getCurrentPost2,
        getCurrentTemplateId: getCurrentTemplateId2
      } = unlock(select9(store));
      const editorSettings2 = _getEditorSettings();
      const currentPost = getCurrentPost2();
      return {
        isTemplateHidden: getRenderingMode2() === "post-only",
        onNavigateToEntityRecord: editorSettings2.onNavigateToEntityRecord,
        getEditorSettings: _getEditorSettings,
        hasGoBack: editorSettings2.hasOwnProperty(
          "onNavigateToPreviousEntityRecord"
        ),
        hasSpecificTemplate: !!currentPost.template,
        id: getCurrentTemplateId2()
      };
    }, []);
    const { get: getPreference } = (0, import_data126.useSelect)(import_preferences13.store);
    const { editedRecord: template2, hasResolved } = (0, import_core_data78.useEntityRecord)(
      "postType",
      "wp_template",
      id
    );
    const { getEntityRecord } = (0, import_data126.useSelect)(import_core_data78.store);
    const { editEntityRecord } = (0, import_data126.useDispatch)(import_core_data78.store);
    const { createSuccessNotice } = (0, import_data126.useDispatch)(import_notices25.store);
    const { setRenderingMode: setRenderingMode2, setDefaultRenderingMode: setDefaultRenderingMode2 } = unlock(
      (0, import_data126.useDispatch)(store)
    );
    const canCreateTemplate = (0, import_data126.useSelect)(
      (select9) => !!select9(import_core_data78.store).canUser("create", {
        kind: "postType",
        name: "wp_template"
      }),
      []
    );
    const [popoverAnchor, setPopoverAnchor] = (0, import_element245.useState)(null);
    const popoverProps = (0, import_element245.useMemo)(
      () => ({
        // Anchor the popover to the middle of the entire row so that it doesn't
        // move around when the label changes.
        anchor: popoverAnchor,
        className: "editor-post-template__dropdown",
        placement: "left-start",
        offset: 36,
        shift: true
      }),
      [popoverAnchor]
    );
    if (!hasResolved) {
      return null;
    }
    const notificationAction = hasGoBack ? [
      {
        label: (0, import_i18n231.__)("Go back"),
        onClick: () => getEditorSettings2().onNavigateToPreviousEntityRecord()
      }
    ] : void 0;
    const mayShowTemplateEditNotice = () => {
      if (!getPreference("core/edit-site", "welcomeGuideTemplate")) {
        createSuccessNotice(
          (0, import_i18n231.__)(
            "Editing template. Changes made here affect all posts and pages that use the template."
          ),
          { type: "snackbar", actions: notificationAction }
        );
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(post_panel_row_default, { label: (0, import_i18n231.__)("Template"), ref: setPopoverAnchor, children: /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(
      import_components188.DropdownMenu,
      {
        popoverProps,
        focusOnMount: true,
        toggleProps: {
          size: "compact",
          variant: "tertiary",
          tooltipPosition: "middle left"
        },
        label: (0, import_i18n231.__)("Template options"),
        text: (0, import_html_entities21.decodeEntities)(template2.title),
        icon: null,
        children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime420.jsxs)(import_jsx_runtime420.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime420.jsxs)(import_components188.MenuGroup, { children: [
            canCreateTemplate && /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(
              import_components188.MenuItem,
              {
                onClick: async () => {
                  onNavigateToEntityRecord({
                    postId: template2.id,
                    postType: "wp_template"
                  });
                  if (!hasSpecificTemplate && window?.__experimentalTemplateActivate) {
                    const activeTemplates = await getEntityRecord(
                      "root",
                      "site"
                    ).active_templates;
                    if (activeTemplates[template2.slug] !== template2.id) {
                      editEntityRecord(
                        "root",
                        "site",
                        void 0,
                        {
                          active_templates: {
                            ...activeTemplates,
                            [template2.slug]: template2.id
                          }
                        }
                      );
                    }
                  }
                  onClose();
                  mayShowTemplateEditNotice();
                },
                children: (0, import_i18n231.__)("Edit template")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(SwapTemplateButton, { onClick: onClose }),
            /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(ResetDefaultTemplate, { onClick: onClose }),
            canCreateTemplate && /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(CreateNewTemplate, {})
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(import_components188.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime420.jsx)(
            import_components188.MenuItem,
            {
              icon: !isTemplateHidden ? check_default : void 0,
              isSelected: !isTemplateHidden,
              role: "menuitemcheckbox",
              onClick: () => {
                const newRenderingMode = isTemplateHidden ? "template-locked" : "post-only";
                setRenderingMode2(newRenderingMode);
                setDefaultRenderingMode2(newRenderingMode);
              },
              children: (0, import_i18n231.__)("Show template")
            }
          ) })
        ] })
      }
    ) });
  }

  // packages/editor/build-module/components/post-template/panel.mjs
  var import_jsx_runtime421 = __toESM(require_jsx_runtime(), 1);
  function PostTemplatePanel() {
    const mode = usePostTemplatePanelMode();
    if (mode === "classic") {
      return /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(classic_theme_default, {});
    }
    if (mode === "block-theme") {
      return /* @__PURE__ */ (0, import_jsx_runtime421.jsx)(BlockThemeControl, {});
    }
    return null;
  }

  // packages/editor/build-module/components/post-author/index.mjs
  var import_data130 = __toESM(require_data(), 1);
  var import_core_data80 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/post-author/combobox.mjs
  var import_compose44 = __toESM(require_compose(), 1);
  var import_element247 = __toESM(require_element(), 1);
  var import_data128 = __toESM(require_data(), 1);
  var import_i18n233 = __toESM(require_i18n(), 1);
  var import_components189 = __toESM(require_components(), 1);

  // packages/editor/build-module/components/post-author/hook.mjs
  var import_i18n232 = __toESM(require_i18n(), 1);
  var import_element246 = __toESM(require_element(), 1);
  var import_data127 = __toESM(require_data(), 1);
  var import_html_entities22 = __toESM(require_html_entities(), 1);
  var import_core_data79 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/post-author/constants.mjs
  var BASE_QUERY = {
    _fields: "id,name",
    context: "view"
    // Allows non-admins to perform requests.
  };
  var AUTHORS_QUERY = {
    who: "authors",
    per_page: 100,
    ...BASE_QUERY
  };

  // packages/editor/build-module/components/post-author/hook.mjs
  function useAuthorsQuery(search) {
    const { authorId, authors, postAuthor, isLoading } = (0, import_data127.useSelect)(
      (select9) => {
        const { getUser, getUsers, isResolving } = select9(import_core_data79.store);
        const { getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
        const _authorId = getEditedPostAttribute2("author");
        const query = { ...AUTHORS_QUERY };
        if (search) {
          query.search = search;
          query.search_columns = ["name"];
        }
        return {
          authorId: _authorId,
          authors: getUsers(query),
          postAuthor: getUser(_authorId, BASE_QUERY),
          isLoading: isResolving("getUsers", [query])
        };
      },
      [search]
    );
    const authorOptions = (0, import_element246.useMemo)(() => {
      const fetchedAuthors = (authors ?? []).map((author) => {
        return {
          value: author.id,
          label: (0, import_html_entities22.decodeEntities)(author.name)
        };
      });
      const foundAuthor = fetchedAuthors.findIndex(
        ({ value }) => postAuthor?.id === value
      );
      let currentAuthor = [];
      if (foundAuthor < 0 && postAuthor) {
        currentAuthor = [
          {
            value: postAuthor.id,
            label: (0, import_html_entities22.decodeEntities)(postAuthor.name)
          }
        ];
      } else if (foundAuthor < 0 && !postAuthor) {
        currentAuthor = [
          {
            value: 0,
            label: (0, import_i18n232.__)("(No author)")
          }
        ];
      }
      return [...currentAuthor, ...fetchedAuthors];
    }, [authors, postAuthor]);
    return { authorId, authorOptions, postAuthor, isLoading };
  }

  // packages/editor/build-module/components/post-author/combobox.mjs
  var import_jsx_runtime422 = __toESM(require_jsx_runtime(), 1);
  function PostAuthorCombobox() {
    const [fieldValue, setFieldValue] = (0, import_element247.useState)();
    const { editPost: editPost2 } = (0, import_data128.useDispatch)(store);
    const { authorId, authorOptions, isLoading } = useAuthorsQuery(fieldValue);
    const handleSelect = (postAuthorId) => {
      if (!postAuthorId) {
        return;
      }
      editPost2({ author: postAuthorId });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime422.jsx)(
      import_components189.ComboboxControl,
      {
        label: (0, import_i18n233.__)("Author"),
        options: authorOptions,
        value: authorId,
        onFilterValueChange: (0, import_compose44.debounce)(setFieldValue, 300),
        onChange: handleSelect,
        allowReset: false,
        hideLabelFromVision: true,
        isLoading
      }
    );
  }

  // packages/editor/build-module/components/post-author/select.mjs
  var import_i18n234 = __toESM(require_i18n(), 1);
  var import_data129 = __toESM(require_data(), 1);
  var import_components190 = __toESM(require_components(), 1);
  var import_jsx_runtime423 = __toESM(require_jsx_runtime(), 1);
  function PostAuthorSelect() {
    const { editPost: editPost2 } = (0, import_data129.useDispatch)(store);
    const { authorId, authorOptions } = useAuthorsQuery();
    const setAuthorId = (value) => {
      const author = Number(value);
      editPost2({ author });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime423.jsx)(
      import_components190.SelectControl,
      {
        className: "post-author-selector",
        label: (0, import_i18n234.__)("Author"),
        options: authorOptions,
        onChange: setAuthorId,
        value: authorId,
        hideLabelFromVision: true
      }
    );
  }

  // packages/editor/build-module/components/post-author/index.mjs
  var import_jsx_runtime424 = __toESM(require_jsx_runtime(), 1);
  var minimumUsersForCombobox = 25;
  function PostAuthor() {
    const showCombobox = (0, import_data130.useSelect)((select9) => {
      const authors = select9(import_core_data80.store).getUsers(AUTHORS_QUERY);
      return authors?.length >= minimumUsersForCombobox;
    }, []);
    if (showCombobox) {
      return /* @__PURE__ */ (0, import_jsx_runtime424.jsx)(PostAuthorCombobox, {});
    }
    return /* @__PURE__ */ (0, import_jsx_runtime424.jsx)(PostAuthorSelect, {});
  }
  var post_author_default = PostAuthor;

  // packages/editor/build-module/components/post-author/check.mjs
  var import_data131 = __toESM(require_data(), 1);
  var import_jsx_runtime425 = __toESM(require_jsx_runtime(), 1);
  function PostAuthorCheck({ children }) {
    const { hasAssignAuthorAction } = (0, import_data131.useSelect)((select9) => {
      const post2 = select9(store).getCurrentPost();
      const canAssignAuthor = post2?._links?.["wp:action-assign-author"] ? true : false;
      return {
        hasAssignAuthorAction: canAssignAuthor
      };
    }, []);
    if (!hasAssignAuthorAction) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime425.jsx)(post_type_support_check_default, { supportKeys: "author", children });
  }

  // packages/editor/build-module/components/post-author/panel.mjs
  var import_i18n235 = __toESM(require_i18n(), 1);
  var import_components191 = __toESM(require_components(), 1);
  var import_element248 = __toESM(require_element(), 1);
  var import_html_entities23 = __toESM(require_html_entities(), 1);
  var import_block_editor51 = __toESM(require_block_editor(), 1);
  var import_data132 = __toESM(require_data(), 1);
  var import_core_data81 = __toESM(require_core_data(), 1);
  var import_jsx_runtime426 = __toESM(require_jsx_runtime(), 1);
  function PostAuthorToggle({ isOpen: isOpen2, onClick }) {
    const { postAuthor } = (0, import_data132.useSelect)((select9) => {
      const id = select9(store).getEditedPostAttribute("author");
      return {
        postAuthor: select9(import_core_data81.store).getUser(id, BASE_QUERY)
      };
    }, []);
    const authorName = (0, import_html_entities23.decodeEntities)(postAuthor?.name) || (0, import_i18n235.__)("(No author)");
    return /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
      import_components191.Button,
      {
        size: "compact",
        variant: "tertiary",
        "aria-expanded": isOpen2,
        "aria-label": (
          // translators: %s: Author name.
          (0, import_i18n235.sprintf)((0, import_i18n235.__)("Change author: %s"), authorName)
        ),
        onClick,
        children: authorName
      }
    );
  }
  function PostAuthor2() {
    const [popoverAnchor, setPopoverAnchor] = (0, import_element248.useState)(null);
    const popoverProps = (0, import_element248.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]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(PostAuthorCheck, { children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(post_panel_row_default, { label: (0, import_i18n235.__)("Author"), ref: setPopoverAnchor, children: /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
      import_components191.Dropdown,
      {
        popoverProps,
        contentClassName: "editor-post-author__panel-dialog",
        focusOnMount: true,
        renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
          PostAuthorToggle,
          {
            isOpen: isOpen2,
            onClick: onToggle
          }
        ),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime426.jsxs)("div", { className: "editor-post-author", children: [
          /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(
            import_block_editor51.__experimentalInspectorPopoverHeader,
            {
              title: (0, import_i18n235.__)("Author"),
              onClose
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime426.jsx)(post_author_default, { onClose })
        ] })
      }
    ) }) });
  }
  var panel_default = PostAuthor2;

  // packages/editor/build-module/components/post-comments/index.mjs
  var import_i18n236 = __toESM(require_i18n(), 1);
  var import_components192 = __toESM(require_components(), 1);
  var import_data133 = __toESM(require_data(), 1);
  var import_jsx_runtime427 = __toESM(require_jsx_runtime(), 1);
  var COMMENT_OPTIONS = [
    {
      label: (0, import_i18n236._x)("Open", 'Adjective: e.g. "Comments are open"'),
      value: "open",
      description: (0, import_i18n236.__)("Visitors can add new comments and replies.")
    },
    {
      label: (0, import_i18n236.__)("Closed"),
      value: "closed",
      description: [
        (0, import_i18n236.__)("Visitors cannot add new comments or replies."),
        (0, import_i18n236.__)("Existing comments remain visible.")
      ].join(" ")
    }
  ];
  function PostComments() {
    const commentStatus = (0, import_data133.useSelect)(
      (select9) => select9(store).getEditedPostAttribute("comment_status") ?? "open",
      []
    );
    const { editPost: editPost2 } = (0, import_data133.useDispatch)(store);
    const handleStatus = (newCommentStatus) => editPost2({
      comment_status: newCommentStatus
    });
    return /* @__PURE__ */ (0, import_jsx_runtime427.jsx)("form", { children: /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(import_components192.__experimentalVStack, { spacing: 4, children: /* @__PURE__ */ (0, import_jsx_runtime427.jsx)(
      import_components192.RadioControl,
      {
        className: "editor-change-status__options",
        hideLabelFromVision: true,
        label: (0, import_i18n236.__)("Comment status"),
        options: COMMENT_OPTIONS,
        onChange: handleStatus,
        selected: commentStatus
      }
    ) }) });
  }
  var post_comments_default = PostComments;

  // packages/editor/build-module/components/post-discussion/panel.mjs
  var import_i18n238 = __toESM(require_i18n(), 1);
  var import_components194 = __toESM(require_components(), 1);
  var import_data135 = __toESM(require_data(), 1);
  var import_element249 = __toESM(require_element(), 1);
  var import_block_editor52 = __toESM(require_block_editor(), 1);
  var import_core_data82 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/post-pingbacks/index.mjs
  var import_i18n237 = __toESM(require_i18n(), 1);
  var import_components193 = __toESM(require_components(), 1);
  var import_data134 = __toESM(require_data(), 1);
  var import_jsx_runtime428 = __toESM(require_jsx_runtime(), 1);
  function PostPingbacks() {
    const pingStatus = (0, import_data134.useSelect)(
      (select9) => select9(store).getEditedPostAttribute("ping_status") ?? "open",
      []
    );
    const { editPost: editPost2 } = (0, import_data134.useDispatch)(store);
    const onTogglePingback = () => editPost2({
      ping_status: pingStatus === "open" ? "closed" : "open"
    });
    return /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
      import_components193.CheckboxControl,
      {
        label: (0, import_i18n237.__)("Enable pingbacks & trackbacks"),
        checked: pingStatus === "open",
        onChange: onTogglePingback,
        help: /* @__PURE__ */ (0, import_jsx_runtime428.jsx)(
          import_components193.ExternalLink,
          {
            href: (0, import_i18n237.__)(
              "https://wordpress.org/documentation/article/trackbacks-and-pingbacks/"
            ),
            children: (0, import_i18n237.__)("Learn more about pingbacks & trackbacks")
          }
        )
      }
    );
  }
  var post_pingbacks_default = PostPingbacks;

  // packages/editor/build-module/components/post-discussion/panel.mjs
  var import_jsx_runtime429 = __toESM(require_jsx_runtime(), 1);
  var PANEL_NAME2 = "discussion-panel";
  function ModalContents({ onClose }) {
    return /* @__PURE__ */ (0, import_jsx_runtime429.jsxs)("div", { className: "editor-post-discussion", children: [
      /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
        import_block_editor52.__experimentalInspectorPopoverHeader,
        {
          title: (0, import_i18n238.__)("Discussion"),
          onClose
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime429.jsxs)(import_components194.__experimentalVStack, { spacing: 4, children: [
        /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(post_type_support_check_default, { supportKeys: "comments", children: /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(post_comments_default, {}) }),
        /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(post_type_support_check_default, { supportKeys: "trackbacks", children: /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(post_pingbacks_default, {}) })
      ] })
    ] });
  }
  function PostDiscussionToggle({ isOpen: isOpen2, onClick }) {
    const {
      commentStatus,
      pingStatus,
      commentsSupported,
      trackbacksSupported
    } = (0, import_data135.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
      const { getPostType } = select9(import_core_data82.store);
      const postType2 = getPostType(getEditedPostAttribute2("type"));
      return {
        commentStatus: getEditedPostAttribute2("comment_status") ?? "open",
        pingStatus: getEditedPostAttribute2("ping_status") ?? "open",
        commentsSupported: !!postType2.supports.comments,
        trackbacksSupported: !!postType2.supports.trackbacks
      };
    }, []);
    let label;
    if (commentStatus === "open") {
      if (pingStatus === "open") {
        label = (0, import_i18n238._x)("Open", 'Adjective: e.g. "Comments are open"');
      } else {
        label = trackbacksSupported ? (0, import_i18n238.__)("Comments only") : (0, import_i18n238._x)("Open", 'Adjective: e.g. "Comments are open"');
      }
    } else if (pingStatus === "open") {
      label = commentsSupported ? (0, import_i18n238.__)("Pings only") : (0, import_i18n238.__)("Pings enabled");
    } else {
      label = (0, import_i18n238.__)("Closed");
    }
    return /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
      import_components194.Button,
      {
        size: "compact",
        className: "editor-post-discussion__panel-toggle",
        variant: "tertiary",
        "aria-label": (0, import_i18n238.__)("Change discussion options"),
        "aria-expanded": isOpen2,
        onClick,
        children: label
      }
    );
  }
  function PostDiscussionPanel() {
    const { isEnabled } = (0, import_data135.useSelect)((select9) => {
      const { isEditorPanelEnabled: isEditorPanelEnabled2 } = select9(store);
      return {
        isEnabled: isEditorPanelEnabled2(PANEL_NAME2)
      };
    }, []);
    const [popoverAnchor, setPopoverAnchor] = (0, import_element249.useState)(null);
    const popoverProps = (0, import_element249.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]
    );
    if (!isEnabled) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(post_type_support_check_default, { supportKeys: ["comments", "trackbacks"], children: /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(post_panel_row_default, { label: (0, import_i18n238.__)("Discussion"), ref: setPopoverAnchor, children: /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
      import_components194.Dropdown,
      {
        popoverProps,
        className: "editor-post-discussion__panel-dropdown",
        contentClassName: "editor-post-discussion__panel-dialog",
        focusOnMount: true,
        renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(
          PostDiscussionToggle,
          {
            isOpen: isOpen2,
            onClick: onToggle
          }
        ),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime429.jsx)(ModalContents, { onClose })
      }
    ) }) });
  }

  // packages/editor/build-module/components/post-excerpt/index.mjs
  var import_i18n239 = __toESM(require_i18n(), 1);
  var import_components195 = __toESM(require_components(), 1);
  var import_data136 = __toESM(require_data(), 1);
  var import_element250 = __toESM(require_element(), 1);
  var import_html_entities24 = __toESM(require_html_entities(), 1);
  var import_jsx_runtime430 = __toESM(require_jsx_runtime(), 1);
  function PostExcerpt({
    hideLabelFromVision = false,
    updateOnBlur = false
  }) {
    const { excerpt, shouldUseDescriptionLabel, usedAttribute } = (0, import_data136.useSelect)(
      (select9) => {
        const { getCurrentPostType: getCurrentPostType2, getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
        const postType2 = getCurrentPostType2();
        const _usedAttribute = [
          "wp_template",
          "wp_template_part"
        ].includes(postType2) ? "description" : "excerpt";
        return {
          excerpt: getEditedPostAttribute2(_usedAttribute),
          // There are special cases where we want to label the excerpt as a description.
          shouldUseDescriptionLabel: [
            "wp_template",
            "wp_template_part",
            "wp_block"
          ].includes(postType2),
          usedAttribute: _usedAttribute
        };
      },
      []
    );
    const { editPost: editPost2 } = (0, import_data136.useDispatch)(store);
    const [localExcerpt, setLocalExcerpt] = (0, import_element250.useState)(
      (0, import_html_entities24.decodeEntities)(excerpt)
    );
    const updatePost2 = (value) => {
      editPost2({ [usedAttribute]: value });
    };
    const label = shouldUseDescriptionLabel ? (0, import_i18n239.__)("Write a description (optional)") : (0, import_i18n239.__)("Write an excerpt (optional)");
    return /* @__PURE__ */ (0, import_jsx_runtime430.jsx)("div", { className: "editor-post-excerpt", children: /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
      import_components195.TextareaControl,
      {
        label,
        hideLabelFromVision,
        className: "editor-post-excerpt__textarea",
        onChange: updateOnBlur ? setLocalExcerpt : updatePost2,
        onBlur: updateOnBlur ? () => updatePost2(localExcerpt) : void 0,
        value: updateOnBlur ? localExcerpt : excerpt,
        help: !shouldUseDescriptionLabel ? /* @__PURE__ */ (0, import_jsx_runtime430.jsx)(
          import_components195.ExternalLink,
          {
            href: (0, import_i18n239.__)(
              "https://wordpress.org/documentation/article/page-post-settings-sidebar/#excerpt"
            ),
            children: (0, import_i18n239.__)("Learn more about manual excerpts")
          }
        ) : (0, import_i18n239.__)("Write a description")
      }
    ) });
  }

  // packages/editor/build-module/components/post-excerpt/check.mjs
  var import_jsx_runtime431 = __toESM(require_jsx_runtime(), 1);
  function PostExcerptCheck({ children }) {
    return /* @__PURE__ */ (0, import_jsx_runtime431.jsx)(post_type_support_check_default, { supportKeys: "excerpt", children });
  }
  var check_default3 = PostExcerptCheck;

  // packages/editor/build-module/components/post-excerpt/panel.mjs
  var import_i18n240 = __toESM(require_i18n(), 1);
  var import_components197 = __toESM(require_components(), 1);
  var import_data137 = __toESM(require_data(), 1);
  var import_element251 = __toESM(require_element(), 1);
  var import_block_editor53 = __toESM(require_block_editor(), 1);
  var import_core_data83 = __toESM(require_core_data(), 1);
  var import_html_entities25 = __toESM(require_html_entities(), 1);

  // packages/editor/build-module/components/post-excerpt/plugin.mjs
  var import_components196 = __toESM(require_components(), 1);
  var import_jsx_runtime432 = __toESM(require_jsx_runtime(), 1);
  var { Fill: Fill9, Slot: Slot9 } = (0, import_components196.createSlotFill)("PluginPostExcerpt");
  var PluginPostExcerpt = ({ children, className }) => {
    return /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(Fill9, { children: /* @__PURE__ */ (0, import_jsx_runtime432.jsx)(import_components196.PanelRow, { className, children }) });
  };
  PluginPostExcerpt.Slot = Slot9;
  var plugin_default = PluginPostExcerpt;

  // packages/editor/build-module/components/post-excerpt/panel.mjs
  var import_jsx_runtime433 = __toESM(require_jsx_runtime(), 1);
  var PANEL_NAME3 = "post-excerpt";
  function ExcerptPanel() {
    const { isOpened, isEnabled, postType: postType2 } = (0, import_data137.useSelect)((select9) => {
      const {
        isEditorPanelOpened: isEditorPanelOpened2,
        isEditorPanelEnabled: isEditorPanelEnabled2,
        getCurrentPostType: getCurrentPostType2
      } = select9(store);
      return {
        isOpened: isEditorPanelOpened2(PANEL_NAME3),
        isEnabled: isEditorPanelEnabled2(PANEL_NAME3),
        postType: getCurrentPostType2()
      };
    }, []);
    const { toggleEditorPanelOpened: toggleEditorPanelOpened2 } = (0, import_data137.useDispatch)(store);
    const toggleExcerptPanel = () => toggleEditorPanelOpened2(PANEL_NAME3);
    if (!isEnabled) {
      return null;
    }
    const shouldUseDescriptionLabel = [
      "wp_template",
      "wp_template_part",
      "wp_block"
    ].includes(postType2);
    return /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
      import_components197.PanelBody,
      {
        title: shouldUseDescriptionLabel ? (0, import_i18n240.__)("Description") : (0, import_i18n240.__)("Excerpt"),
        opened: isOpened,
        onToggle: toggleExcerptPanel,
        children: /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(plugin_default.Slot, { children: (fills) => /* @__PURE__ */ (0, import_jsx_runtime433.jsxs)(import_jsx_runtime433.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(PostExcerpt, {}),
          fills
        ] }) })
      }
    );
  }
  function PostExcerptPanel() {
    return /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(check_default3, { children: /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(ExcerptPanel, {}) });
  }
  function PrivatePostExcerptPanel() {
    return /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(check_default3, { children: /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(PrivateExcerpt, {}) });
  }
  function PrivateExcerpt() {
    const { shouldRender, excerpt, shouldBeUsedAsDescription, allowEditing } = (0, import_data137.useSelect)((select9) => {
      const {
        getCurrentPostType: getCurrentPostType2,
        getCurrentPostId: getCurrentPostId2,
        getEditedPostAttribute: getEditedPostAttribute2,
        isEditorPanelEnabled: isEditorPanelEnabled2
      } = select9(store);
      const postType2 = getCurrentPostType2();
      const isTemplateOrTemplatePart2 = [
        "wp_template",
        "wp_template_part"
      ].includes(postType2);
      const isPattern = postType2 === "wp_block";
      const _shouldBeUsedAsDescription = isTemplateOrTemplatePart2 || isPattern;
      const _usedAttribute = isTemplateOrTemplatePart2 ? "description" : "excerpt";
      const _excerpt = getEditedPostAttribute2(_usedAttribute);
      const template2 = isTemplateOrTemplatePart2 && select9(import_core_data83.store).getEntityRecord(
        "postType",
        postType2,
        getCurrentPostId2()
      );
      const fallback = !_excerpt && isTemplateOrTemplatePart2 ? getTemplateInfo({
        template: template2,
        templateTypes: select9(import_core_data83.store).getCurrentTheme()?.default_template_types
      })?.description : void 0;
      const _shouldRender = isEditorPanelEnabled2(PANEL_NAME3) || _shouldBeUsedAsDescription;
      return {
        excerpt: _excerpt ?? fallback,
        shouldRender: _shouldRender,
        shouldBeUsedAsDescription: _shouldBeUsedAsDescription,
        // If we should render, allow editing for all post types that are not used as description.
        // For the rest allow editing only for user generated entities.
        allowEditing: _shouldRender && (!_shouldBeUsedAsDescription || isPattern || template2 && template2.source === TEMPLATE_ORIGINS.custom && !template2.has_theme_file && template2.is_custom)
      };
    }, []);
    const [popoverAnchor, setPopoverAnchor] = (0, import_element251.useState)(null);
    const label = shouldBeUsedAsDescription ? (0, import_i18n240.__)("Description") : (0, import_i18n240.__)("Excerpt");
    const popoverProps = (0, import_element251.useMemo)(
      () => ({
        // Anchor the popover to the middle of the entire row so that it doesn't
        // move around when the label changes.
        anchor: popoverAnchor,
        "aria-label": label,
        headerTitle: label,
        placement: "left-start",
        offset: 36,
        shift: true
      }),
      [popoverAnchor, label]
    );
    if (!shouldRender) {
      return false;
    }
    const excerptText = !!excerpt && /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(import_components197.__experimentalText, { align: "left", numberOfLines: 4, truncate: allowEditing, children: (0, import_html_entities25.decodeEntities)(excerpt) });
    if (!allowEditing) {
      return excerptText;
    }
    const excerptPlaceholder = shouldBeUsedAsDescription ? (0, import_i18n240.__)("Add a description\u2026") : (0, import_i18n240.__)("Add an excerpt\u2026");
    const triggerEditLabel = shouldBeUsedAsDescription ? (0, import_i18n240.__)("Edit description") : (0, import_i18n240.__)("Edit excerpt");
    return /* @__PURE__ */ (0, import_jsx_runtime433.jsxs)(import_components197.__experimentalVStack, { children: [
      excerptText,
      /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
        import_components197.Dropdown,
        {
          className: "editor-post-excerpt__dropdown",
          contentClassName: "editor-post-excerpt__dropdown__content",
          popoverProps,
          focusOnMount: true,
          ref: setPopoverAnchor,
          renderToggle: ({ onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
            import_components197.Button,
            {
              __next40pxDefaultSize: true,
              onClick: onToggle,
              variant: "link",
              children: excerptText ? triggerEditLabel : excerptPlaceholder
            }
          ),
          renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime433.jsxs)(import_jsx_runtime433.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
              import_block_editor53.__experimentalInspectorPopoverHeader,
              {
                title: label,
                onClose
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(import_components197.__experimentalVStack, { spacing: 4, children: /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(plugin_default.Slot, { children: (fills) => /* @__PURE__ */ (0, import_jsx_runtime433.jsxs)(import_jsx_runtime433.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime433.jsx)(
                PostExcerpt,
                {
                  hideLabelFromVision: true,
                  updateOnBlur: true
                }
              ),
              fills
            ] }) }) })
          ] })
        }
      )
    ] });
  }

  // packages/editor/build-module/components/post-featured-image/index.mjs
  var import_i18n241 = __toESM(require_i18n(), 1);
  var import_hooks49 = __toESM(require_hooks(), 1);
  var import_components198 = __toESM(require_components(), 1);
  var import_blob3 = __toESM(require_blob(), 1);
  var import_element252 = __toESM(require_element(), 1);
  var import_compose45 = __toESM(require_compose(), 1);
  var import_data139 = __toESM(require_data(), 1);
  var import_block_editor54 = __toESM(require_block_editor(), 1);
  var import_core_data85 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/theme-support-check/index.mjs
  var import_data138 = __toESM(require_data(), 1);
  var import_core_data84 = __toESM(require_core_data(), 1);
  function ThemeSupportCheck({ children, supportKeys }) {
    const { postType: postType2, themeSupports } = (0, import_data138.useSelect)((select9) => {
      return {
        postType: select9(store).getEditedPostAttribute("type"),
        themeSupports: select9(import_core_data84.store).getThemeSupports()
      };
    }, []);
    const isSupported = (Array.isArray(supportKeys) ? supportKeys : [supportKeys]).some((key) => {
      const supported = themeSupports?.[key] ?? false;
      if ("post-thumbnails" === key && Array.isArray(supported)) {
        return supported.includes(postType2);
      }
      return supported;
    });
    if (!isSupported) {
      return null;
    }
    return children;
  }

  // packages/editor/build-module/components/post-featured-image/check.mjs
  var import_jsx_runtime434 = __toESM(require_jsx_runtime(), 1);
  function PostFeaturedImageCheck({ children }) {
    return /* @__PURE__ */ (0, import_jsx_runtime434.jsx)(ThemeSupportCheck, { supportKeys: "post-thumbnails", children: /* @__PURE__ */ (0, import_jsx_runtime434.jsx)(post_type_support_check_default, { supportKeys: "thumbnail", children }) });
  }
  var check_default4 = PostFeaturedImageCheck;

  // packages/editor/build-module/components/post-featured-image/index.mjs
  var import_jsx_runtime435 = __toESM(require_jsx_runtime(), 1);
  var ALLOWED_MEDIA_TYPES = ["image"];
  var DEFAULT_FEATURE_IMAGE_LABEL = (0, import_i18n241.__)("Featured image");
  var DEFAULT_SET_FEATURE_IMAGE_LABEL = (0, import_i18n241.__)("Add a featured image");
  var instructions = /* @__PURE__ */ (0, import_jsx_runtime435.jsx)("p", { children: (0, import_i18n241.__)(
    "To edit the featured image, you need permission to upload media."
  ) });
  function getMediaDetails(media, postId2) {
    if (!media) {
      return {};
    }
    const defaultSize = (0, import_hooks49.applyFilters)(
      "editor.PostFeaturedImage.imageSize",
      "large",
      media.id,
      postId2
    );
    if (defaultSize in (media?.media_details?.sizes ?? {})) {
      return {
        mediaWidth: media.media_details.sizes[defaultSize].width,
        mediaHeight: media.media_details.sizes[defaultSize].height,
        mediaSourceUrl: media.media_details.sizes[defaultSize].source_url
      };
    }
    const fallbackSize = (0, import_hooks49.applyFilters)(
      "editor.PostFeaturedImage.imageSize",
      "thumbnail",
      media.id,
      postId2
    );
    if (fallbackSize in (media?.media_details?.sizes ?? {})) {
      return {
        mediaWidth: media.media_details.sizes[fallbackSize].width,
        mediaHeight: media.media_details.sizes[fallbackSize].height,
        mediaSourceUrl: media.media_details.sizes[fallbackSize].source_url
      };
    }
    return {
      mediaWidth: media.media_details.width,
      mediaHeight: media.media_details.height,
      mediaSourceUrl: media.source_url
    };
  }
  function PostFeaturedImage({
    currentPostId,
    featuredImageId,
    onUpdateImage,
    onRemoveImage,
    media,
    postType: postType2,
    noticeUI,
    noticeOperations,
    isRequestingFeaturedImageMedia
  }) {
    const returnsFocusRef = (0, import_element252.useRef)(false);
    const [isLoading, setIsLoading] = (0, import_element252.useState)(false);
    const { getSettings: getSettings10 } = (0, import_data139.useSelect)(import_block_editor54.store);
    const { mediaSourceUrl } = getMediaDetails(media, currentPostId);
    function onDropFiles(filesList) {
      getSettings10().mediaUpload({
        allowedTypes: ALLOWED_MEDIA_TYPES,
        filesList,
        onFileChange([image]) {
          if ((0, import_blob3.isBlobURL)(image?.url)) {
            setIsLoading(true);
            return;
          }
          if (image) {
            onUpdateImage(image);
          }
          setIsLoading(false);
        },
        onError(message2) {
          noticeOperations.removeAllNotices();
          noticeOperations.createErrorNotice(message2);
        },
        multiple: false
      });
    }
    function getImageDescription(imageMedia) {
      if (imageMedia.alt_text) {
        return (0, import_i18n241.sprintf)(
          // Translators: %s: The selected image alt text.
          (0, import_i18n241.__)("Current image: %s"),
          imageMedia.alt_text
        );
      }
      return (0, import_i18n241.sprintf)(
        // Translators: %s: The selected image filename.
        (0, import_i18n241.__)(
          "The current image has no alternative text. The file name is: %s"
        ),
        imageMedia.media_details.sizes?.full?.file || imageMedia.slug
      );
    }
    function returnFocus(node) {
      if (returnsFocusRef.current && node) {
        node.focus();
        returnsFocusRef.current = false;
      }
    }
    const isMissingMedia = !isRequestingFeaturedImageMedia && !!featuredImageId && !media;
    return /* @__PURE__ */ (0, import_jsx_runtime435.jsxs)(check_default4, { children: [
      noticeUI,
      /* @__PURE__ */ (0, import_jsx_runtime435.jsxs)("div", { className: "editor-post-featured-image", children: [
        media && /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(
          "div",
          {
            id: `editor-post-featured-image-${featuredImageId}-describedby`,
            className: "hidden",
            children: getImageDescription(media)
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(import_block_editor54.MediaUploadCheck, { fallback: instructions, children: /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(
          import_block_editor54.MediaUpload,
          {
            title: postType2?.labels?.featured_image || DEFAULT_FEATURE_IMAGE_LABEL,
            onSelect: onUpdateImage,
            unstableFeaturedImageFlow: true,
            allowedTypes: ALLOWED_MEDIA_TYPES,
            modalClass: "editor-post-featured-image__media-modal",
            render: ({ open }) => /* @__PURE__ */ (0, import_jsx_runtime435.jsxs)("div", { className: "editor-post-featured-image__container", children: [
              isMissingMedia ? /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(
                import_components198.Notice,
                {
                  status: "warning",
                  isDismissible: false,
                  children: (0, import_i18n241.__)(
                    "Could not retrieve the featured image data."
                  )
                }
              ) : /* @__PURE__ */ (0, import_jsx_runtime435.jsxs)(
                import_components198.Button,
                {
                  __next40pxDefaultSize: true,
                  ref: returnFocus,
                  className: !featuredImageId ? "editor-post-featured-image__toggle" : "editor-post-featured-image__preview",
                  onClick: open,
                  "aria-label": !featuredImageId ? null : (0, import_i18n241.__)(
                    "Edit or replace the featured image"
                  ),
                  "aria-describedby": !featuredImageId ? null : `editor-post-featured-image-${featuredImageId}-describedby`,
                  "aria-haspopup": "dialog",
                  disabled: isLoading,
                  accessibleWhenDisabled: true,
                  children: [
                    !!featuredImageId && media && /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(
                      "img",
                      {
                        className: "editor-post-featured-image__preview-image",
                        src: mediaSourceUrl,
                        alt: getImageDescription(
                          media
                        )
                      }
                    ),
                    (isLoading || isRequestingFeaturedImageMedia) && /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(import_components198.Spinner, {}),
                    !featuredImageId && !isLoading && (postType2?.labels?.set_featured_image || DEFAULT_SET_FEATURE_IMAGE_LABEL)
                  ]
                }
              ),
              !!featuredImageId && /* @__PURE__ */ (0, import_jsx_runtime435.jsxs)(
                import_components198.__experimentalHStack,
                {
                  className: clsx_default(
                    "editor-post-featured-image__actions",
                    {
                      "editor-post-featured-image__actions-missing-image": isMissingMedia,
                      "editor-post-featured-image__actions-is-requesting-image": isRequestingFeaturedImageMedia
                    }
                  ),
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(
                      import_components198.Button,
                      {
                        __next40pxDefaultSize: true,
                        className: "editor-post-featured-image__action",
                        onClick: open,
                        "aria-haspopup": "dialog",
                        variant: isMissingMedia ? "secondary" : void 0,
                        children: (0, import_i18n241.__)("Replace")
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(
                      import_components198.Button,
                      {
                        __next40pxDefaultSize: true,
                        className: "editor-post-featured-image__action",
                        onClick: () => {
                          onRemoveImage();
                          returnsFocusRef.current = true;
                        },
                        variant: isMissingMedia ? "secondary" : void 0,
                        isDestructive: isMissingMedia,
                        children: (0, import_i18n241.__)("Remove")
                      }
                    )
                  ]
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime435.jsx)(import_components198.DropZone, { onFilesDrop: onDropFiles })
            ] }),
            value: featuredImageId
          }
        ) })
      ] })
    ] });
  }
  var applyWithSelect = (0, import_data139.withSelect)((select9) => {
    const { getEntityRecord, getPostType, hasFinishedResolution } = select9(import_core_data85.store);
    const { getCurrentPostId: getCurrentPostId2, getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
    const featuredImageId = getEditedPostAttribute2("featured_media");
    return {
      media: featuredImageId ? getEntityRecord("postType", "attachment", featuredImageId, {
        context: "view"
      }) : null,
      currentPostId: getCurrentPostId2(),
      postType: getPostType(getEditedPostAttribute2("type")),
      featuredImageId,
      isRequestingFeaturedImageMedia: !!featuredImageId && !hasFinishedResolution("getEntityRecord", [
        "postType",
        "attachment",
        featuredImageId,
        { context: "view" }
      ])
    };
  });
  var applyWithDispatch = (0, import_data139.withDispatch)(
    (dispatch8, { noticeOperations }, { select: select9 }) => {
      const { editPost: editPost2 } = dispatch8(store);
      return {
        onUpdateImage(image) {
          editPost2({ featured_media: image.id });
        },
        onDropImage(filesList) {
          select9(import_block_editor54.store).getSettings().mediaUpload({
            allowedTypes: ["image"],
            filesList,
            onFileChange([image]) {
              editPost2({ featured_media: image.id });
            },
            onError(message2) {
              noticeOperations.removeAllNotices();
              noticeOperations.createErrorNotice(message2);
            },
            multiple: false
          });
        },
        onRemoveImage() {
          editPost2({ featured_media: 0 });
        }
      };
    }
  );
  var post_featured_image_default = (0, import_compose45.compose)(
    import_components198.withNotices,
    applyWithSelect,
    applyWithDispatch,
    (0, import_components198.withFilters)("editor.PostFeaturedImage")
  )(PostFeaturedImage);

  // packages/editor/build-module/components/post-featured-image/panel.mjs
  var import_i18n242 = __toESM(require_i18n(), 1);
  var import_components199 = __toESM(require_components(), 1);
  var import_data140 = __toESM(require_data(), 1);
  var import_core_data86 = __toESM(require_core_data(), 1);
  var import_jsx_runtime436 = __toESM(require_jsx_runtime(), 1);
  var PANEL_NAME4 = "featured-image";
  function PostFeaturedImagePanel({ withPanelBody = true }) {
    const { postType: postType2, isEnabled, isOpened } = (0, import_data140.useSelect)((select9) => {
      const {
        getEditedPostAttribute: getEditedPostAttribute2,
        isEditorPanelEnabled: isEditorPanelEnabled2,
        isEditorPanelOpened: isEditorPanelOpened2
      } = select9(store);
      const { getPostType } = select9(import_core_data86.store);
      return {
        postType: getPostType(getEditedPostAttribute2("type")),
        isEnabled: isEditorPanelEnabled2(PANEL_NAME4),
        isOpened: isEditorPanelOpened2(PANEL_NAME4)
      };
    }, []);
    const { toggleEditorPanelOpened: toggleEditorPanelOpened2 } = (0, import_data140.useDispatch)(store);
    if (!isEnabled) {
      return null;
    }
    if (!withPanelBody) {
      return /* @__PURE__ */ (0, import_jsx_runtime436.jsx)(check_default4, { children: /* @__PURE__ */ (0, import_jsx_runtime436.jsx)(post_featured_image_default, {}) });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime436.jsx)(check_default4, { children: /* @__PURE__ */ (0, import_jsx_runtime436.jsx)(
      import_components199.PanelBody,
      {
        title: postType2?.labels?.featured_image ?? (0, import_i18n242.__)("Featured image"),
        opened: isOpened,
        onToggle: () => toggleEditorPanelOpened2(PANEL_NAME4),
        children: /* @__PURE__ */ (0, import_jsx_runtime436.jsx)(post_featured_image_default, {})
      }
    ) });
  }

  // packages/editor/build-module/components/post-format/index.mjs
  var import_i18n243 = __toESM(require_i18n(), 1);
  var import_components200 = __toESM(require_components(), 1);
  var import_data142 = __toESM(require_data(), 1);
  var import_compose46 = __toESM(require_compose(), 1);
  var import_core_data87 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/post-format/check.mjs
  var import_data141 = __toESM(require_data(), 1);
  var import_jsx_runtime437 = __toESM(require_jsx_runtime(), 1);
  function PostFormatCheck({ children }) {
    const disablePostFormats = (0, import_data141.useSelect)(
      (select9) => select9(store).getEditorSettings().disablePostFormats,
      []
    );
    if (disablePostFormats) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime437.jsx)(post_type_support_check_default, { supportKeys: "post-formats", children });
  }

  // packages/editor/build-module/components/post-format/index.mjs
  var import_jsx_runtime438 = __toESM(require_jsx_runtime(), 1);
  var POST_FORMATS2 = [
    { id: "aside", caption: (0, import_i18n243.__)("Aside") },
    { id: "audio", caption: (0, import_i18n243.__)("Audio") },
    { id: "chat", caption: (0, import_i18n243.__)("Chat") },
    { id: "gallery", caption: (0, import_i18n243.__)("Gallery") },
    { id: "image", caption: (0, import_i18n243.__)("Image") },
    { id: "link", caption: (0, import_i18n243.__)("Link") },
    { id: "quote", caption: (0, import_i18n243.__)("Quote") },
    { id: "standard", caption: (0, import_i18n243.__)("Standard") },
    { id: "status", caption: (0, import_i18n243.__)("Status") },
    { id: "video", caption: (0, import_i18n243.__)("Video") }
  ].sort((a3, b3) => {
    const normalizedA = a3.caption.toUpperCase();
    const normalizedB = b3.caption.toUpperCase();
    if (normalizedA < normalizedB) {
      return -1;
    }
    if (normalizedA > normalizedB) {
      return 1;
    }
    return 0;
  });
  function PostFormat() {
    const instanceId = (0, import_compose46.useInstanceId)(PostFormat);
    const postFormatSelectorId = `post-format-selector-${instanceId}`;
    const { postFormat, suggestedFormat, supportedFormats } = (0, import_data142.useSelect)(
      (select9) => {
        const { getEditedPostAttribute: getEditedPostAttribute2, getSuggestedPostFormat: getSuggestedPostFormat2 } = select9(store);
        const _postFormat = getEditedPostAttribute2("format");
        const themeSupports = select9(import_core_data87.store).getThemeSupports();
        return {
          postFormat: _postFormat ?? "standard",
          suggestedFormat: getSuggestedPostFormat2(),
          supportedFormats: themeSupports.formats
        };
      },
      []
    );
    const formats = POST_FORMATS2.filter((format6) => {
      return supportedFormats?.includes(format6.id) || postFormat === format6.id;
    });
    const suggestion = formats.find(
      (format6) => format6.id === suggestedFormat
    );
    const { editPost: editPost2 } = (0, import_data142.useDispatch)(store);
    const onUpdatePostFormat = (format6) => editPost2({ format: format6 });
    return /* @__PURE__ */ (0, import_jsx_runtime438.jsx)(PostFormatCheck, { children: /* @__PURE__ */ (0, import_jsx_runtime438.jsxs)("div", { className: "editor-post-format", children: [
      /* @__PURE__ */ (0, import_jsx_runtime438.jsx)(
        import_components200.RadioControl,
        {
          className: "editor-post-format__options",
          label: (0, import_i18n243.__)("Post Format"),
          selected: postFormat,
          onChange: (format6) => onUpdatePostFormat(format6),
          id: postFormatSelectorId,
          options: formats.map((format6) => ({
            label: format6.caption,
            value: format6.id
          })),
          hideLabelFromVision: true
        }
      ),
      suggestion && suggestion.id !== postFormat && /* @__PURE__ */ (0, import_jsx_runtime438.jsx)("p", { className: "editor-post-format__suggestion", children: /* @__PURE__ */ (0, import_jsx_runtime438.jsx)(
        import_components200.Button,
        {
          __next40pxDefaultSize: true,
          variant: "link",
          onClick: () => onUpdatePostFormat(suggestion.id),
          children: (0, import_i18n243.sprintf)(
            /* translators: %s: post format */
            (0, import_i18n243.__)("Apply suggested format: %s"),
            suggestion.caption
          )
        }
      ) })
    ] }) });
  }

  // packages/editor/build-module/components/post-last-revision/index.mjs
  var import_i18n244 = __toESM(require_i18n(), 1);
  var import_components201 = __toESM(require_components(), 1);
  var import_data144 = __toESM(require_data(), 1);
  var import_url17 = __toESM(require_url(), 1);

  // packages/editor/build-module/components/post-last-revision/check.mjs
  var import_data143 = __toESM(require_data(), 1);
  var import_jsx_runtime439 = __toESM(require_jsx_runtime(), 1);
  function PostLastRevisionCheck({ children }) {
    const { lastRevisionId, revisionsCount } = (0, import_data143.useSelect)((select9) => {
      const { getCurrentPostLastRevisionId: getCurrentPostLastRevisionId2, getCurrentPostRevisionsCount: getCurrentPostRevisionsCount2 } = select9(store);
      return {
        lastRevisionId: getCurrentPostLastRevisionId2(),
        revisionsCount: getCurrentPostRevisionsCount2()
      };
    }, []);
    if (!lastRevisionId || revisionsCount < 2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime439.jsx)(post_type_support_check_default, { supportKeys: "revisions", children });
  }
  var check_default5 = PostLastRevisionCheck;

  // packages/editor/build-module/components/post-last-revision/index.mjs
  var import_jsx_runtime440 = __toESM(require_jsx_runtime(), 1);
  function usePostLastRevisionInfo() {
    return (0, import_data144.useSelect)((select9) => {
      const {
        getCurrentPostLastRevisionId: getCurrentPostLastRevisionId2,
        getCurrentPostRevisionsCount: getCurrentPostRevisionsCount2,
        getEditorSettings: getEditorSettings2
      } = select9(store);
      return {
        lastRevisionId: getCurrentPostLastRevisionId2(),
        revisionsCount: getCurrentPostRevisionsCount2(),
        disableVisualRevisions: !!getEditorSettings2().disableVisualRevisions
      };
    }, []);
  }
  function PostLastRevision() {
    const { lastRevisionId, revisionsCount, disableVisualRevisions } = usePostLastRevisionInfo();
    const { setCurrentRevisionId: setCurrentRevisionId2 } = unlock((0, import_data144.useDispatch)(store));
    const buttonProps = disableVisualRevisions ? {
      href: (0, import_url17.addQueryArgs)("revision.php", {
        revision: lastRevisionId
      })
    } : { onClick: () => setCurrentRevisionId2(lastRevisionId) };
    return /* @__PURE__ */ (0, import_jsx_runtime440.jsx)(check_default5, { children: /* @__PURE__ */ (0, import_jsx_runtime440.jsx)(
      import_components201.Button,
      {
        __next40pxDefaultSize: true,
        ...buttonProps,
        className: "editor-post-last-revision__title",
        icon: backup_default,
        iconPosition: "right",
        text: (0, import_i18n244.sprintf)(
          /* translators: %s: number of revisions. */
          (0, import_i18n244.__)("Revisions (%s)"),
          revisionsCount
        )
      }
    ) });
  }
  function PrivatePostLastRevision() {
    const { lastRevisionId, revisionsCount, disableVisualRevisions } = usePostLastRevisionInfo();
    const { setCurrentRevisionId: setCurrentRevisionId2 } = unlock((0, import_data144.useDispatch)(store));
    const buttonProps = disableVisualRevisions ? {
      href: (0, import_url17.addQueryArgs)("revision.php", {
        revision: lastRevisionId
      })
    } : { onClick: () => setCurrentRevisionId2(lastRevisionId) };
    return /* @__PURE__ */ (0, import_jsx_runtime440.jsx)(check_default5, { children: /* @__PURE__ */ (0, import_jsx_runtime440.jsx)(post_panel_row_default, { label: (0, import_i18n244.__)("Revisions"), children: /* @__PURE__ */ (0, import_jsx_runtime440.jsx)(
      import_components201.Button,
      {
        ...buttonProps,
        className: "editor-private-post-last-revision__button",
        text: revisionsCount,
        "aria-label": (0, import_i18n244.sprintf)(
          /* translators: %d: number of revisions. */
          (0, import_i18n244._n)(
            "Open revisions screen: %d revision",
            "Open revisions screen: %d revisions",
            revisionsCount
          ),
          revisionsCount
        ),
        variant: "tertiary",
        size: "compact"
      }
    ) }) });
  }
  var post_last_revision_default = PostLastRevision;

  // packages/editor/build-module/components/post-last-revision/panel.mjs
  var import_components202 = __toESM(require_components(), 1);
  var import_jsx_runtime441 = __toESM(require_jsx_runtime(), 1);
  function PostLastRevisionPanel() {
    return /* @__PURE__ */ (0, import_jsx_runtime441.jsx)(check_default5, { children: /* @__PURE__ */ (0, import_jsx_runtime441.jsx)(import_components202.PanelBody, { className: "editor-post-last-revision__panel", children: /* @__PURE__ */ (0, import_jsx_runtime441.jsx)(post_last_revision_default, {}) }) });
  }
  var panel_default2 = PostLastRevisionPanel;

  // packages/editor/build-module/components/post-locked-modal/index.mjs
  var import_i18n246 = __toESM(require_i18n(), 1);
  var import_components203 = __toESM(require_components(), 1);
  var import_data145 = __toESM(require_data(), 1);
  var import_url18 = __toESM(require_url(), 1);
  var import_element253 = __toESM(require_element(), 1);
  var import_hooks50 = __toESM(require_hooks(), 1);
  var import_compose47 = __toESM(require_compose(), 1);
  var import_core_data88 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/utils/sync-error-messages.mjs
  var import_i18n245 = __toESM(require_i18n(), 1);
  var AUTHENTICATION_FAILED = "authentication-failed";
  var CONNECTION_EXPIRED = "connection-expired";
  var CONNECTION_LIMIT_EXCEEDED = "connection-limit-exceeded";
  var DOCUMENT_SIZE_LIMIT_EXCEEDED = "document-size-limit-exceeded";
  var PROTOCOL_MISMATCH = "protocol-mismatch";
  var UNKNOWN_ERROR = "unknown-error";
  var ERROR_MESSAGES = {
    [AUTHENTICATION_FAILED]: {
      title: (0, import_i18n245.__)("Unable to connect"),
      description: (0, import_i18n245.__)(
        "Real-time collaboration couldn't verify your permissions. Check that you have access to edit this post or contact your site administrator."
      )
    },
    [CONNECTION_EXPIRED]: {
      title: (0, import_i18n245.__)("Connection expired"),
      description: (0, import_i18n245.__)(
        "Your connection to real-time collaboration has timed out. Editing is paused to prevent conflicts with other editors."
      )
    },
    [CONNECTION_LIMIT_EXCEEDED]: {
      title: (0, import_i18n245.__)("Too many editors connected"),
      description: (0, import_i18n245.__)(
        "Real-time collaboration has reached its connection limit. Try again later or contact your site administrator."
      )
    },
    [PROTOCOL_MISMATCH]: {
      title: (0, import_i18n245.__)("Protocol update"),
      description: (0, import_i18n245.__)(
        "Real-time collaboration has been updated. Please refresh the page to continue editing."
      )
    },
    // DOCUMENT_SIZE_LIMIT_EXCEEDED is not included here because it results in
    // collaboration being disabled entirely.
    [UNKNOWN_ERROR]: {
      title: (0, import_i18n245.__)("Connection lost"),
      description: (0, import_i18n245.__)(
        "The connection to real-time collaboration was interrupted. Editing is paused to prevent conflicts with other editors."
      )
    }
  };
  function getSyncErrorMessages(error2) {
    if (error2?.code && ERROR_MESSAGES[error2?.code]) {
      return ERROR_MESSAGES[error2.code];
    }
    return ERROR_MESSAGES[UNKNOWN_ERROR];
  }

  // packages/editor/build-module/components/post-locked-modal/index.mjs
  var import_jsx_runtime442 = __toESM(require_jsx_runtime(), 1);
  function CollaborationContext() {
    const { isCollaborationSupported, syncConnectionStatus } = (0, import_data145.useSelect)(
      (select9) => {
        const {
          isCollaborationSupported: isSupported,
          getSyncConnectionStatus
        } = unlock(select9(import_core_data88.store));
        return {
          isCollaborationSupported: isSupported(),
          syncConnectionStatus: getSyncConnectionStatus()
        };
      },
      []
    );
    if (isCollaborationSupported) {
      return null;
    }
    if (DOCUMENT_SIZE_LIMIT_EXCEEDED === syncConnectionStatus?.error?.code) {
      return /* @__PURE__ */ (0, import_jsx_runtime442.jsx)("p", { children: (0, import_i18n246.__)(
        "Because this post is too large for real-time collaboration, only one person can edit at a time."
      ) });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime442.jsx)("p", { children: (0, import_i18n246.__)(
      "Because this post uses plugins that aren\u2019t compatible with real-time collaboration, only one person can edit at a time."
    ) });
  }
  function PostLockedModal() {
    const instanceId = (0, import_compose47.useInstanceId)(PostLockedModal);
    const hookName = "core/editor/post-locked-modal-" + instanceId;
    const { autosave: autosave2, updatePostLock: updatePostLock2 } = (0, import_data145.useDispatch)(store);
    const {
      isCollaborationEnabled,
      isLocked,
      isTakeover,
      user,
      postId: postId2,
      postLockUtils,
      activePostLock,
      postType: postType2,
      previewLink
    } = (0, import_data145.useSelect)((select9) => {
      const {
        isPostLocked: isPostLocked2,
        isPostLockTakeover: isPostLockTakeover2,
        getPostLockUser: getPostLockUser2,
        getCurrentPostId: getCurrentPostId2,
        getActivePostLock: getActivePostLock2,
        getEditedPostAttribute: getEditedPostAttribute2,
        getEditedPostPreviewLink: getEditedPostPreviewLink2,
        getEditorSettings: getEditorSettings2,
        isCollaborationEnabledForCurrentPost: isCollaborationEnabledForCurrentPost2
      } = unlock(select9(store));
      const { getPostType } = select9(import_core_data88.store);
      return {
        isCollaborationEnabled: isCollaborationEnabledForCurrentPost2(),
        isLocked: isPostLocked2(),
        isTakeover: isPostLockTakeover2(),
        user: getPostLockUser2(),
        postId: getCurrentPostId2(),
        postLockUtils: getEditorSettings2().postLockUtils,
        activePostLock: getActivePostLock2(),
        postType: getPostType(getEditedPostAttribute2("type")),
        previewLink: getEditedPostPreviewLink2()
      };
    }, []);
    (0, import_element253.useEffect)(() => {
      function sendPostLock(data) {
        if (isLocked) {
          return;
        }
        data["wp-refresh-post-lock"] = {
          lock: activePostLock,
          post_id: postId2
        };
      }
      function receivePostLock(data) {
        if (!data["wp-refresh-post-lock"]) {
          return;
        }
        const received = data["wp-refresh-post-lock"];
        if (received.lock_error) {
          autosave2();
          updatePostLock2({
            isLocked: true,
            isTakeover: true,
            user: {
              name: received.lock_error.name,
              avatar: received.lock_error.avatar_src_2x
            }
          });
        } else if (received.new_lock) {
          updatePostLock2({
            isLocked: false,
            activePostLock: received.new_lock
          });
        }
      }
      function releasePostLock() {
        if (isLocked || !activePostLock) {
          return;
        }
        const data = new window.FormData();
        data.append("action", "wp-remove-post-lock");
        data.append("_wpnonce", postLockUtils.unlockNonce);
        data.append("post_ID", postId2);
        data.append("active_post_lock", activePostLock);
        if (window.navigator.sendBeacon) {
          window.navigator.sendBeacon(postLockUtils.ajaxUrl, data);
        } else {
          const xhr = new window.XMLHttpRequest();
          xhr.open("POST", postLockUtils.ajaxUrl, false);
          xhr.send(data);
        }
      }
      (0, import_hooks50.addAction)("heartbeat.send", hookName, sendPostLock);
      (0, import_hooks50.addAction)("heartbeat.tick", hookName, receivePostLock);
      window.addEventListener("beforeunload", releasePostLock);
      return () => {
        (0, import_hooks50.removeAction)("heartbeat.send", hookName);
        (0, import_hooks50.removeAction)("heartbeat.tick", hookName);
        window.removeEventListener("beforeunload", releasePostLock);
      };
    }, []);
    if (!isLocked) {
      return null;
    }
    if (isCollaborationEnabled) {
      return null;
    }
    const userDisplayName = user.name;
    const userAvatar = user.avatar;
    const unlockUrl = (0, import_url18.addQueryArgs)("post.php", {
      "get-post-lock": "1",
      lockKey: true,
      post: postId2,
      action: "edit",
      _wpnonce: postLockUtils.nonce
    });
    const allPostsUrl = (0, import_url18.addQueryArgs)("edit.php", {
      post_type: postType2?.slug
    });
    const allPostsLabel = (0, import_i18n246.__)("Exit editor");
    return /* @__PURE__ */ (0, import_jsx_runtime442.jsx)(
      import_components203.Modal,
      {
        title: isTakeover ? (0, import_i18n246.__)("Someone else has taken over this post") : (0, import_i18n246.__)("This post is already being edited"),
        focusOnMount: true,
        shouldCloseOnClickOutside: false,
        shouldCloseOnEsc: false,
        isDismissible: false,
        className: "editor-post-locked-modal",
        size: "medium",
        children: /* @__PURE__ */ (0, import_jsx_runtime442.jsxs)(import_components203.__experimentalHStack, { alignment: "top", spacing: 6, children: [
          !!userAvatar && /* @__PURE__ */ (0, import_jsx_runtime442.jsx)(
            "img",
            {
              src: userAvatar,
              alt: (0, import_i18n246.__)("Avatar"),
              className: "editor-post-locked-modal__avatar",
              width: 64,
              height: 64
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime442.jsxs)("div", { children: [
            !!isTakeover && /* @__PURE__ */ (0, import_jsx_runtime442.jsxs)(import_jsx_runtime442.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime442.jsx)("p", { children: (0, import_element253.createInterpolateElement)(
                userDisplayName ? (0, import_i18n246.sprintf)(
                  /* translators: %s: user's display name */
                  (0, import_i18n246.__)(
                    "<strong>%s</strong> now has editing control of this post (<PreviewLink />). Don\u2019t worry, your changes up to this moment have been saved."
                  ),
                  userDisplayName
                ) : (0, import_i18n246.__)(
                  "Another user now has editing control of this post (<PreviewLink />). Don\u2019t worry, your changes up to this moment have been saved."
                ),
                {
                  strong: /* @__PURE__ */ (0, import_jsx_runtime442.jsx)("strong", {}),
                  PreviewLink: /* @__PURE__ */ (0, import_jsx_runtime442.jsx)(import_components203.ExternalLink, { href: previewLink, children: (0, import_i18n246.__)("preview") })
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime442.jsx)(CollaborationContext, {})
            ] }),
            !isTakeover && /* @__PURE__ */ (0, import_jsx_runtime442.jsxs)(import_jsx_runtime442.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime442.jsx)("p", { children: (0, import_element253.createInterpolateElement)(
                userDisplayName ? (0, import_i18n246.sprintf)(
                  /* translators: %s: user's display name */
                  (0, import_i18n246.__)(
                    "<strong>%s</strong> is currently working on this post (<PreviewLink />), which means you cannot make changes, unless you take over."
                  ),
                  userDisplayName
                ) : (0, import_i18n246.__)(
                  "Another user is currently working on this post (<PreviewLink />), which means you cannot make changes, unless you take over."
                ),
                {
                  strong: /* @__PURE__ */ (0, import_jsx_runtime442.jsx)("strong", {}),
                  PreviewLink: /* @__PURE__ */ (0, import_jsx_runtime442.jsx)(import_components203.ExternalLink, { href: previewLink, children: (0, import_i18n246.__)("preview") })
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime442.jsx)(CollaborationContext, {}),
              /* @__PURE__ */ (0, import_jsx_runtime442.jsx)("p", { children: (0, import_i18n246.__)(
                "If you take over, the other user will lose editing control to the post, but their changes will be saved."
              ) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime442.jsxs)(
              import_components203.__experimentalHStack,
              {
                className: "editor-post-locked-modal__buttons",
                justify: "flex-end",
                children: [
                  !isTakeover && /* @__PURE__ */ (0, import_jsx_runtime442.jsx)(
                    import_components203.Button,
                    {
                      __next40pxDefaultSize: true,
                      variant: "tertiary",
                      href: unlockUrl,
                      children: (0, import_i18n246.__)("Take over")
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime442.jsx)(
                    import_components203.Button,
                    {
                      __next40pxDefaultSize: true,
                      variant: "primary",
                      href: allPostsUrl,
                      children: allPostsLabel
                    }
                  )
                ]
              }
            )
          ] })
        ] })
      }
    );
  }
  var post_locked_modal_default = false ? (0, import_components203.withFilters)("editor.PostLockedModal")(PostLockedModal) : PostLockedModal;

  // packages/editor/build-module/components/post-pending-status/index.mjs
  var import_i18n247 = __toESM(require_i18n(), 1);
  var import_components204 = __toESM(require_components(), 1);
  var import_data147 = __toESM(require_data(), 1);

  // packages/editor/build-module/components/post-pending-status/check.mjs
  var import_data146 = __toESM(require_data(), 1);
  function PostPendingStatusCheck({ children }) {
    const { hasPublishAction, isPublished } = (0, import_data146.useSelect)((select9) => {
      const { isCurrentPostPublished: isCurrentPostPublished2, getCurrentPost: getCurrentPost2 } = select9(store);
      return {
        hasPublishAction: getCurrentPost2()._links?.["wp:action-publish"] ?? false,
        isPublished: isCurrentPostPublished2()
      };
    }, []);
    if (isPublished || !hasPublishAction) {
      return null;
    }
    return children;
  }
  var check_default6 = PostPendingStatusCheck;

  // packages/editor/build-module/components/post-pending-status/index.mjs
  var import_jsx_runtime443 = __toESM(require_jsx_runtime(), 1);
  function PostPendingStatus() {
    const status = (0, import_data147.useSelect)(
      (select9) => select9(store).getEditedPostAttribute("status"),
      []
    );
    const { editPost: editPost2 } = (0, import_data147.useDispatch)(store);
    const togglePendingStatus = () => {
      const updatedStatus = status === "pending" ? "draft" : "pending";
      editPost2({ status: updatedStatus });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime443.jsx)(check_default6, { children: /* @__PURE__ */ (0, import_jsx_runtime443.jsx)(
      import_components204.CheckboxControl,
      {
        label: (0, import_i18n247.__)("Pending review"),
        checked: status === "pending",
        onChange: togglePendingStatus
      }
    ) });
  }
  var post_pending_status_default = PostPendingStatus;

  // packages/editor/build-module/components/post-preview-button/index.mjs
  var import_element254 = __toESM(require_element(), 1);
  var import_components205 = __toESM(require_components(), 1);
  var import_i18n248 = __toESM(require_i18n(), 1);
  var import_data148 = __toESM(require_data(), 1);
  var import_hooks51 = __toESM(require_hooks(), 1);
  var import_core_data89 = __toESM(require_core_data(), 1);
  var import_jsx_runtime444 = __toESM(require_jsx_runtime(), 1);
  function buildInterstitialMarkup() {
    let markup = (0, import_element254.renderToString)(
      /* @__PURE__ */ (0, import_jsx_runtime444.jsxs)("div", { className: "editor-post-preview-button__interstitial-message", children: [
        /* @__PURE__ */ (0, import_jsx_runtime444.jsxs)(import_components205.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 96 96", children: [
          /* @__PURE__ */ (0, import_jsx_runtime444.jsx)(
            import_components205.Path,
            {
              className: "outer",
              d: "M48 12c19.9 0 36 16.1 36 36S67.9 84 48 84 12 67.9 12 48s16.1-36 36-36",
              fill: "none"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime444.jsx)(
            import_components205.Path,
            {
              className: "inner",
              d: "M69.5 46.4c0-3.9-1.4-6.7-2.6-8.8-1.6-2.6-3.1-4.9-3.1-7.5 0-2.9 2.2-5.7 5.4-5.7h.4C63.9 19.2 56.4 16 48 16c-11.2 0-21 5.7-26.7 14.4h2.1c3.3 0 8.5-.4 8.5-.4 1.7-.1 1.9 2.4.2 2.6 0 0-1.7.2-3.7.3L40 67.5l7-20.9L42 33c-1.7-.1-3.3-.3-3.3-.3-1.7-.1-1.5-2.7.2-2.6 0 0 5.3.4 8.4.4 3.3 0 8.5-.4 8.5-.4 1.7-.1 1.9 2.4.2 2.6 0 0-1.7.2-3.7.3l11.5 34.3 3.3-10.4c1.6-4.5 2.4-7.8 2.4-10.5zM16.1 48c0 12.6 7.3 23.5 18 28.7L18.8 35c-1.7 4-2.7 8.4-2.7 13zm32.5 2.8L39 78.6c2.9.8 5.9 1.3 9 1.3 3.7 0 7.3-.6 10.6-1.8-.1-.1-.2-.3-.2-.4l-9.8-26.9zM76.2 36c0 3.2-.6 6.9-2.4 11.4L64 75.6c9.5-5.5 15.9-15.8 15.9-27.6 0-5.5-1.4-10.8-3.9-15.3.1 1 .2 2.1.2 3.3z",
              fill: "none"
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime444.jsx)("p", { children: (0, import_i18n248.__)("Generating preview\u2026") })
      ] })
    );
    markup += `
		<style>
			body {
				margin: 0;
			}
			.editor-post-preview-button__interstitial-message {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				height: 100vh;
				width: 100vw;
			}
			@-webkit-keyframes paint {
				0% {
					stroke-dashoffset: 0;
				}
			}
			@-moz-keyframes paint {
				0% {
					stroke-dashoffset: 0;
				}
			}
			@-o-keyframes paint {
				0% {
					stroke-dashoffset: 0;
				}
			}
			@keyframes paint {
				0% {
					stroke-dashoffset: 0;
				}
			}
			.editor-post-preview-button__interstitial-message svg {
				width: 192px;
				height: 192px;
				stroke: #555d66;
				stroke-width: 0.75;
			}
			.editor-post-preview-button__interstitial-message svg .outer,
			.editor-post-preview-button__interstitial-message svg .inner {
				stroke-dasharray: 280;
				stroke-dashoffset: 280;
				-webkit-animation: paint 1.5s ease infinite alternate;
				-moz-animation: paint 1.5s ease infinite alternate;
				-o-animation: paint 1.5s ease infinite alternate;
				animation: paint 1.5s ease infinite alternate;
			}
			p {
				text-align: center;
				font-family: -apple-system, system-ui, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
			}
		</style>
	`;
    markup = (0, import_hooks51.applyFilters)("editor.PostPreview.interstitialMarkup", markup);
    return markup;
  }
  function writeInterstitialMessage(targetDocument, markup) {
    targetDocument.write(markup);
    targetDocument.title = (0, import_i18n248.__)("Generating preview\u2026");
    targetDocument.close();
  }
  async function getPreviewDocument(previewWindow) {
    try {
      return previewWindow.document;
    } catch {
    }
    previewWindow.location = "about:blank";
    const timeoutMs = 1e3;
    const intervalMs = 50;
    const deadline = Date.now() + timeoutMs;
    do {
      await new Promise((resolve) => setTimeout(resolve, intervalMs));
      try {
        return previewWindow.document;
      } catch {
      }
    } while (Date.now() < deadline);
    return null;
  }
  async function writeInterstitialIntoPreviewWindow(previewWindow) {
    const previewDocument = await getPreviewDocument(previewWindow);
    if (previewDocument) {
      writeInterstitialMessage(previewDocument, buildInterstitialMarkup());
    }
  }
  function usePostPreviewProps({ forceIsAutosaveable, onPreview }) {
    const { postId: postId2, currentPostLink, previewLink, isSaveable, isViewable } = (0, import_data148.useSelect)((select9) => {
      const editor = select9(store);
      const core = select9(import_core_data89.store);
      const postType2 = core.getPostType(
        editor.getCurrentPostType("type")
      );
      const canView = postType2?.viewable ?? false;
      if (!canView) {
        return { isViewable: canView };
      }
      return {
        postId: editor.getCurrentPostId(),
        currentPostLink: editor.getCurrentPostAttribute("link"),
        previewLink: editor.getEditedPostPreviewLink(),
        isSaveable: editor.isEditedPostSaveable(),
        isViewable: canView
      };
    }, []);
    const { __unstableSaveForPreview: __unstableSaveForPreview2 } = (0, import_data148.useDispatch)(store);
    if (!isViewable) {
      return null;
    }
    const target = `wp-preview-${postId2}`;
    const handlePreviewClick = async (event) => {
      event.preventDefault();
      const previewWindow = window.open("", target);
      previewWindow.focus();
      await writeInterstitialIntoPreviewWindow(previewWindow);
      const link = await __unstableSaveForPreview2({ forceIsAutosaveable });
      previewWindow.location = link;
      onPreview?.();
    };
    const href = previewLink || currentPostLink;
    return {
      href,
      target,
      disabled: !isSaveable,
      onClick: handlePreviewClick
    };
  }
  function PostPreviewMenuItem({ forceIsAutosaveable, onPreview }) {
    const previewProps = usePostPreviewProps({
      forceIsAutosaveable,
      onPreview
    });
    if (!previewProps) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime444.jsx)(import_components205.MenuItem, { icon: external_default, ...previewProps, children: (0, import_i18n248.__)("Preview in new tab") });
  }
  function PostPreviewButton({
    className,
    textContent,
    forceIsAutosaveable,
    role,
    onPreview
  }) {
    const previewProps = usePostPreviewProps({
      forceIsAutosaveable,
      onPreview
    });
    if (!previewProps) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime444.jsx)(
      import_components205.Button,
      {
        variant: !className ? "tertiary" : void 0,
        className: className || "editor-post-preview",
        role,
        size: "compact",
        accessibleWhenDisabled: true,
        ...previewProps,
        children: textContent || /* @__PURE__ */ (0, import_jsx_runtime444.jsxs)(import_jsx_runtime444.Fragment, { children: [
          (0, import_i18n248._x)("Preview", "imperative verb"),
          /* @__PURE__ */ (0, import_jsx_runtime444.jsx)(VisuallyHidden, {
            render: /* @__PURE__ */ (0, import_jsx_runtime444.jsx)("span", {}),
            /* translators: accessibility text */
            children: (0, import_i18n248.__)("(opens in a new tab)")
          })
        ] })
      }
    );
  }

  // packages/editor/build-module/components/post-publish-button/index.mjs
  var import_components206 = __toESM(require_components(), 1);
  var import_data150 = __toESM(require_data(), 1);

  // packages/editor/build-module/components/post-publish-button/label.mjs
  var import_i18n249 = __toESM(require_i18n(), 1);
  var import_data149 = __toESM(require_data(), 1);
  var import_compose48 = __toESM(require_compose(), 1);
  function PublishButtonLabel() {
    const isSmallerThanMediumViewport = (0, import_compose48.useViewportMatch)("medium", "<");
    const {
      isPublished,
      isBeingScheduled,
      isSaving,
      isPublishing,
      hasPublishAction,
      isAutosaving,
      hasNonPostEntityChanges: hasNonPostEntityChanges2,
      postStatusHasChanged,
      postStatus,
      isPostSavingLocked: isPostSavingLocked2
    } = (0, import_data149.useSelect)((select9) => {
      const {
        isCurrentPostPublished: isCurrentPostPublished2,
        isEditedPostBeingScheduled: isEditedPostBeingScheduled2,
        isSavingPost: isSavingPost2,
        isPublishingPost: isPublishingPost2,
        getCurrentPost: getCurrentPost2,
        isAutosavingPost: isAutosavingPost2,
        getPostEdits: getPostEdits2,
        getEditedPostAttribute: getEditedPostAttribute2
      } = select9(store);
      return {
        isPublished: isCurrentPostPublished2(),
        isBeingScheduled: isEditedPostBeingScheduled2(),
        isSaving: isSavingPost2(),
        isPublishing: isPublishingPost2(),
        hasPublishAction: getCurrentPost2()._links?.["wp:action-publish"] ?? false,
        isAutosaving: isAutosavingPost2(),
        hasNonPostEntityChanges: select9(store).hasNonPostEntityChanges(),
        isPostSavingLocked: select9(store).isPostSavingLocked(),
        postStatusHasChanged: !!getPostEdits2()?.status,
        postStatus: getEditedPostAttribute2("status")
      };
    }, []);
    if (isPublishing) {
      return (0, import_i18n249.__)("Publishing\u2026");
    } else if ((isPublished || isBeingScheduled) && isSaving && !isAutosaving) {
      return (0, import_i18n249.__)("Saving\u2026");
    }
    if (!hasPublishAction) {
      return isSmallerThanMediumViewport ? (0, import_i18n249.__)("Publish") : (0, import_i18n249.__)("Submit for Review");
    }
    if (hasNonPostEntityChanges2 && !isPostSavingLocked2 || isPublished || postStatusHasChanged && !["future", "publish"].includes(postStatus) || !postStatusHasChanged && postStatus === "future") {
      return (0, import_i18n249.__)("Save");
    }
    if (isBeingScheduled) {
      return (0, import_i18n249.__)("Schedule");
    }
    return (0, import_i18n249.__)("Publish");
  }

  // packages/editor/build-module/components/post-publish-button/index.mjs
  var import_jsx_runtime445 = __toESM(require_jsx_runtime(), 1);
  var noop11 = () => {
  };
  function PostPublishButton({
    forceIsDirty,
    isOpen: isOpen2,
    isToggle,
    onSubmit = noop11,
    onToggle,
    setEntitiesSavedStatesCallback
  }) {
    const {
      hasPublishAction,
      isBeingScheduled,
      isPostSavingLocked: isPostSavingLocked2,
      isPublishable,
      isPublished,
      isSaveable,
      isSaving,
      isAutoSaving,
      visibility,
      hasNonPostEntityChanges: hasNonPostEntityChanges2,
      isSavingNonPostEntityChanges: isSavingNonPostEntityChanges2,
      postStatus,
      postStatusHasChanged,
      postType: postType2,
      postId: postId2
    } = (0, import_data150.useSelect)((select9) => {
      const store4 = select9(store);
      return {
        isSaving: store4.isSavingPost(),
        isAutoSaving: store4.isAutosavingPost(),
        isBeingScheduled: store4.isEditedPostBeingScheduled(),
        visibility: store4.getEditedPostVisibility(),
        isSaveable: store4.isEditedPostSaveable(),
        isPostSavingLocked: store4.isPostSavingLocked(),
        isPublishable: store4.isEditedPostPublishable(),
        isPublished: store4.isCurrentPostPublished(),
        hasPublishAction: !!store4.getCurrentPost()?._links?.["wp:action-publish"],
        postType: store4.getCurrentPostType(),
        postId: store4.getCurrentPostId(),
        postStatus: store4.getEditedPostAttribute("status"),
        postStatusHasChanged: store4.getPostEdits()?.status,
        hasNonPostEntityChanges: store4.hasNonPostEntityChanges(),
        isSavingNonPostEntityChanges: store4.isSavingNonPostEntityChanges()
      };
    }, []);
    const { editPost: editPost2, savePost: savePost2 } = (0, import_data150.useDispatch)(store);
    const savePostStatus = (status) => {
      editPost2({ status }, { undoIgnore: true });
      savePost2();
    };
    const createOnClick = (callback) => (...args) => {
      if (hasNonPostEntityChanges2 && setEntitiesSavedStatesCallback) {
        const onClose = (savedEntities) => {
          if (savedEntities && savedEntities.some(
            (elt) => elt.kind === "postType" && elt.name === postType2 && elt.key === postId2
          )) {
            callback(...args);
          }
        };
        setEntitiesSavedStatesCallback(() => onClose);
        return noop11;
      }
      return callback(...args);
    };
    const isButtonDisabled = isPostSavingLocked2 || // Disable while a non-post entity (e.g. a newly created term) is mid-save.
    isSavingNonPostEntityChanges2 || (isSaving || !isSaveable || !isPublishable && !forceIsDirty) && !hasNonPostEntityChanges2;
    const isToggleDisabled = isPostSavingLocked2 || isSavingNonPostEntityChanges2 || (isPublished || isSaving || !isSaveable || !isPublishable && !forceIsDirty) && !hasNonPostEntityChanges2;
    let publishStatus = "publish";
    if (postStatusHasChanged) {
      publishStatus = postStatus;
    } else if (!hasPublishAction) {
      publishStatus = "pending";
    } else if (visibility === "private") {
      publishStatus = "private";
    } else if (isBeingScheduled) {
      publishStatus = "future";
    }
    const onClickButton = () => {
      if (isButtonDisabled) {
        return;
      }
      onSubmit();
      savePostStatus(publishStatus);
    };
    const onClickToggle = () => {
      if (isToggleDisabled) {
        return;
      }
      onToggle();
    };
    const buttonProps = {
      "aria-disabled": isButtonDisabled,
      className: "editor-post-publish-button",
      isBusy: !isAutoSaving && isSaving,
      variant: "primary",
      onClick: createOnClick(onClickButton),
      "aria-haspopup": hasNonPostEntityChanges2 ? "dialog" : void 0
    };
    const toggleProps = {
      "aria-disabled": isToggleDisabled,
      "aria-expanded": isOpen2,
      className: "editor-post-publish-panel__toggle",
      isBusy: isSaving && isPublished,
      variant: "primary",
      size: "compact",
      onClick: createOnClick(onClickToggle),
      "aria-haspopup": hasNonPostEntityChanges2 ? "dialog" : void 0
    };
    const componentProps = isToggle ? toggleProps : buttonProps;
    return /* @__PURE__ */ (0, import_jsx_runtime445.jsx)(
      import_components206.Button,
      {
        ...componentProps,
        className: `${componentProps.className} editor-post-publish-button__button`,
        size: "compact",
        children: /* @__PURE__ */ (0, import_jsx_runtime445.jsx)(PublishButtonLabel, {})
      }
    );
  }
  var post_publish_button_default = PostPublishButton;

  // packages/editor/build-module/components/post-publish-panel/index.mjs
  var import_i18n262 = __toESM(require_i18n(), 1);
  var import_element263 = __toESM(require_element(), 1);
  var import_components217 = __toESM(require_components(), 1);
  var import_data164 = __toESM(require_data(), 1);
  var import_compose53 = __toESM(require_compose(), 1);
  var import_core_data99 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/post-publish-panel/prepublish.mjs
  var import_i18n260 = __toESM(require_i18n(), 1);
  var import_components215 = __toESM(require_components(), 1);
  var import_data162 = __toESM(require_data(), 1);
  var import_url19 = __toESM(require_url(), 1);
  var import_core_data97 = __toESM(require_core_data(), 1);
  var import_html_entities27 = __toESM(require_html_entities(), 1);

  // packages/editor/build-module/components/post-visibility/index.mjs
  var import_i18n251 = __toESM(require_i18n(), 1);
  var import_element255 = __toESM(require_element(), 1);
  var import_components207 = __toESM(require_components(), 1);
  var import_compose49 = __toESM(require_compose(), 1);
  var import_data151 = __toESM(require_data(), 1);
  var import_block_editor55 = __toESM(require_block_editor(), 1);

  // packages/editor/build-module/components/post-visibility/utils.mjs
  var import_i18n250 = __toESM(require_i18n(), 1);
  var VISIBILITY_OPTIONS = [
    {
      label: (0, import_i18n250.__)("Public"),
      value: "public",
      description: (0, import_i18n250.__)("Visible to everyone.")
    },
    {
      label: (0, import_i18n250.__)("Private"),
      value: "private",
      description: (0, import_i18n250.__)("Only visible to site admins and editors.")
    },
    {
      label: (0, import_i18n250.__)("Password protected"),
      value: "password",
      description: (0, import_i18n250.__)("Only visible to those who know the password.")
    }
  ];

  // packages/editor/build-module/components/post-visibility/index.mjs
  var import_jsx_runtime446 = __toESM(require_jsx_runtime(), 1);
  function PostVisibility({ onClose }) {
    const instanceId = (0, import_compose49.useInstanceId)(PostVisibility);
    const { status, visibility, password } = (0, import_data151.useSelect)((select9) => ({
      status: select9(store).getEditedPostAttribute("status"),
      visibility: select9(store).getEditedPostVisibility(),
      password: select9(store).getEditedPostAttribute("password")
    }));
    const { editPost: editPost2 } = (0, import_data151.useDispatch)(store);
    const [hasPassword, setHasPassword] = (0, import_element255.useState)(!!password);
    function updateVisibility(value) {
      const nextValues = {
        public: {
          status: visibility === "private" ? "draft" : status,
          password: ""
        },
        private: { status: "private", password: "" },
        password: {
          status: visibility === "private" ? "draft" : status,
          password: password || ""
        }
      };
      editPost2(nextValues[value]);
      setHasPassword(value === "password");
    }
    const updatePassword = (value) => {
      editPost2({ password: value });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime446.jsxs)("div", { className: "editor-post-visibility", children: [
      /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(
        import_block_editor55.__experimentalInspectorPopoverHeader,
        {
          title: (0, import_i18n251.__)("Visibility"),
          help: (0, import_i18n251.__)("Control how this post is viewed."),
          onClose
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime446.jsxs)(import_components207.__experimentalVStack, { spacing: 4, children: [
        /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(
          import_components207.RadioControl,
          {
            label: (0, import_i18n251.__)("Visibility"),
            hideLabelFromVision: true,
            options: VISIBILITY_OPTIONS,
            selected: hasPassword ? "password" : visibility,
            onChange: updateVisibility
          }
        ),
        hasPassword && /* @__PURE__ */ (0, import_jsx_runtime446.jsx)(
          import_components207.TextControl,
          {
            label: (0, import_i18n251.__)("Password"),
            onChange: updatePassword,
            value: password,
            placeholder: (0, import_i18n251.__)("Use a secure password"),
            type: "text",
            id: `editor-post-visibility__password-input-${instanceId}`,
            maxLength: 255
          }
        )
      ] })
    ] });
  }

  // packages/editor/build-module/components/post-visibility/label.mjs
  var import_data152 = __toESM(require_data(), 1);
  function PostVisibilityLabel() {
    return usePostVisibilityLabel();
  }
  function usePostVisibilityLabel() {
    const visibility = (0, import_data152.useSelect)(
      (select9) => select9(store).getEditedPostVisibility(),
      []
    );
    return VISIBILITY_OPTIONS.find((option) => option.value === visibility)?.label;
  }

  // packages/editor/build-module/components/post-schedule/index.mjs
  var import_date17 = __toESM(require_date(), 1);
  var import_i18n252 = __toESM(require_i18n(), 1);
  var import_data153 = __toESM(require_data(), 1);
  var import_block_editor56 = __toESM(require_block_editor(), 1);
  var import_element256 = __toESM(require_element(), 1);
  var import_core_data90 = __toESM(require_core_data(), 1);
  var import_jsx_runtime447 = __toESM(require_jsx_runtime(), 1);
  var { PrivatePublishDateTimePicker } = unlock(import_block_editor56.privateApis);
  function PostSchedule(props) {
    return /* @__PURE__ */ (0, import_jsx_runtime447.jsx)(
      PrivatePostSchedule,
      {
        ...props,
        showPopoverHeaderActions: true,
        isCompact: false
      }
    );
  }
  function PrivatePostSchedule({
    onClose,
    showPopoverHeaderActions,
    isCompact
  }) {
    const { postDate, postType: postType2 } = (0, import_data153.useSelect)(
      (select9) => ({
        postDate: select9(store).getEditedPostAttribute("date"),
        postType: select9(store).getCurrentPostType()
      }),
      []
    );
    const { editPost: editPost2 } = (0, import_data153.useDispatch)(store);
    const onUpdateDate = (date) => editPost2({ date });
    const [previewedMonth, setPreviewedMonth] = (0, import_element256.useState)(
      startOfMonth(new Date(postDate))
    );
    const eventsByPostType = (0, import_data153.useSelect)(
      (select9) => select9(import_core_data90.store).getEntityRecords("postType", postType2, {
        status: "publish,future",
        after: startOfMonth(previewedMonth).toISOString(),
        before: endOfMonth(previewedMonth).toISOString(),
        exclude: [select9(store).getCurrentPostId()],
        per_page: 100,
        _fields: "id,date"
      }),
      [previewedMonth, postType2]
    );
    const events = (0, import_element256.useMemo)(
      () => (eventsByPostType || []).map(({ date: eventDate }) => ({
        date: new Date(eventDate)
      })),
      [eventsByPostType]
    );
    const settings = (0, import_date17.getSettings)();
    const is12HourTime = /a(?!\\)/i.test(
      settings.formats.time.toLowerCase().replace(/\\\\/g, "").split("").reverse().join("")
      // Reverse the string and test for "a" not followed by a slash.
    );
    return /* @__PURE__ */ (0, import_jsx_runtime447.jsx)(
      PrivatePublishDateTimePicker,
      {
        currentDate: postDate,
        onChange: onUpdateDate,
        is12Hour: is12HourTime,
        dateOrder: (
          /* translators: Order of day, month, and year. Available formats are 'dmy', 'mdy', and 'ymd'. */
          (0, import_i18n252._x)("dmy", "date order")
        ),
        events,
        onMonthPreviewed: (date) => setPreviewedMonth(parseISO(date)),
        onClose,
        isCompact,
        showPopoverHeaderActions
      }
    );
  }

  // packages/editor/build-module/components/post-schedule/label.mjs
  var import_i18n253 = __toESM(require_i18n(), 1);
  var import_date18 = __toESM(require_date(), 1);
  var import_data154 = __toESM(require_data(), 1);
  function PostScheduleLabel(props) {
    return usePostScheduleLabel(props);
  }
  function usePostScheduleLabel({ full = false } = {}) {
    const { date, isFloating } = (0, import_data154.useSelect)(
      (select9) => ({
        date: select9(store).getEditedPostAttribute("date"),
        isFloating: select9(store).isEditedPostDateFloating()
      }),
      []
    );
    return full ? getFullPostScheduleLabel(date) : getPostScheduleLabel(date, { isFloating });
  }
  function getFullPostScheduleLabel(dateAttribute) {
    const date = (0, import_date18.getDate)(dateAttribute);
    const timezoneAbbreviation = getTimezoneAbbreviation();
    const formattedDate = (0, import_date18.dateI18n)(
      // translators: Use a non-breaking space between 'g:i' and 'a' if appropriate.
      (0, import_i18n253._x)("F j, Y g:i\xA0a", "post schedule full date format"),
      date
    );
    return (0, import_i18n253.isRTL)() ? `${timezoneAbbreviation} ${formattedDate}` : `${formattedDate} ${timezoneAbbreviation}`;
  }
  function getPostScheduleLabel(dateAttribute, { isFloating = false, now = /* @__PURE__ */ new Date() } = {}) {
    if (!dateAttribute || isFloating) {
      return (0, import_i18n253.__)("Immediately");
    }
    if (!isTimezoneSameAsSiteTimezone(now)) {
      return getFullPostScheduleLabel(dateAttribute);
    }
    const date = (0, import_date18.getDate)(dateAttribute);
    if (isSameDay(date, now)) {
      return (0, import_i18n253.sprintf)(
        // translators: %s: Time of day the post is scheduled for.
        (0, import_i18n253.__)("Today at %s"),
        // translators: If using a space between 'g:i' and 'a', use a non-breaking space.
        (0, import_date18.dateI18n)((0, import_i18n253._x)("g:i\xA0a", "post schedule time format"), date)
      );
    }
    const tomorrow = new Date(now);
    tomorrow.setDate(tomorrow.getDate() + 1);
    if (isSameDay(date, tomorrow)) {
      return (0, import_i18n253.sprintf)(
        // translators: %s: Time of day the post is scheduled for.
        (0, import_i18n253.__)("Tomorrow at %s"),
        // translators: If using a space between 'g:i' and 'a', use a non-breaking space.
        (0, import_date18.dateI18n)((0, import_i18n253._x)("g:i\xA0a", "post schedule time format"), date)
      );
    }
    if (date.getFullYear() === now.getFullYear()) {
      return (0, import_date18.dateI18n)(
        // translators: If using a space between 'g:i' and 'a', use a non-breaking space.
        (0, import_i18n253._x)("F j g:i\xA0a", "post schedule date format without year"),
        date
      );
    }
    return (0, import_date18.dateI18n)(
      // translators: Use a non-breaking space between 'g:i' and 'a' if appropriate.
      (0, import_i18n253._x)("F j, Y g:i\xA0a", "post schedule full date format"),
      date
    );
  }
  function getTimezoneAbbreviation() {
    const { timezone } = (0, import_date18.getSettings)();
    if (timezone.abbr && isNaN(Number(timezone.abbr))) {
      return timezone.abbr;
    }
    const symbol3 = timezone.offset < 0 ? "" : "+";
    return `UTC${symbol3}${timezone.offsetFormatted}`;
  }
  function isTimezoneSameAsSiteTimezone(date) {
    const { timezone } = (0, import_date18.getSettings)();
    const siteOffset = Number(timezone.offset);
    const dateOffset = -1 * (date.getTimezoneOffset() / 60);
    return siteOffset === dateOffset;
  }
  function isSameDay(left, right) {
    return left.getDate() === right.getDate() && left.getMonth() === right.getMonth() && left.getFullYear() === right.getFullYear();
  }

  // packages/editor/build-module/components/post-publish-panel/maybe-tags-panel.mjs
  var import_i18n255 = __toESM(require_i18n(), 1);
  var import_element258 = __toESM(require_element(), 1);
  var import_data157 = __toESM(require_data(), 1);
  var import_components210 = __toESM(require_components(), 1);
  var import_core_data93 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/post-taxonomies/flat-term-selector.mjs
  var import_i18n254 = __toESM(require_i18n(), 1);
  var import_element257 = __toESM(require_element(), 1);
  var import_components209 = __toESM(require_components(), 1);
  var import_data156 = __toESM(require_data(), 1);
  var import_core_data92 = __toESM(require_core_data(), 1);
  var import_compose50 = __toESM(require_compose(), 1);
  var import_a11y8 = __toESM(require_a11y(), 1);
  var import_notices26 = __toESM(require_notices(), 1);

  // packages/editor/build-module/components/post-taxonomies/most-used-terms.mjs
  var import_components208 = __toESM(require_components(), 1);
  var import_data155 = __toESM(require_data(), 1);
  var import_core_data91 = __toESM(require_core_data(), 1);
  var import_jsx_runtime448 = __toESM(require_jsx_runtime(), 1);
  var MIN_MOST_USED_TERMS = 3;
  var DEFAULT_QUERY2 = {
    per_page: 10,
    orderby: "count",
    order: "desc",
    hide_empty: true,
    _fields: "id,name,count",
    context: "view"
  };
  function MostUsedTerms({ onSelect, taxonomy }) {
    const { _terms, showTerms } = (0, import_data155.useSelect)(
      (select9) => {
        const mostUsedTerms = select9(import_core_data91.store).getEntityRecords(
          "taxonomy",
          taxonomy.slug,
          DEFAULT_QUERY2
        );
        return {
          _terms: mostUsedTerms,
          showTerms: mostUsedTerms?.length >= MIN_MOST_USED_TERMS
        };
      },
      [taxonomy.slug]
    );
    if (!showTerms) {
      return null;
    }
    const terms = unescapeTerms(_terms);
    return /* @__PURE__ */ (0, import_jsx_runtime448.jsxs)("div", { className: "editor-post-taxonomies__flat-term-most-used", children: [
      /* @__PURE__ */ (0, import_jsx_runtime448.jsx)(
        import_components208.BaseControl.VisualLabel,
        {
          as: "h3",
          className: "editor-post-taxonomies__flat-term-most-used-label",
          children: taxonomy.labels.most_used
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime448.jsx)(
        "ul",
        {
          role: "list",
          className: "editor-post-taxonomies__flat-term-most-used-list",
          children: terms.map((term) => /* @__PURE__ */ (0, import_jsx_runtime448.jsx)("li", { children: /* @__PURE__ */ (0, import_jsx_runtime448.jsx)(
            import_components208.Button,
            {
              __next40pxDefaultSize: true,
              variant: "link",
              onClick: () => onSelect(term),
              children: term.name
            }
          ) }, term.id))
        }
      )
    ] });
  }

  // packages/editor/build-module/components/post-taxonomies/flat-term-selector.mjs
  var import_jsx_runtime449 = __toESM(require_jsx_runtime(), 1);
  var EMPTY_ARRAY14 = [];
  var MAX_TERMS_SUGGESTIONS = 100;
  var DEFAULT_QUERY3 = {
    per_page: MAX_TERMS_SUGGESTIONS,
    _fields: "id,name",
    context: "view"
  };
  var isSameTermName = (termA, termB) => unescapeString(termA).toLowerCase() === unescapeString(termB).toLowerCase();
  var termNamesToIds = (names, terms) => {
    return names.map(
      (termName) => terms.find((term) => isSameTermName(term.name, termName))?.id
    ).filter((id) => id !== void 0);
  };
  function FlatTermSelector({ slug }) {
    const [values, setValues] = (0, import_element257.useState)([]);
    const [search, setSearch] = (0, import_element257.useState)("");
    const debouncedSearch = (0, import_compose50.useDebounce)(setSearch, 500);
    const {
      terms,
      termIds,
      taxonomy,
      hasAssignAction,
      hasCreateAction,
      hasResolvedTerms
    } = (0, import_data156.useSelect)(
      (select9) => {
        const { getCurrentPost: getCurrentPost2, getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
        const { getEntityRecords, getEntityRecord, hasFinishedResolution } = select9(import_core_data92.store);
        const post2 = getCurrentPost2();
        const _taxonomy = getEntityRecord("root", "taxonomy", slug);
        const _termIds = _taxonomy ? getEditedPostAttribute2(_taxonomy.rest_base) : EMPTY_ARRAY14;
        const query = {
          ...DEFAULT_QUERY3,
          include: _termIds?.join(","),
          per_page: -1
        };
        return {
          hasCreateAction: _taxonomy ? post2._links?.["wp:action-create-" + _taxonomy.rest_base] ?? false : false,
          hasAssignAction: _taxonomy ? post2._links?.["wp:action-assign-" + _taxonomy.rest_base] ?? false : false,
          taxonomy: _taxonomy,
          termIds: _termIds,
          terms: _termIds?.length ? getEntityRecords("taxonomy", slug, query) : EMPTY_ARRAY14,
          hasResolvedTerms: hasFinishedResolution("getEntityRecords", [
            "taxonomy",
            slug,
            query
          ])
        };
      },
      [slug]
    );
    const { searchResults } = (0, import_data156.useSelect)(
      (select9) => {
        const { getEntityRecords } = select9(import_core_data92.store);
        return {
          searchResults: !!search ? getEntityRecords("taxonomy", slug, {
            ...DEFAULT_QUERY3,
            search
          }) : EMPTY_ARRAY14
        };
      },
      [search, slug]
    );
    (0, import_element257.useEffect)(() => {
      if (hasResolvedTerms) {
        const newValues = (terms ?? []).map(
          (term) => unescapeString(term.name)
        );
        setValues(newValues);
      }
    }, [terms, hasResolvedTerms]);
    const suggestions = (0, import_element257.useMemo)(() => {
      return (searchResults ?? []).map(
        (term) => unescapeString(term.name)
      );
    }, [searchResults]);
    const { editPost: editPost2 } = (0, import_data156.useDispatch)(store);
    const { saveEntityRecord } = (0, import_data156.useDispatch)(import_core_data92.store);
    const { createErrorNotice } = (0, import_data156.useDispatch)(import_notices26.store);
    if (!hasAssignAction) {
      return null;
    }
    async function findOrCreateTerm(term) {
      try {
        const newTerm = await saveEntityRecord("taxonomy", slug, term, {
          throwOnError: true
        });
        return unescapeTerm(newTerm);
      } catch (error2) {
        if (error2.code !== "term_exists") {
          throw error2;
        }
        return {
          id: error2.data.term_id,
          name: term.name
        };
      }
    }
    function onUpdateTerms(newTermIds) {
      editPost2({ [taxonomy.rest_base]: newTermIds });
    }
    function onChange(termNames) {
      const availableTerms = [
        ...terms ?? [],
        ...searchResults ?? []
      ];
      const uniqueTerms = termNames.reduce((acc, name2) => {
        if (!acc.some((n3) => n3.toLowerCase() === name2.toLowerCase())) {
          acc.push(name2);
        }
        return acc;
      }, []);
      const newTermNames = uniqueTerms.filter(
        (termName) => !availableTerms.find(
          (term) => isSameTermName(term.name, termName)
        )
      );
      setValues(uniqueTerms);
      if (newTermNames.length === 0) {
        onUpdateTerms(termNamesToIds(uniqueTerms, availableTerms));
        return;
      }
      if (!hasCreateAction) {
        return;
      }
      Promise.all(
        newTermNames.map(
          (termName) => findOrCreateTerm({ name: termName })
        )
      ).then((newTerms) => {
        const newAvailableTerms = availableTerms.concat(newTerms);
        onUpdateTerms(
          termNamesToIds(uniqueTerms, newAvailableTerms)
        );
      }).catch((error2) => {
        createErrorNotice(error2.message, {
          type: "snackbar"
        });
        onUpdateTerms(termNamesToIds(uniqueTerms, availableTerms));
      });
    }
    function appendTerm(newTerm) {
      if (termIds.includes(newTerm.id)) {
        return;
      }
      const newTermIds = [...termIds, newTerm.id];
      const defaultName = slug === "post_tag" ? (0, import_i18n254.__)("Tag") : (0, import_i18n254.__)("Term");
      const termAddedMessage = (0, import_i18n254.sprintf)(
        /* translators: %s: term name. */
        (0, import_i18n254._x)("%s added", "term"),
        taxonomy?.labels?.singular_name ?? defaultName
      );
      (0, import_a11y8.speak)(termAddedMessage, "assertive");
      onUpdateTerms(newTermIds);
    }
    const newTermLabel = taxonomy?.labels?.add_new_item ?? (slug === "post_tag" ? (0, import_i18n254.__)("Add Tag") : (0, import_i18n254.__)("Add Term"));
    const singularName = taxonomy?.labels?.singular_name ?? (slug === "post_tag" ? (0, import_i18n254.__)("Tag") : (0, import_i18n254.__)("Term"));
    const termAddedLabel = (0, import_i18n254.sprintf)(
      /* translators: %s: term name. */
      (0, import_i18n254._x)("%s added", "term"),
      singularName
    );
    const termRemovedLabel = (0, import_i18n254.sprintf)(
      /* translators: %s: term name. */
      (0, import_i18n254._x)("%s removed", "term"),
      singularName
    );
    const removeTermLabel = (0, import_i18n254.sprintf)(
      /* translators: %s: term name. */
      (0, import_i18n254._x)("Remove %s", "term"),
      singularName
    );
    return /* @__PURE__ */ (0, import_jsx_runtime449.jsxs)(Stack, { direction: "column", gap: "lg", children: [
      /* @__PURE__ */ (0, import_jsx_runtime449.jsx)(
        import_components209.FormTokenField,
        {
          value: values,
          suggestions,
          onChange,
          onInputChange: debouncedSearch,
          maxSuggestions: MAX_TERMS_SUGGESTIONS,
          label: newTermLabel,
          messages: {
            added: termAddedLabel,
            removed: termRemovedLabel,
            remove: removeTermLabel
          }
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime449.jsx)(MostUsedTerms, { taxonomy, onSelect: appendTerm })
    ] });
  }
  var flat_term_selector_default = (0, import_components209.withFilters)("editor.PostTaxonomyType")(FlatTermSelector);

  // packages/editor/build-module/components/post-publish-panel/maybe-tags-panel.mjs
  var import_jsx_runtime450 = __toESM(require_jsx_runtime(), 1);
  var TagsPanel = () => {
    const tagLabels = (0, import_data157.useSelect)((select9) => {
      const taxonomy = select9(import_core_data93.store).getTaxonomy("post_tag");
      return taxonomy?.labels;
    }, []);
    const addNewItem = tagLabels?.add_new_item ?? (0, import_i18n255.__)("Add tag");
    const tagLabel = tagLabels?.name ?? (0, import_i18n255.__)("Tags");
    const panelBodyTitle = [
      (0, import_i18n255.__)("Suggestion:"),
      /* @__PURE__ */ (0, import_jsx_runtime450.jsx)("span", { className: "editor-post-publish-panel__link", children: addNewItem }, "label")
    ];
    return /* @__PURE__ */ (0, import_jsx_runtime450.jsxs)(import_components210.PanelBody, { initialOpen: false, title: panelBodyTitle, children: [
      /* @__PURE__ */ (0, import_jsx_runtime450.jsx)("p", { children: (0, import_i18n255.sprintf)(
        // translators: %s is the taxonomy name (e.g., "Tags").
        (0, import_i18n255.__)(
          "%s help users and search engines navigate your site and find your content. Add a few keywords to describe your post."
        ),
        tagLabel
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime450.jsx)(flat_term_selector_default, { slug: "post_tag" })
    ] });
  };
  var MaybeTagsPanel = () => {
    const { postHasTags, siteHasTags, isPostTypeSupported } = (0, import_data157.useSelect)(
      (select9) => {
        const postType2 = select9(store).getCurrentPostType();
        const tagsTaxonomy = select9(import_core_data93.store).getEntityRecord(
          "root",
          "taxonomy",
          "post_tag"
        );
        const _isPostTypeSupported = tagsTaxonomy?.types?.includes(postType2);
        const areTagsFetched = tagsTaxonomy !== void 0;
        const tags = tagsTaxonomy && select9(store).getEditedPostAttribute(
          tagsTaxonomy.rest_base
        );
        const siteTags = _isPostTypeSupported ? !!select9(import_core_data93.store).getEntityRecords(
          "taxonomy",
          "post_tag",
          { per_page: 1 }
        )?.length : false;
        return {
          postHasTags: !!tags?.length,
          siteHasTags: siteTags,
          isPostTypeSupported: areTagsFetched && _isPostTypeSupported
        };
      },
      []
    );
    const [hadTagsWhenOpeningThePanel] = (0, import_element258.useState)(postHasTags);
    if (!isPostTypeSupported || !siteHasTags) {
      return null;
    }
    if (!hadTagsWhenOpeningThePanel) {
      return /* @__PURE__ */ (0, import_jsx_runtime450.jsx)(TagsPanel, {});
    }
    return null;
  };
  var maybe_tags_panel_default = MaybeTagsPanel;

  // packages/editor/build-module/components/post-publish-panel/maybe-post-format-panel.mjs
  var import_components211 = __toESM(require_components(), 1);
  var import_data158 = __toESM(require_data(), 1);
  var import_i18n256 = __toESM(require_i18n(), 1);
  var import_core_data94 = __toESM(require_core_data(), 1);
  var import_jsx_runtime451 = __toESM(require_jsx_runtime(), 1);
  var getSuggestion = (supportedFormats, suggestedPostFormat) => {
    const formats = POST_FORMATS2.filter(
      (format6) => supportedFormats?.includes(format6.id)
    );
    return formats.find((format6) => format6.id === suggestedPostFormat);
  };
  var PostFormatSuggestion = ({
    suggestedPostFormat,
    suggestionText,
    onUpdatePostFormat
  }) => /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
    import_components211.Button,
    {
      __next40pxDefaultSize: true,
      variant: "link",
      onClick: () => onUpdatePostFormat(suggestedPostFormat),
      children: suggestionText
    }
  );
  function PostFormatPanel() {
    const { currentPostFormat, suggestion } = (0, import_data158.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2, getSuggestedPostFormat: getSuggestedPostFormat2 } = select9(store);
      const supportedFormats = select9(import_core_data94.store).getThemeSupports().formats ?? [];
      return {
        currentPostFormat: getEditedPostAttribute2("format"),
        suggestion: getSuggestion(
          supportedFormats,
          getSuggestedPostFormat2()
        )
      };
    }, []);
    const { editPost: editPost2 } = (0, import_data158.useDispatch)(store);
    const onUpdatePostFormat = (format6) => editPost2({ format: format6 });
    const panelBodyTitle = [
      (0, import_i18n256.__)("Suggestion:"),
      /* @__PURE__ */ (0, import_jsx_runtime451.jsx)("span", { className: "editor-post-publish-panel__link", children: (0, import_i18n256.__)("Use a post format") }, "label")
    ];
    if (!suggestion || suggestion.id === currentPostFormat) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime451.jsxs)(import_components211.PanelBody, { initialOpen: false, title: panelBodyTitle, children: [
      /* @__PURE__ */ (0, import_jsx_runtime451.jsx)("p", { children: (0, import_i18n256.__)(
        "Your theme uses post formats to highlight different kinds of content, like images or videos. Apply a post format to see this special styling."
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime451.jsx)("p", { children: /* @__PURE__ */ (0, import_jsx_runtime451.jsx)(
        PostFormatSuggestion,
        {
          onUpdatePostFormat,
          suggestedPostFormat: suggestion.id,
          suggestionText: (0, import_i18n256.sprintf)(
            /* translators: %1s: post format */
            (0, import_i18n256.__)('Apply the "%1$s" format.'),
            suggestion.caption
          )
        }
      ) })
    ] });
  }

  // packages/editor/build-module/components/post-publish-panel/maybe-category-panel.mjs
  var import_i18n258 = __toESM(require_i18n(), 1);
  var import_data160 = __toESM(require_data(), 1);
  var import_components213 = __toESM(require_components(), 1);
  var import_core_data96 = __toESM(require_core_data(), 1);
  var import_element260 = __toESM(require_element(), 1);

  // packages/editor/build-module/components/post-taxonomies/hierarchical-term-selector.mjs
  var import_i18n257 = __toESM(require_i18n(), 1);
  var import_element259 = __toESM(require_element(), 1);
  var import_notices27 = __toESM(require_notices(), 1);
  var import_components212 = __toESM(require_components(), 1);
  var import_data159 = __toESM(require_data(), 1);
  var import_compose51 = __toESM(require_compose(), 1);
  var import_core_data95 = __toESM(require_core_data(), 1);
  var import_a11y9 = __toESM(require_a11y(), 1);
  var import_html_entities26 = __toESM(require_html_entities(), 1);
  var import_jsx_runtime452 = __toESM(require_jsx_runtime(), 1);
  var { normalizeTextString } = unlock(import_components212.privateApis);
  var { RECEIVE_INTERMEDIATE_RESULTS } = unlock(import_core_data95.privateApis);
  var DEFAULT_QUERY4 = {
    per_page: -1,
    orderby: "name",
    order: "asc",
    _fields: "id,name,parent",
    context: "view",
    [RECEIVE_INTERMEDIATE_RESULTS]: true
  };
  var MIN_TERMS_COUNT_FOR_FILTER = 8;
  var EMPTY_ARRAY15 = [];
  function sortBySelected(termsTree, terms) {
    const treeHasSelection = (termTree) => {
      if (terms.indexOf(termTree.id) !== -1) {
        return true;
      }
      if (void 0 === termTree.children) {
        return false;
      }
      return termTree.children.map(treeHasSelection).filter((child) => child).length > 0;
    };
    const termOrChildIsSelected = (termA, termB) => {
      const termASelected = treeHasSelection(termA);
      const termBSelected = treeHasSelection(termB);
      if (termASelected === termBSelected) {
        return 0;
      }
      if (termASelected && !termBSelected) {
        return -1;
      }
      if (!termASelected && termBSelected) {
        return 1;
      }
      return 0;
    };
    const newTermTree = [...termsTree];
    newTermTree.sort(termOrChildIsSelected);
    return newTermTree;
  }
  function findTerm(terms, parent, name2) {
    return terms.find((term) => {
      return (!term.parent && !parent || parseInt(term.parent) === parseInt(parent)) && term.name.toLowerCase() === name2.toLowerCase();
    });
  }
  function getFilterMatcher(filterValue) {
    const matchTermsForFilter = (originalTerm) => {
      if ("" === filterValue) {
        return originalTerm;
      }
      const term = { ...originalTerm };
      if (term.children.length > 0) {
        term.children = term.children.map(matchTermsForFilter).filter((child) => child);
      }
      if (-1 !== normalizeTextString(term.name).indexOf(
        normalizeTextString(filterValue)
      ) || term.children.length > 0) {
        return term;
      }
      return false;
    };
    return matchTermsForFilter;
  }
  function HierarchicalTermSelector({ slug }) {
    const [adding, setAdding] = (0, import_element259.useState)(false);
    const [formName, setFormName] = (0, import_element259.useState)("");
    const [formParent, setFormParent] = (0, import_element259.useState)("");
    const [showForm, setShowForm] = (0, import_element259.useState)(false);
    const [filterValue, setFilterValue] = (0, import_element259.useState)("");
    const [filteredTermsTree, setFilteredTermsTree] = (0, import_element259.useState)([]);
    const debouncedSpeak = (0, import_compose51.useDebounce)(import_a11y9.speak, 500);
    const {
      hasCreateAction,
      hasAssignAction,
      terms,
      loading,
      availableTerms,
      taxonomy
    } = (0, import_data159.useSelect)(
      (select9) => {
        const { getCurrentPost: getCurrentPost2, getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
        const { getEntityRecord, getEntityRecords, isResolving } = select9(import_core_data95.store);
        const _taxonomy = getEntityRecord("root", "taxonomy", slug);
        const post2 = getCurrentPost2();
        return {
          hasCreateAction: _taxonomy ? !!post2._links?.["wp:action-create-" + _taxonomy.rest_base] : false,
          hasAssignAction: _taxonomy ? !!post2._links?.["wp:action-assign-" + _taxonomy.rest_base] : false,
          terms: _taxonomy ? getEditedPostAttribute2(_taxonomy.rest_base) : EMPTY_ARRAY15,
          loading: isResolving("getEntityRecords", [
            "taxonomy",
            slug,
            DEFAULT_QUERY4
          ]),
          availableTerms: getEntityRecords("taxonomy", slug, DEFAULT_QUERY4) || EMPTY_ARRAY15,
          taxonomy: _taxonomy
        };
      },
      [slug]
    );
    const { editPost: editPost2 } = (0, import_data159.useDispatch)(store);
    const { saveEntityRecord } = (0, import_data159.useDispatch)(import_core_data95.store);
    const availableTermsTree = (0, import_element259.useMemo)(
      () => sortBySelected(buildTermsTree2(availableTerms), terms),
      // Remove `terms` from the dependency list to avoid reordering every time
      // checking or unchecking a term.
      [availableTerms]
    );
    const { createErrorNotice } = (0, import_data159.useDispatch)(import_notices27.store);
    if (!hasAssignAction) {
      return null;
    }
    const addTerm = (term) => {
      return saveEntityRecord("taxonomy", slug, term, {
        throwOnError: true
      });
    };
    const onUpdateTerms = (termIds) => {
      editPost2({ [taxonomy.rest_base]: termIds });
    };
    const onChange = (termId) => {
      const hasTerm = terms.includes(termId);
      const newTerms = hasTerm ? terms.filter((id) => id !== termId) : [...terms, termId];
      onUpdateTerms(newTerms);
    };
    const onChangeFormName = (value) => {
      setFormName(value);
    };
    const onChangeFormParent = (parentId) => {
      setFormParent(parentId);
    };
    const onToggleForm = () => {
      setShowForm(!showForm);
    };
    const onAddTerm = async (event) => {
      event.preventDefault();
      if (formName === "" || adding) {
        return;
      }
      const existingTerm = findTerm(availableTerms, formParent, formName);
      if (existingTerm) {
        if (!terms.some((term) => term === existingTerm.id)) {
          onUpdateTerms([...terms, existingTerm.id]);
        }
        setFormName("");
        setFormParent("");
        return;
      }
      setAdding(true);
      let newTerm;
      try {
        newTerm = await addTerm({
          name: formName,
          parent: formParent ? formParent : void 0
        });
      } catch (error2) {
        createErrorNotice(error2.message, {
          type: "snackbar"
        });
        return;
      }
      const defaultName = slug === "category" ? (0, import_i18n257.__)("Category") : (0, import_i18n257.__)("Term");
      const termAddedMessage = (0, import_i18n257.sprintf)(
        /* translators: %s: term name. */
        (0, import_i18n257._x)("%s added", "term"),
        taxonomy?.labels?.singular_name ?? defaultName
      );
      (0, import_a11y9.speak)(termAddedMessage, "assertive");
      setAdding(false);
      setFormName("");
      setFormParent("");
      onUpdateTerms([...terms, newTerm.id]);
    };
    const setFilter = (value) => {
      const newFilteredTermsTree = availableTermsTree.map(getFilterMatcher(value)).filter((term) => term);
      const getResultCount = (termsTree) => {
        let count = 0;
        for (let i3 = 0; i3 < termsTree.length; i3++) {
          count++;
          if (void 0 !== termsTree[i3].children) {
            count += getResultCount(termsTree[i3].children);
          }
        }
        return count;
      };
      setFilterValue(value);
      setFilteredTermsTree(newFilteredTermsTree);
      const resultCount = getResultCount(newFilteredTermsTree);
      const resultsFoundMessage = (0, import_i18n257.sprintf)(
        /* translators: %d: number of results. */
        (0, import_i18n257._n)("%d result found.", "%d results found.", resultCount),
        resultCount
      );
      debouncedSpeak(resultsFoundMessage, "assertive");
    };
    const renderTerms = (renderedTerms) => {
      return renderedTerms.map((term) => {
        return /* @__PURE__ */ (0, import_jsx_runtime452.jsxs)(
          "div",
          {
            className: "editor-post-taxonomies__hierarchical-terms-choice",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
                import_components212.CheckboxControl,
                {
                  checked: terms.indexOf(term.id) !== -1,
                  onChange: () => {
                    const termId = parseInt(term.id, 10);
                    onChange(termId);
                  },
                  label: (0, import_html_entities26.decodeEntities)(term.name)
                }
              ),
              !!term.children.length && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)("div", { className: "editor-post-taxonomies__hierarchical-terms-subchoices", children: renderTerms(term.children) })
            ]
          },
          term.id
        );
      });
    };
    const labelWithFallback = (labelProperty, fallbackIsCategory, fallbackIsNotCategory) => taxonomy?.labels?.[labelProperty] ?? (slug === "category" ? fallbackIsCategory : fallbackIsNotCategory);
    const newTermButtonLabel = labelWithFallback(
      "add_new_item",
      (0, import_i18n257.__)("Add Category"),
      (0, import_i18n257.__)("Add Term")
    );
    const newTermLabel = labelWithFallback(
      "new_item_name",
      (0, import_i18n257.__)("Add Category"),
      (0, import_i18n257.__)("Add Term")
    );
    const parentSelectLabel = labelWithFallback(
      "parent_item",
      (0, import_i18n257.__)("Parent Category"),
      (0, import_i18n257.__)("Parent Term")
    );
    const noParentOption = `\u2014 ${parentSelectLabel} \u2014`;
    const newTermSubmitLabel = newTermButtonLabel;
    const filterLabel = taxonomy?.labels?.search_items ?? (0, import_i18n257.__)("Search Terms");
    const groupLabel = taxonomy?.name ?? (0, import_i18n257.__)("Terms");
    const showFilter = availableTerms.length >= MIN_TERMS_COUNT_FOR_FILTER;
    return /* @__PURE__ */ (0, import_jsx_runtime452.jsxs)(import_components212.Flex, { direction: "column", gap: "4", children: [
      showFilter && !loading && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
        import_components212.SearchControl,
        {
          label: filterLabel,
          placeholder: filterLabel,
          value: filterValue,
          onChange: setFilter
        }
      ),
      loading && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
        import_components212.Flex,
        {
          justify: "center",
          style: {
            // Match SearchControl height to prevent layout shift.
            height: "40px"
          },
          children: /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(import_components212.Spinner, {})
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
        "div",
        {
          className: "editor-post-taxonomies__hierarchical-terms-list",
          tabIndex: "0",
          role: "group",
          "aria-label": groupLabel,
          children: renderTerms(
            "" !== filterValue ? filteredTermsTree : availableTermsTree
          )
        }
      ),
      !loading && hasCreateAction && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(import_components212.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
        import_components212.Button,
        {
          __next40pxDefaultSize: true,
          onClick: onToggleForm,
          className: "editor-post-taxonomies__hierarchical-terms-add",
          "aria-expanded": showForm,
          variant: "link",
          children: newTermButtonLabel
        }
      ) }),
      showForm && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)("form", { onSubmit: onAddTerm, children: /* @__PURE__ */ (0, import_jsx_runtime452.jsxs)(import_components212.Flex, { direction: "column", gap: "4", children: [
        /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
          import_components212.TextControl,
          {
            className: "editor-post-taxonomies__hierarchical-terms-input",
            label: newTermLabel,
            value: formName,
            onChange: onChangeFormName,
            required: true
          }
        ),
        !!availableTerms.length && /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
          import_components212.TreeSelect,
          {
            label: parentSelectLabel,
            noOptionLabel: noParentOption,
            onChange: onChangeFormParent,
            selectedId: formParent,
            tree: availableTermsTree
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(import_components212.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime452.jsx)(
          import_components212.Button,
          {
            __next40pxDefaultSize: true,
            variant: "secondary",
            type: "submit",
            className: "editor-post-taxonomies__hierarchical-terms-submit",
            children: newTermSubmitLabel
          }
        ) })
      ] }) })
    ] });
  }
  var hierarchical_term_selector_default = (0, import_components212.withFilters)("editor.PostTaxonomyType")(
    HierarchicalTermSelector
  );

  // packages/editor/build-module/components/post-publish-panel/maybe-category-panel.mjs
  var import_jsx_runtime453 = __toESM(require_jsx_runtime(), 1);
  function MaybeCategoryPanel() {
    const { hasNoCategory, hasSiteCategories } = (0, import_data160.useSelect)((select9) => {
      const postType2 = select9(store).getCurrentPostType();
      const { canUser, getEntityRecord } = select9(import_core_data96.store);
      const categoriesTaxonomy = getEntityRecord(
        "root",
        "taxonomy",
        "category"
      );
      const defaultCategoryId = canUser("read", {
        kind: "root",
        name: "site"
      }) ? getEntityRecord("root", "site")?.default_category : void 0;
      const defaultCategory = defaultCategoryId ? getEntityRecord("taxonomy", "category", defaultCategoryId) : void 0;
      const postTypeSupportsCategories = categoriesTaxonomy && categoriesTaxonomy.types.some((type) => type === postType2);
      const categories = categoriesTaxonomy && select9(store).getEditedPostAttribute(
        categoriesTaxonomy.rest_base
      );
      const siteCategories = postTypeSupportsCategories ? !!select9(import_core_data96.store).getEntityRecords("taxonomy", "category", {
        exclude: [defaultCategoryId],
        per_page: 1
      })?.length : false;
      const noCategory = !!categoriesTaxonomy && !!defaultCategory && postTypeSupportsCategories && (categories?.length === 0 || categories?.length === 1 && defaultCategory?.id === categories[0]);
      return {
        hasNoCategory: noCategory,
        hasSiteCategories: siteCategories
      };
    }, []);
    const [shouldShowPanel, setShouldShowPanel] = (0, import_element260.useState)(false);
    (0, import_element260.useEffect)(() => {
      if (hasNoCategory) {
        setShouldShowPanel(true);
      }
    }, [hasNoCategory]);
    if (!shouldShowPanel || !hasSiteCategories) {
      return null;
    }
    const panelBodyTitle = [
      (0, import_i18n258.__)("Suggestion:"),
      /* @__PURE__ */ (0, import_jsx_runtime453.jsx)("span", { className: "editor-post-publish-panel__link", children: (0, import_i18n258.__)("Assign a category") }, "label")
    ];
    return /* @__PURE__ */ (0, import_jsx_runtime453.jsxs)(import_components213.PanelBody, { initialOpen: false, title: panelBodyTitle, children: [
      /* @__PURE__ */ (0, import_jsx_runtime453.jsx)("p", { children: (0, import_i18n258.__)(
        "Categories provide a helpful way to group related posts together and to quickly tell readers what a post is about."
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime453.jsx)(hierarchical_term_selector_default, { slug: "category" })
    ] });
  }
  var maybe_category_panel_default = MaybeCategoryPanel;

  // packages/editor/build-module/components/post-publish-panel/maybe-upload-media.mjs
  var import_components214 = __toESM(require_components(), 1);
  var import_data161 = __toESM(require_data(), 1);
  var import_i18n259 = __toESM(require_i18n(), 1);
  var import_block_editor57 = __toESM(require_block_editor(), 1);
  var import_element261 = __toESM(require_element(), 1);
  var import_jsx_runtime454 = __toESM(require_jsx_runtime(), 1);
  var { mediaSideloadFromUrlKey: mediaSideloadFromUrlKey2 } = unlock(import_block_editor57.privateApis);
  function flattenBlocks(blocks) {
    const result = [];
    blocks.forEach((block) => {
      result.push(block);
      result.push(...flattenBlocks(block.innerBlocks));
    });
    return result;
  }
  function hasExternalMedia(block) {
    if (block.name === "core/image" || block.name === "core/cover") {
      return block.attributes.url && !block.attributes.id;
    }
    if (block.name === "core/media-text") {
      return block.attributes.mediaUrl && !block.attributes.mediaId;
    }
    return void 0;
  }
  function getMediaInfo(block) {
    if (block.name === "core/image" || block.name === "core/cover") {
      const { url, alt, id } = block.attributes;
      return { url, alt, id };
    }
    if (block.name === "core/media-text") {
      const { mediaUrl: url, mediaAlt: alt, mediaId: id } = block.attributes;
      return { url, alt, id };
    }
    return {};
  }
  function Image2({ clientId, alt, url }) {
    const { selectBlock: selectBlock2 } = (0, import_data161.useDispatch)(import_block_editor57.store);
    return /* @__PURE__ */ (0, import_jsx_runtime454.jsx)(
      import_components214.__unstableMotion.img,
      {
        tabIndex: 0,
        role: "button",
        "aria-label": (0, import_i18n259.__)("Select image block."),
        onClick: () => {
          selectBlock2(clientId);
        },
        onKeyDown: (event) => {
          if (event.key === "Enter" || event.key === " ") {
            selectBlock2(clientId);
            event.preventDefault();
          }
        },
        alt,
        src: url,
        animate: { opacity: 1 },
        exit: { opacity: 0, scale: 0 },
        style: {
          width: "32px",
          height: "32px",
          objectFit: "cover",
          borderRadius: "2px",
          cursor: "var(--wpds-cursor-control, pointer)"
        },
        whileHover: { scale: 1.08 }
      },
      clientId
    );
  }
  function MaybeUploadMediaPanel() {
    const [isUploading, setIsUploading] = (0, import_element261.useState)(false);
    const [isAnimating2, setIsAnimating] = (0, import_element261.useState)(false);
    const [hadUploadError, setHadUploadError] = (0, import_element261.useState)(false);
    const { editorBlocks, mediaSideloadFromUrl: mediaSideloadFromUrl2 } = (0, import_data161.useSelect)(
      (select9) => ({
        editorBlocks: select9(import_block_editor57.store).getBlocks(),
        mediaSideloadFromUrl: select9(import_block_editor57.store).getSettings()[mediaSideloadFromUrlKey2]
      }),
      []
    );
    const blocksWithExternalMedia = flattenBlocks(editorBlocks).filter(
      (block) => hasExternalMedia(block)
    );
    const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data161.useDispatch)(import_block_editor57.store);
    if (!mediaSideloadFromUrl2 || !blocksWithExternalMedia.length) {
      return null;
    }
    const panelBodyTitle = [
      (0, import_i18n259.__)("Suggestion:"),
      /* @__PURE__ */ (0, import_jsx_runtime454.jsx)("span", { className: "editor-post-publish-panel__link", children: (0, import_i18n259.__)("External media") }, "label")
    ];
    function updateBlockWithUploadedMedia(block, media) {
      if (block.name === "core/image" || block.name === "core/cover") {
        updateBlockAttributes2(block.clientId, {
          id: media.id,
          url: media.url
        });
      }
      if (block.name === "core/media-text") {
        updateBlockAttributes2(block.clientId, {
          mediaId: media.id,
          mediaUrl: media.url
        });
      }
    }
    function uploadImages() {
      setIsUploading(true);
      setHadUploadError(false);
      const mediaUrls = new Set(
        blocksWithExternalMedia.map((block) => {
          const { url } = getMediaInfo(block);
          return url;
        })
      );
      const uploadPromises = Object.fromEntries(
        [...mediaUrls].map((url) => {
          const uploadPromise = new Promise((resolve, reject) => {
            mediaSideloadFromUrl2({
              url,
              onSuccess: (media) => resolve(media),
              onError: () => reject()
            });
          });
          return [url, uploadPromise];
        })
      );
      Promise.allSettled(
        blocksWithExternalMedia.map((block) => {
          const { url } = getMediaInfo(block);
          return uploadPromises[url].then(
            (media) => updateBlockWithUploadedMedia(block, media)
          ).then(() => setIsAnimating(true)).catch(() => setHadUploadError(true));
        })
      ).finally(() => {
        setIsUploading(false);
      });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime454.jsxs)(import_components214.PanelBody, { initialOpen: true, title: panelBodyTitle, children: [
      /* @__PURE__ */ (0, import_jsx_runtime454.jsx)("p", { children: (0, import_i18n259.__)(
        "Upload external images to the Media Library. Images from different domains may load slowly, display incorrectly, or be removed unexpectedly."
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime454.jsxs)(
        "div",
        {
          style: {
            display: "inline-flex",
            flexWrap: "wrap",
            gap: "8px"
          },
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime454.jsx)(
              import_components214.__unstableAnimatePresence,
              {
                onExitComplete: () => setIsAnimating(false),
                children: blocksWithExternalMedia.map((block) => {
                  const { url, alt } = getMediaInfo(block);
                  return /* @__PURE__ */ (0, import_jsx_runtime454.jsx)(
                    Image2,
                    {
                      clientId: block.clientId,
                      url,
                      alt
                    },
                    block.clientId
                  );
                })
              }
            ),
            isUploading || isAnimating2 ? /* @__PURE__ */ (0, import_jsx_runtime454.jsx)(import_components214.Spinner, {}) : /* @__PURE__ */ (0, import_jsx_runtime454.jsx)(
              import_components214.Button,
              {
                size: "compact",
                variant: "primary",
                onClick: uploadImages,
                children: (0, import_i18n259._x)("Upload", "verb")
              }
            )
          ]
        }
      ),
      hadUploadError && /* @__PURE__ */ (0, import_jsx_runtime454.jsx)("p", { children: (0, import_i18n259.__)("Upload failed, try again.") })
    ] });
  }

  // packages/editor/build-module/components/post-publish-panel/prepublish.mjs
  var import_jsx_runtime455 = __toESM(require_jsx_runtime(), 1);
  function PostPublishPanelPrepublish({ children }) {
    const {
      isBeingScheduled,
      isRequestingSiteIcon,
      hasPublishAction,
      siteIconUrl,
      siteTitle,
      siteHome
    } = (0, import_data162.useSelect)((select9) => {
      const { getCurrentPost: getCurrentPost2, isEditedPostBeingScheduled: isEditedPostBeingScheduled2 } = select9(store);
      const { getEntityRecord, isResolving } = select9(import_core_data97.store);
      const siteData = getEntityRecord("root", "__unstableBase", void 0) || {};
      return {
        hasPublishAction: getCurrentPost2()._links?.["wp:action-publish"] ?? false,
        isBeingScheduled: isEditedPostBeingScheduled2(),
        isRequestingSiteIcon: isResolving("getEntityRecord", [
          "root",
          "__unstableBase",
          void 0
        ]),
        siteIconUrl: siteData.site_icon_url,
        siteTitle: siteData.name,
        siteHome: siteData.home && (0, import_url19.filterURLForDisplay)(siteData.home)
      };
    }, []);
    let siteIcon = /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
      import_components215.Icon,
      {
        className: "components-site-icon",
        size: "36px",
        icon: wordpress_default
      }
    );
    if (siteIconUrl) {
      siteIcon = /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
        "img",
        {
          alt: (0, import_i18n260.__)("Site Icon"),
          className: "components-site-icon",
          src: siteIconUrl
        }
      );
    }
    if (isRequestingSiteIcon) {
      siteIcon = null;
    }
    let prePublishTitle, prePublishBodyText;
    if (!hasPublishAction) {
      prePublishTitle = (0, import_i18n260.__)("Are you ready to submit for review?");
      prePublishBodyText = (0, import_i18n260.__)(
        "Your work will be reviewed and then approved."
      );
    } else if (isBeingScheduled) {
      prePublishTitle = (0, import_i18n260.__)("Are you ready to schedule?");
      prePublishBodyText = (0, import_i18n260.__)(
        "Your work will be published at the specified date and time."
      );
    } else {
      prePublishTitle = (0, import_i18n260.__)("Are you ready to publish?");
      prePublishBodyText = (0, import_i18n260.__)(
        "Double-check your settings before publishing."
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime455.jsxs)("div", { className: "editor-post-publish-panel__prepublish", children: [
      /* @__PURE__ */ (0, import_jsx_runtime455.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime455.jsx)("strong", { children: prePublishTitle }) }),
      /* @__PURE__ */ (0, import_jsx_runtime455.jsx)("p", { children: prePublishBodyText }),
      /* @__PURE__ */ (0, import_jsx_runtime455.jsxs)("div", { className: "components-site-card", children: [
        siteIcon,
        /* @__PURE__ */ (0, import_jsx_runtime455.jsxs)("div", { className: "components-site-info", children: [
          /* @__PURE__ */ (0, import_jsx_runtime455.jsx)("span", { className: "components-site-name", children: (0, import_html_entities27.decodeEntities)(siteTitle) || (0, import_i18n260.__)("(Untitled)") }),
          /* @__PURE__ */ (0, import_jsx_runtime455.jsx)("span", { className: "components-site-home", children: siteHome })
        ] })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(MaybeUploadMediaPanel, {}),
      hasPublishAction && /* @__PURE__ */ (0, import_jsx_runtime455.jsxs)(import_jsx_runtime455.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
          import_components215.PanelBody,
          {
            initialOpen: false,
            title: [
              (0, import_i18n260.__)("Visibility:"),
              /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
                "span",
                {
                  className: "editor-post-publish-panel__link",
                  children: /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(PostVisibilityLabel, {})
                },
                "label"
              )
            ],
            children: /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(PostVisibility, {})
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
          import_components215.PanelBody,
          {
            initialOpen: false,
            title: [
              (0, import_i18n260.__)("Publish:"),
              /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(
                "span",
                {
                  className: "editor-post-publish-panel__link",
                  children: /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(PostScheduleLabel, {})
                },
                "label"
              )
            ],
            children: /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(PostSchedule, {})
          }
        )
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(PostFormatPanel, {}),
      /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(maybe_tags_panel_default, {}),
      /* @__PURE__ */ (0, import_jsx_runtime455.jsx)(maybe_category_panel_default, {}),
      children
    ] });
  }
  var prepublish_default = PostPublishPanelPrepublish;

  // packages/editor/build-module/components/post-publish-panel/postpublish.mjs
  var import_components216 = __toESM(require_components(), 1);
  var import_i18n261 = __toESM(require_i18n(), 1);
  var import_element262 = __toESM(require_element(), 1);
  var import_data163 = __toESM(require_data(), 1);
  var import_url20 = __toESM(require_url(), 1);
  var import_html_entities28 = __toESM(require_html_entities(), 1);
  var import_compose52 = __toESM(require_compose(), 1);
  var import_core_data98 = __toESM(require_core_data(), 1);
  var import_jsx_runtime456 = __toESM(require_jsx_runtime(), 1);
  var POSTNAME = "%postname%";
  var PAGENAME = "%pagename%";
  var getFuturePostUrl = (post2) => {
    const { slug } = post2;
    if (post2.permalink_template.includes(POSTNAME)) {
      return post2.permalink_template.replace(POSTNAME, slug);
    }
    if (post2.permalink_template.includes(PAGENAME)) {
      return post2.permalink_template.replace(PAGENAME, slug);
    }
    return post2.permalink_template;
  };
  function CopyButton2({ text }) {
    const [showCopyConfirmation, setShowCopyConfirmation] = (0, import_element262.useState)(false);
    const timeoutIdRef = (0, import_element262.useRef)();
    const ref = (0, import_compose52.useCopyToClipboard)(text, () => {
      setShowCopyConfirmation(true);
      if (timeoutIdRef.current) {
        clearTimeout(timeoutIdRef.current);
      }
      timeoutIdRef.current = setTimeout(() => {
        setShowCopyConfirmation(false);
      }, 4e3);
    });
    (0, import_element262.useEffect)(() => {
      return () => {
        if (timeoutIdRef.current) {
          clearTimeout(timeoutIdRef.current);
        }
      };
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(import_components216.Button, { __next40pxDefaultSize: true, variant: "secondary", ref, children: showCopyConfirmation ? (0, import_i18n261.__)("Copied!") : (0, import_i18n261.__)("Copy") });
  }
  function PostPublishPanelPostpublish({
    focusOnMount,
    children
  }) {
    const { post: post2, postType: postType2, isScheduled } = (0, import_data163.useSelect)((select9) => {
      const {
        getEditedPostAttribute: getEditedPostAttribute2,
        getCurrentPost: getCurrentPost2,
        isCurrentPostScheduled: isCurrentPostScheduled2
      } = select9(store);
      const { getPostType } = select9(import_core_data98.store);
      return {
        post: getCurrentPost2(),
        postType: getPostType(getEditedPostAttribute2("type")),
        isScheduled: isCurrentPostScheduled2()
      };
    }, []);
    const postLabel = postType2?.labels?.singular_name;
    const viewPostLabel = postType2?.labels?.view_item;
    const addNewPostLabel = postType2?.labels?.add_new_item;
    const link = post2.status === "future" ? getFuturePostUrl(post2) : post2.link;
    const addLink = (0, import_url20.addQueryArgs)("post-new.php", {
      post_type: post2.type
    });
    const postLinkRef = (0, import_element262.useCallback)(
      (node) => {
        if (focusOnMount && node) {
          node.focus();
        }
      },
      [focusOnMount]
    );
    const postPublishNonLinkHeader = isScheduled ? /* @__PURE__ */ (0, import_jsx_runtime456.jsxs)(import_jsx_runtime456.Fragment, { children: [
      (0, import_i18n261.__)("is now scheduled. It will go live on"),
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(PostScheduleLabel, {}),
      "."
    ] }) : (0, import_i18n261.__)("is now live.");
    return /* @__PURE__ */ (0, import_jsx_runtime456.jsxs)("div", { className: "post-publish-panel__postpublish", children: [
      /* @__PURE__ */ (0, import_jsx_runtime456.jsxs)(import_components216.PanelBody, { className: "post-publish-panel__postpublish-header", children: [
        /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(import_components216.ExternalLink, { ref: postLinkRef, href: link, children: (0, import_html_entities28.decodeEntities)(post2.title) || (0, import_i18n261.__)("(no title)") }),
        " ",
        postPublishNonLinkHeader
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime456.jsxs)(import_components216.PanelBody, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime456.jsx)("p", { className: "post-publish-panel__postpublish-subheader", children: /* @__PURE__ */ (0, import_jsx_runtime456.jsx)("strong", { children: (0, import_i18n261.__)("What\u2019s next?") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime456.jsxs)("div", { className: "post-publish-panel__postpublish-post-address-container", children: [
          /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(
            import_components216.TextControl,
            {
              className: "post-publish-panel__postpublish-post-address",
              readOnly: true,
              label: (0, import_i18n261.sprintf)(
                /* translators: %s: post type singular name */
                (0, import_i18n261.__)("%s address"),
                postLabel
              ),
              value: (0, import_url20.safeDecodeURIComponent)(link),
              onFocus: (event) => event.target.select()
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime456.jsx)("div", { className: "post-publish-panel__postpublish-post-address__copy-button-wrap", children: /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(CopyButton2, { text: link }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime456.jsxs)("div", { className: "post-publish-panel__postpublish-buttons", children: [
          !isScheduled && /* @__PURE__ */ (0, import_jsx_runtime456.jsxs)(
            import_components216.Button,
            {
              variant: "primary",
              href: link,
              __next40pxDefaultSize: true,
              icon: external_default,
              iconPosition: "right",
              target: "_blank",
              children: [
                viewPostLabel,
                /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(VisuallyHidden, {
                  render: /* @__PURE__ */ (0, import_jsx_runtime456.jsx)("span", {}),
                  /* translators: accessibility text */
                  children: (0, import_i18n261.__)("(opens in a new tab)")
                })
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime456.jsx)(
            import_components216.Button,
            {
              variant: isScheduled ? "primary" : "secondary",
              __next40pxDefaultSize: true,
              href: addLink,
              children: addNewPostLabel
            }
          )
        ] })
      ] }),
      children
    ] });
  }

  // packages/editor/build-module/components/post-publish-panel/index.mjs
  var import_jsx_runtime457 = __toESM(require_jsx_runtime(), 1);
  function PostPublishPanel({
    forceIsDirty,
    onClose,
    PostPublishExtension,
    PrePublishExtension,
    ...propsForPanel
  }) {
    const {
      hasPublishAction,
      isPostTypeViewable,
      isBeingScheduled,
      isDirty,
      isPublished,
      isPublishSidebarEnabled: isPublishSidebarEnabled2,
      isSaving,
      isSavingNonPostEntityChanges: isSavingNonPostEntityChanges2,
      isScheduled,
      currentPostId
    } = (0, import_data164.useSelect)((select9) => {
      const { getPostType } = select9(import_core_data99.store);
      const {
        getCurrentPost: getCurrentPost2,
        getCurrentPostId: getCurrentPostId2,
        getEditedPostAttribute: getEditedPostAttribute2,
        isCurrentPostPublished: isCurrentPostPublished2,
        isCurrentPostScheduled: isCurrentPostScheduled2,
        isEditedPostBeingScheduled: isEditedPostBeingScheduled2,
        isEditedPostDirty: isEditedPostDirty2,
        isAutosavingPost: isAutosavingPost2,
        isSavingPost: isSavingPost2,
        isSavingNonPostEntityChanges: _isSavingNonPostEntityChanges,
        isPublishSidebarEnabled: _isPublishSidebarEnabled
      } = select9(store);
      const postType2 = getPostType(getEditedPostAttribute2("type"));
      return {
        hasPublishAction: getCurrentPost2()._links?.["wp:action-publish"] ?? false,
        isPostTypeViewable: postType2?.viewable,
        isBeingScheduled: isEditedPostBeingScheduled2(),
        isDirty: isEditedPostDirty2(),
        isPublished: isCurrentPostPublished2(),
        isPublishSidebarEnabled: _isPublishSidebarEnabled(),
        isSaving: isSavingPost2() && !isAutosavingPost2(),
        isSavingNonPostEntityChanges: _isSavingNonPostEntityChanges(),
        isScheduled: isCurrentPostScheduled2(),
        currentPostId: getCurrentPostId2()
      };
    }, []);
    const { disablePublishSidebar: disablePublishSidebar2, enablePublishSidebar: enablePublishSidebar2 } = (0, import_data164.useDispatch)(store);
    const cancelButtonRef = (0, import_element263.useRef)(null);
    const wrapperRef = (0, import_compose53.useMergeRefs)([
      (0, import_compose53.useFocusReturn)(),
      (0, import_compose53.useConstrainedTabbing)()
    ]);
    (0, import_element263.useEffect)(() => {
      cancelButtonRef.current?.focus();
    }, []);
    const prevPostIdRef = (0, import_element263.useRef)(currentPostId);
    const stableOnClose = (0, import_compose53.useEvent)(onClose);
    (0, import_element263.useEffect)(() => {
      const postChanged = currentPostId !== prevPostIdRef.current;
      prevPostIdRef.current = currentPostId;
      if (postChanged || isPublished && !isSaving && isDirty) {
        stableOnClose();
      }
    }, [isPublished, isSaving, isDirty, currentPostId, stableOnClose]);
    function onTogglePublishSidebar() {
      if (isPublishSidebarEnabled2) {
        disablePublishSidebar2();
      } else {
        enablePublishSidebar2();
      }
    }
    function onSubmit() {
      if (!hasPublishAction || !isPostTypeViewable) {
        onClose();
      }
    }
    const isPublishedOrScheduled = isPublished || isScheduled && isBeingScheduled;
    const isPrePublish = !isPublishedOrScheduled && !isSaving;
    const isPostPublish = isPublishedOrScheduled && !isSaving;
    return /* @__PURE__ */ (0, import_jsx_runtime457.jsxs)(
      "div",
      {
        ref: wrapperRef,
        tabIndex: -1,
        className: "editor-post-publish-panel",
        ...propsForPanel,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime457.jsx)("div", { className: "editor-post-publish-panel__header", children: isPostPublish ? /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(
            import_components217.Button,
            {
              size: "compact",
              onClick: onClose,
              icon: close_small_default,
              label: (0, import_i18n262.__)("Close panel")
            }
          ) : /* @__PURE__ */ (0, import_jsx_runtime457.jsxs)(import_jsx_runtime457.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime457.jsx)("div", { className: "editor-post-publish-panel__header-cancel-button", children: /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(
              import_components217.Button,
              {
                ref: cancelButtonRef,
                accessibleWhenDisabled: true,
                disabled: isSavingNonPostEntityChanges2,
                onClick: onClose,
                variant: "secondary",
                size: "compact",
                children: (0, import_i18n262.__)("Cancel")
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime457.jsx)("div", { className: "editor-post-publish-panel__header-publish-button", children: /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(
              post_publish_button_default,
              {
                onSubmit,
                forceIsDirty
              }
            ) })
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime457.jsxs)("div", { className: "editor-post-publish-panel__content", children: [
            isPrePublish && /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(prepublish_default, { children: PrePublishExtension && /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(PrePublishExtension, {}) }),
            isPostPublish && /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(PostPublishPanelPostpublish, { focusOnMount: true, children: PostPublishExtension && /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(PostPublishExtension, {}) }),
            isSaving && /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(import_components217.Spinner, {})
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime457.jsx)("div", { className: "editor-post-publish-panel__footer", children: /* @__PURE__ */ (0, import_jsx_runtime457.jsx)(
            import_components217.CheckboxControl,
            {
              label: (0, import_i18n262.__)("Always show pre-publish checks."),
              checked: isPublishSidebarEnabled2,
              onChange: onTogglePublishSidebar
            }
          ) })
        ]
      }
    );
  }

  // packages/editor/build-module/components/post-saved-state/index.mjs
  var import_components220 = __toESM(require_components(), 1);
  var import_compose55 = __toESM(require_compose(), 1);
  var import_data168 = __toESM(require_data(), 1);
  var import_element265 = __toESM(require_element(), 1);
  var import_i18n265 = __toESM(require_i18n(), 1);
  var import_keycodes14 = __toESM(require_keycodes(), 1);
  var import_preferences14 = __toESM(require_preferences(), 1);

  // packages/editor/build-module/components/post-status/index.mjs
  var import_components219 = __toESM(require_components(), 1);
  var import_i18n264 = __toESM(require_i18n(), 1);
  var import_data167 = __toESM(require_data(), 1);
  var import_element264 = __toESM(require_element(), 1);
  var import_core_data100 = __toESM(require_core_data(), 1);
  var import_block_editor58 = __toESM(require_block_editor(), 1);
  var import_compose54 = __toESM(require_compose(), 1);

  // packages/editor/build-module/components/post-sticky/index.mjs
  var import_i18n263 = __toESM(require_i18n(), 1);
  var import_components218 = __toESM(require_components(), 1);
  var import_data166 = __toESM(require_data(), 1);

  // packages/editor/build-module/components/post-sticky/check.mjs
  var import_data165 = __toESM(require_data(), 1);
  function PostStickyCheck({ children }) {
    const { hasStickyAction, postType: postType2 } = (0, import_data165.useSelect)((select9) => {
      const post2 = select9(store).getCurrentPost();
      return {
        hasStickyAction: post2._links?.["wp:action-sticky"] ?? false,
        postType: select9(store).getCurrentPostType()
      };
    }, []);
    if (postType2 !== "post" || !hasStickyAction) {
      return null;
    }
    return children;
  }

  // packages/editor/build-module/components/post-sticky/index.mjs
  var import_jsx_runtime458 = __toESM(require_jsx_runtime(), 1);
  function PostSticky() {
    const postSticky = (0, import_data166.useSelect)((select9) => {
      return select9(store).getEditedPostAttribute("sticky") ?? false;
    }, []);
    const { editPost: editPost2 } = (0, import_data166.useDispatch)(store);
    return /* @__PURE__ */ (0, import_jsx_runtime458.jsx)(PostStickyCheck, { children: /* @__PURE__ */ (0, import_jsx_runtime458.jsx)(
      import_components218.CheckboxControl,
      {
        className: "editor-post-sticky__checkbox-control",
        label: (0, import_i18n263.__)("Sticky"),
        help: (0, import_i18n263.__)("Pin this post to the top of the blog."),
        checked: postSticky,
        onChange: () => editPost2({ sticky: !postSticky })
      }
    ) });
  }

  // packages/editor/build-module/components/post-status/index.mjs
  var import_jsx_runtime459 = __toESM(require_jsx_runtime(), 1);
  var postStatusesInfo = {
    "auto-draft": { label: (0, import_i18n264.__)("Draft"), icon: drafts_default },
    draft: { label: (0, import_i18n264.__)("Draft"), icon: drafts_default },
    pending: { label: (0, import_i18n264.__)("Pending"), icon: pending_default },
    private: { label: (0, import_i18n264.__)("Private"), icon: not_allowed_default },
    future: { label: (0, import_i18n264.__)("Scheduled"), icon: scheduled_default },
    publish: { label: (0, import_i18n264.__)("Published"), icon: published_default }
  };
  var STATUS_OPTIONS = [
    {
      label: (0, import_i18n264.__)("Draft"),
      value: "draft",
      description: (0, import_i18n264.__)("Not ready to publish.")
    },
    {
      label: (0, import_i18n264.__)("Pending"),
      value: "pending",
      description: (0, import_i18n264.__)("Waiting for review before publishing.")
    },
    {
      label: (0, import_i18n264.__)("Private"),
      value: "private",
      description: (0, import_i18n264.__)("Only visible to site admins and editors.")
    },
    {
      label: (0, import_i18n264.__)("Scheduled"),
      value: "future",
      description: (0, import_i18n264.__)("Publish automatically on a chosen date.")
    },
    {
      label: (0, import_i18n264.__)("Published"),
      value: "publish",
      description: (0, import_i18n264.__)("Visible to everyone.")
    }
  ];
  function PostStatus() {
    const { status, date, password, postId: postId2, postType: postType2, canEdit } = (0, import_data167.useSelect)(
      (select9) => {
        const {
          getEditedPostAttribute: getEditedPostAttribute2,
          getCurrentPostId: getCurrentPostId2,
          getCurrentPostType: getCurrentPostType2,
          getCurrentPost: getCurrentPost2
        } = select9(store);
        return {
          status: getEditedPostAttribute2("status"),
          date: getEditedPostAttribute2("date"),
          password: getEditedPostAttribute2("password"),
          postId: getCurrentPostId2(),
          postType: getCurrentPostType2(),
          canEdit: getCurrentPost2()._links?.["wp:action-publish"] ?? false
        };
      },
      []
    );
    const [showPassword, setShowPassword] = (0, import_element264.useState)(!!password);
    const passwordInputId = (0, import_compose54.useInstanceId)(
      PostStatus,
      "editor-change-status__password-input"
    );
    const { editEntityRecord } = (0, import_data167.useDispatch)(import_core_data100.store);
    const [popoverAnchor, setPopoverAnchor] = (0, import_element264.useState)(null);
    const popoverProps = (0, import_element264.useMemo)(
      () => ({
        // Anchor the popover to the middle of the entire row so that it doesn't
        // move around when the label changes.
        anchor: popoverAnchor,
        "aria-label": (0, import_i18n264.__)("Status & visibility"),
        headerTitle: (0, import_i18n264.__)("Status & visibility"),
        placement: "left-start",
        offset: 36,
        shift: true
      }),
      [popoverAnchor]
    );
    if (DESIGN_POST_TYPES.includes(postType2)) {
      return null;
    }
    const updatePost2 = ({
      status: newStatus = status,
      password: newPassword = password,
      date: newDate = date
    }) => {
      editEntityRecord("postType", postType2, postId2, {
        status: newStatus,
        date: newDate,
        password: newPassword
      });
    };
    const handleTogglePassword = (value) => {
      setShowPassword(value);
      if (!value) {
        updatePost2({ password: "" });
      }
    };
    const handleStatus = (value) => {
      let newDate = date;
      let newPassword = password;
      if (status === "future" && new Date(date) > /* @__PURE__ */ new Date()) {
        newDate = null;
      }
      if (value === "private" && password) {
        newPassword = "";
      }
      updatePost2({
        status: value,
        date: newDate,
        password: newPassword
      });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(post_panel_row_default, { label: (0, import_i18n264.__)("Status"), ref: setPopoverAnchor, children: canEdit ? /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(
      import_components219.Dropdown,
      {
        className: "editor-post-status",
        contentClassName: "editor-change-status__content",
        popoverProps,
        focusOnMount: true,
        renderToggle: ({ onToggle, isOpen: isOpen2 }) => /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(
          import_components219.Button,
          {
            className: "editor-post-status__toggle",
            variant: "tertiary",
            size: "compact",
            onClick: onToggle,
            icon: postStatusesInfo[status]?.icon,
            "aria-label": (0, import_i18n264.sprintf)(
              // translators: %s: Current post status.
              (0, import_i18n264.__)("Change status: %s"),
              postStatusesInfo[status]?.label
            ),
            "aria-expanded": isOpen2,
            children: postStatusesInfo[status]?.label
          }
        ),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime459.jsxs)(import_jsx_runtime459.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(
            import_block_editor58.__experimentalInspectorPopoverHeader,
            {
              title: (0, import_i18n264.__)("Status & visibility"),
              onClose
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(
            "form",
            {
              onSubmit: (event) => {
                event.preventDefault();
                onClose();
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime459.jsxs)(import_components219.__experimentalVStack, { spacing: 4, children: [
                /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(
                  import_components219.RadioControl,
                  {
                    className: "editor-change-status__options",
                    hideLabelFromVision: true,
                    label: (0, import_i18n264.__)("Status"),
                    options: STATUS_OPTIONS,
                    onChange: handleStatus,
                    selected: status === "auto-draft" ? "draft" : status
                  }
                ),
                status === "future" && /* @__PURE__ */ (0, import_jsx_runtime459.jsx)("div", { className: "editor-change-status__publish-date-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(
                  PrivatePostSchedule,
                  {
                    showPopoverHeaderActions: false,
                    isCompact: true
                  }
                ) }),
                status !== "private" && /* @__PURE__ */ (0, import_jsx_runtime459.jsxs)(
                  import_components219.__experimentalVStack,
                  {
                    as: "fieldset",
                    spacing: 4,
                    className: "editor-change-status__password-fieldset",
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(
                        import_components219.CheckboxControl,
                        {
                          label: (0, import_i18n264.__)(
                            "Password protected"
                          ),
                          help: (0, import_i18n264.__)(
                            "Only visible to those who know the password."
                          ),
                          checked: showPassword,
                          onChange: handleTogglePassword
                        }
                      ),
                      showPassword && /* @__PURE__ */ (0, import_jsx_runtime459.jsx)("div", { className: "editor-change-status__password-input", children: /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(
                        import_components219.TextControl,
                        {
                          label: (0, import_i18n264.__)(
                            "Password"
                          ),
                          onChange: (value) => updatePost2({
                            password: value
                          }),
                          value: password,
                          placeholder: (0, import_i18n264.__)(
                            "Use a secure password"
                          ),
                          type: "text",
                          id: passwordInputId,
                          maxLength: 255
                        }
                      ) })
                    ]
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime459.jsx)(PostSticky, {})
              ] })
            }
          )
        ] })
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime459.jsx)("div", { className: "editor-post-status is-read-only", children: postStatusesInfo[status]?.label }) });
  }

  // packages/editor/build-module/components/post-saved-state/index.mjs
  var import_jsx_runtime460 = __toESM(require_jsx_runtime(), 1);
  function PostSavedState({ forceIsDirty }) {
    const [forceSavedMessage, setForceSavedMessage] = (0, import_element265.useState)(false);
    const isLargeViewport = (0, import_compose55.useViewportMatch)("small");
    const {
      isAutosaving,
      isDirty,
      isNew,
      isPublished,
      isSaveable,
      isSaving,
      isSavingLocked,
      isSavingNonPostEntityChanges: isSavingNonPostEntityChanges2,
      isScheduled,
      hasPublishAction,
      showIconLabels,
      postStatus,
      postStatusHasChanged,
      postType: postType2
    } = (0, import_data168.useSelect)(
      (select9) => {
        const store4 = select9(store);
        const { get } = select9(import_preferences14.store);
        return {
          isAutosaving: store4.isAutosavingPost(),
          isDirty: forceIsDirty || store4.isEditedPostDirty(),
          isNew: store4.isEditedPostNew(),
          isPublished: store4.isCurrentPostPublished(),
          isSaving: store4.isSavingPost(),
          isSaveable: store4.isEditedPostSaveable(),
          isSavingLocked: store4.isPostSavingLocked(),
          isSavingNonPostEntityChanges: store4.isSavingNonPostEntityChanges(),
          isScheduled: store4.isCurrentPostScheduled(),
          hasPublishAction: !!store4.getCurrentPost()?._links?.["wp:action-publish"],
          showIconLabels: get("core", "showIconLabels"),
          postStatus: store4.getEditedPostAttribute("status"),
          postStatusHasChanged: !!store4.getPostEdits()?.status,
          postType: store4.getCurrentPostType()
        };
      },
      [forceIsDirty]
    );
    const isPending = postStatus === "pending";
    const { savePost: savePost2 } = (0, import_data168.useDispatch)(store);
    const wasSaving = (0, import_compose55.usePrevious)(isSaving);
    (0, import_element265.useEffect)(() => {
      let timeoutId;
      if (wasSaving && !isSaving) {
        setForceSavedMessage(true);
        timeoutId = setTimeout(() => {
          setForceSavedMessage(false);
        }, 1e3);
      }
      return () => clearTimeout(timeoutId);
    }, [isSaving]);
    if (postType2 === ATTACHMENT_POST_TYPE) {
      return null;
    }
    if (!hasPublishAction && isPending) {
      return null;
    }
    const isIneligibleStatus = !["pending", "draft", "auto-draft"].includes(postStatus) && STATUS_OPTIONS.map(({ value }) => value).includes(postStatus);
    if (isPublished || isScheduled || isIneligibleStatus || postStatusHasChanged && ["pending", "draft"].includes(postStatus)) {
      return null;
    }
    const label = isPending ? (0, import_i18n265.__)("Save as pending") : (0, import_i18n265.__)("Save draft");
    const shortLabel = (0, import_i18n265.__)("Save");
    const isSaved = forceSavedMessage || !isNew && !isDirty;
    const isSavedState = isSaving || isSaved;
    const isDisabled = isSaving || isSaved || !isSaveable || isSavingLocked || // Disable while a non-post entity (e.g. a newly created term) is mid-save.
    isSavingNonPostEntityChanges2;
    let text;
    if (isSaving) {
      text = isAutosaving ? (0, import_i18n265.__)("Autosaving") : (0, import_i18n265.__)("Saving");
    } else if (isSaved) {
      text = (0, import_i18n265.__)("Saved");
    } else if (isLargeViewport) {
      text = label;
    } else if (showIconLabels) {
      text = shortLabel;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime460.jsxs)(
      import_components220.Button,
      {
        className: isSaveable || isSaving ? clsx_default({
          "editor-post-save-draft": !isSavedState,
          "editor-post-saved-state": isSavedState,
          "is-saving": isSaving,
          "is-autosaving": isAutosaving,
          "is-saved": isSaved,
          [(0, import_components220.__unstableGetAnimateClassName)({
            type: "loading"
          })]: isSaving
        }) : void 0,
        onClick: isDisabled ? void 0 : () => savePost2(),
        shortcut: isDisabled ? void 0 : import_keycodes14.displayShortcut.primary("s"),
        variant: "tertiary",
        size: "compact",
        icon: isLargeViewport ? void 0 : cloud_upload_default,
        label: text || label,
        "aria-disabled": isDisabled,
        children: [
          isSavedState && /* @__PURE__ */ (0, import_jsx_runtime460.jsx)(icon_default, { icon: isSaved ? check_default : cloud_default }),
          text
        ]
      }
    );
  }

  // packages/editor/build-module/components/post-schedule/check.mjs
  var import_data169 = __toESM(require_data(), 1);
  function PostScheduleCheck({ children }) {
    const hasPublishAction = (0, import_data169.useSelect)((select9) => {
      return select9(store).getCurrentPost()._links?.["wp:action-publish"] ?? false;
    }, []);
    if (!hasPublishAction) {
      return null;
    }
    return children;
  }

  // packages/editor/build-module/components/post-schedule/panel.mjs
  var import_components221 = __toESM(require_components(), 1);
  var import_i18n266 = __toESM(require_i18n(), 1);
  var import_element266 = __toESM(require_element(), 1);
  var import_data170 = __toESM(require_data(), 1);
  var import_jsx_runtime461 = __toESM(require_jsx_runtime(), 1);
  function PostSchedulePanel() {
    const [popoverAnchor, setPopoverAnchor] = (0, import_element266.useState)(null);
    const postType2 = (0, import_data170.useSelect)(
      (select9) => select9(store).getCurrentPostType(),
      []
    );
    const popoverProps = (0, import_element266.useMemo)(
      () => ({
        // Anchor the popover to the middle of the entire row so that it doesn't
        // move around when the label changes.
        anchor: popoverAnchor,
        "aria-label": (0, import_i18n266.__)("Change publish date"),
        placement: "left-start",
        offset: 36,
        shift: true
      }),
      [popoverAnchor]
    );
    const label = usePostScheduleLabel();
    const fullLabel = usePostScheduleLabel({ full: true });
    if (DESIGN_POST_TYPES.includes(postType2)) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime461.jsx)(PostScheduleCheck, { children: /* @__PURE__ */ (0, import_jsx_runtime461.jsx)(post_panel_row_default, { label: (0, import_i18n266.__)("Publish"), ref: setPopoverAnchor, children: /* @__PURE__ */ (0, import_jsx_runtime461.jsx)(
      import_components221.Dropdown,
      {
        popoverProps,
        focusOnMount: true,
        className: "editor-post-schedule__panel-dropdown",
        contentClassName: "editor-post-schedule__dialog",
        renderToggle: ({ onToggle, isOpen: isOpen2 }) => /* @__PURE__ */ (0, import_jsx_runtime461.jsx)(
          import_components221.Button,
          {
            size: "compact",
            className: "editor-post-schedule__dialog-toggle",
            variant: "tertiary",
            tooltipPosition: "middle left",
            onClick: onToggle,
            "aria-label": (0, import_i18n266.sprintf)(
              // translators: %s: Current post date.
              (0, import_i18n266.__)("Change date: %s"),
              label
            ),
            label: fullLabel,
            showTooltip: label !== fullLabel,
            "aria-expanded": isOpen2,
            children: label
          }
        ),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime461.jsx)(PostSchedule, { onClose })
      }
    ) }) });
  }

  // packages/editor/build-module/components/post-switch-to-draft-button/index.mjs
  var import_components222 = __toESM(require_components(), 1);
  var import_i18n267 = __toESM(require_i18n(), 1);
  var import_data171 = __toESM(require_data(), 1);
  var import_element267 = __toESM(require_element(), 1);
  var import_deprecated12 = __toESM(require_deprecated(), 1);
  var import_jsx_runtime462 = __toESM(require_jsx_runtime(), 1);
  function PostSwitchToDraftButton() {
    (0, import_deprecated12.default)("wp.editor.PostSwitchToDraftButton", {
      since: "6.7",
      version: "6.9"
    });
    const [showConfirmDialog, setShowConfirmDialog] = (0, import_element267.useState)(false);
    const { editPost: editPost2, savePost: savePost2 } = (0, import_data171.useDispatch)(store);
    const { isSaving, isPublished, isScheduled } = (0, import_data171.useSelect)((select9) => {
      const { isSavingPost: isSavingPost2, isCurrentPostPublished: isCurrentPostPublished2, isCurrentPostScheduled: isCurrentPostScheduled2 } = select9(store);
      return {
        isSaving: isSavingPost2(),
        isPublished: isCurrentPostPublished2(),
        isScheduled: isCurrentPostScheduled2()
      };
    }, []);
    const isDisabled = isSaving || !isPublished && !isScheduled;
    let alertMessage;
    let confirmButtonText;
    if (isPublished) {
      alertMessage = (0, import_i18n267.__)("Are you sure you want to unpublish this post?");
      confirmButtonText = (0, import_i18n267.__)("Unpublish");
    } else if (isScheduled) {
      alertMessage = (0, import_i18n267.__)("Are you sure you want to unschedule this post?");
      confirmButtonText = (0, import_i18n267.__)("Unschedule");
    }
    const handleConfirm = () => {
      setShowConfirmDialog(false);
      editPost2({ status: "draft" });
      savePost2();
    };
    return /* @__PURE__ */ (0, import_jsx_runtime462.jsxs)(import_jsx_runtime462.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime462.jsx)(
        import_components222.Button,
        {
          __next40pxDefaultSize: true,
          className: "editor-post-switch-to-draft",
          onClick: () => {
            if (!isDisabled) {
              setShowConfirmDialog(true);
            }
          },
          "aria-disabled": isDisabled,
          variant: "secondary",
          style: { flexGrow: "1", justifyContent: "center" },
          children: (0, import_i18n267.__)("Switch to draft")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime462.jsx)(
        import_components222.__experimentalConfirmDialog,
        {
          isOpen: showConfirmDialog,
          onConfirm: handleConfirm,
          onCancel: () => setShowConfirmDialog(false),
          confirmButtonText,
          children: alertMessage
        }
      )
    ] });
  }

  // packages/editor/build-module/components/post-sync-status/index.mjs
  var import_data172 = __toESM(require_data(), 1);
  var import_i18n268 = __toESM(require_i18n(), 1);
  var import_jsx_runtime463 = __toESM(require_jsx_runtime(), 1);
  function PostSyncStatus() {
    const { syncStatus, postType: postType2 } = (0, import_data172.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
      const meta2 = getEditedPostAttribute2("meta");
      const currentSyncStatus = meta2?.wp_pattern_sync_status === "unsynced" ? "unsynced" : getEditedPostAttribute2("wp_pattern_sync_status");
      return {
        syncStatus: currentSyncStatus,
        postType: getEditedPostAttribute2("type")
      };
    });
    if (postType2 !== "wp_block") {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime463.jsx)(post_panel_row_default, { label: (0, import_i18n268.__)("Sync status"), children: /* @__PURE__ */ (0, import_jsx_runtime463.jsx)("div", { className: "editor-post-sync-status__value", children: syncStatus === "unsynced" ? (0, import_i18n268._x)("Not synced", "pattern (singular)") : (0, import_i18n268._x)("Synced", "pattern (singular)") }) });
  }

  // packages/editor/build-module/components/post-taxonomies/index.mjs
  var import_element268 = __toESM(require_element(), 1);
  var import_data173 = __toESM(require_data(), 1);
  var import_core_data101 = __toESM(require_core_data(), 1);
  var import_jsx_runtime464 = __toESM(require_jsx_runtime(), 1);
  var identity3 = (x2) => x2;
  function PostTaxonomies({ taxonomyWrapper = identity3 }) {
    const { postType: postType2, taxonomies } = (0, import_data173.useSelect)((select9) => {
      return {
        postType: select9(store).getCurrentPostType(),
        taxonomies: select9(import_core_data101.store).getEntityRecords(
          "root",
          "taxonomy"
        )
      };
    }, []);
    const visibleTaxonomies = (taxonomies ?? []).filter(
      (taxonomy) => (
        // In some circumstances .visibility can end up as undefined so optional chaining operator required.
        // https://github.com/WordPress/gutenberg/issues/40326
        taxonomy.types.includes(postType2) && taxonomy.visibility?.show_ui
      )
    );
    return visibleTaxonomies.map((taxonomy) => {
      const TaxonomyComponent = taxonomy.hierarchical ? hierarchical_term_selector_default : flat_term_selector_default;
      return /* @__PURE__ */ (0, import_jsx_runtime464.jsx)(import_element268.Fragment, { children: taxonomyWrapper(
        /* @__PURE__ */ (0, import_jsx_runtime464.jsx)(TaxonomyComponent, { slug: taxonomy.slug }),
        taxonomy
      ) }, `taxonomy-${taxonomy.slug}`);
    });
  }
  var post_taxonomies_default = PostTaxonomies;

  // packages/editor/build-module/components/post-taxonomies/check.mjs
  var import_data174 = __toESM(require_data(), 1);
  var import_core_data102 = __toESM(require_core_data(), 1);
  function PostTaxonomiesCheck({ children }) {
    const hasTaxonomies = (0, import_data174.useSelect)((select9) => {
      const postType2 = select9(store).getCurrentPostType();
      const taxonomies = select9(import_core_data102.store).getEntityRecords(
        "root",
        "taxonomy"
      );
      return taxonomies?.some(
        (taxonomy) => taxonomy.types.includes(postType2)
      );
    }, []);
    if (!hasTaxonomies) {
      return null;
    }
    return children;
  }

  // packages/editor/build-module/components/post-taxonomies/panel.mjs
  var import_components223 = __toESM(require_components(), 1);
  var import_data175 = __toESM(require_data(), 1);
  var import_jsx_runtime465 = __toESM(require_jsx_runtime(), 1);
  function TaxonomyPanel({ taxonomy, children }) {
    const slug = taxonomy?.slug;
    const panelName = slug ? `taxonomy-panel-${slug}` : "";
    const { isEnabled, isOpened } = (0, import_data175.useSelect)(
      (select9) => {
        const { isEditorPanelEnabled: isEditorPanelEnabled2, isEditorPanelOpened: isEditorPanelOpened2 } = select9(store);
        return {
          isEnabled: slug ? isEditorPanelEnabled2(panelName) : false,
          isOpened: slug ? isEditorPanelOpened2(panelName) : false
        };
      },
      [panelName, slug]
    );
    const { toggleEditorPanelOpened: toggleEditorPanelOpened2 } = (0, import_data175.useDispatch)(store);
    if (!isEnabled) {
      return null;
    }
    const taxonomyMenuName = taxonomy?.labels?.menu_name;
    if (!taxonomyMenuName) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime465.jsx)(
      import_components223.PanelBody,
      {
        title: taxonomyMenuName,
        opened: isOpened,
        onToggle: () => toggleEditorPanelOpened2(panelName),
        children
      }
    );
  }
  function PostTaxonomies2() {
    return /* @__PURE__ */ (0, import_jsx_runtime465.jsx)(PostTaxonomiesCheck, { children: /* @__PURE__ */ (0, import_jsx_runtime465.jsx)(
      post_taxonomies_default,
      {
        taxonomyWrapper: (content, taxonomy) => {
          return /* @__PURE__ */ (0, import_jsx_runtime465.jsx)(TaxonomyPanel, { taxonomy, children: content });
        }
      }
    ) });
  }

  // packages/editor/build-module/components/post-text-editor/index.mjs
  var import_react_autosize_textarea = __toESM(require_lib(), 1);
  var import_element269 = __toESM(require_element(), 1);
  var import_i18n269 = __toESM(require_i18n(), 1);
  var import_core_data103 = __toESM(require_core_data(), 1);
  var import_data176 = __toESM(require_data(), 1);
  var import_compose56 = __toESM(require_compose(), 1);

  // packages/editor/build-module/components/post-text-editor/utils.mjs
  var STRING_TOO_LARGE_THRESHOLD = 1e3;
  function getDiff(oldValue, newValue) {
    const maxStringLength = Math.max(oldValue.length, newValue.length);
    if (maxStringLength <= STRING_TOO_LARGE_THRESHOLD) {
      return diffChars(oldValue, newValue);
    }
    let start2 = 0;
    const minStringLength = Math.min(oldValue.length, newValue.length);
    while (start2 < minStringLength && oldValue[start2] === newValue[start2]) {
      start2++;
    }
    let oldEnd = oldValue.length;
    let newEnd = newValue.length;
    while (oldEnd > start2 && newEnd > start2 && oldValue[oldEnd - 1] === newValue[newEnd - 1]) {
      oldEnd--;
      newEnd--;
    }
    const oldChangedValue = oldValue.slice(start2, oldEnd);
    const newChangedValue = newValue.slice(start2, newEnd);
    const maxChangedStringLength = Math.max(
      oldChangedValue.length,
      newChangedValue.length
    );
    let changes;
    if (maxChangedStringLength <= STRING_TOO_LARGE_THRESHOLD) {
      changes = diffChars(oldChangedValue, newChangedValue);
    } else {
      changes = diffLines(oldChangedValue, newChangedValue);
    }
    if (start2 > 0) {
      changes.unshift({ value: oldValue.slice(0, start2) });
    }
    if (oldEnd < oldValue.length) {
      changes.push({ value: oldValue.slice(oldEnd) });
    }
    return changes;
  }
  function clampCursorPosition(position, value) {
    return Math.max(0, Math.min(value.length, position));
  }
  function getCursorOffsetFromCommonTextBeforeCursor(oldValue, newValue, position) {
    const oldValueBeforeCursor = oldValue.slice(0, position);
    let low = 1;
    let high = oldValueBeforeCursor.length;
    let cursorOffset;
    while (low <= high) {
      const length2 = Math.floor((low + high) / 2);
      const index2 = newValue.indexOf(
        oldValueBeforeCursor.slice(oldValueBeforeCursor.length - length2)
      );
      if (index2 === -1) {
        high = length2 - 1;
      } else {
        cursorOffset = index2 + length2;
        low = length2 + 1;
      }
    }
    return cursorOffset;
  }
  function adjustPosition(position, changes, oldValue, newValue) {
    let oldIndex = 0;
    let newIndex = 0;
    let adjustedPosition = position;
    for (let i3 = 0; i3 < changes.length; i3++) {
      const change = changes[i3];
      if (!change.added && !change.removed) {
        oldIndex += change.value.length;
        newIndex += change.value.length;
        continue;
      }
      const oldStart = oldIndex;
      const newStart = newIndex;
      let oldLength = 0;
      let newLength = 0;
      while (i3 < changes.length && (changes[i3].added || changes[i3].removed)) {
        if (changes[i3].removed) {
          oldLength += changes[i3].value.length;
        } else {
          newLength += changes[i3].value.length;
        }
        i3++;
      }
      i3--;
      const oldEnd = oldStart + oldLength;
      const newEnd = newStart + newLength;
      if (position < oldStart) {
        break;
      }
      if (oldLength === 0) {
        adjustedPosition += newLength;
      } else if (position <= oldEnd) {
        const cursorOffset = getCursorOffsetFromCommonTextBeforeCursor(
          oldValue.slice(oldStart, oldEnd),
          newValue.slice(newStart, newEnd),
          position - oldStart
        );
        adjustedPosition = cursorOffset === void 0 ? newEnd : newStart + cursorOffset;
        break;
      } else {
        adjustedPosition += newLength - oldLength;
      }
      oldIndex += oldLength;
      newIndex += newLength;
    }
    return clampCursorPosition(adjustedPosition, newValue);
  }

  // packages/editor/build-module/components/post-text-editor/index.mjs
  var import_jsx_runtime466 = __toESM(require_jsx_runtime(), 1);
  function PostTextEditor() {
    const instanceId = (0, import_compose56.useInstanceId)(PostTextEditor);
    const textareaRef = (0, import_element269.useRef)();
    const previousValueRef = (0, import_element269.useRef)();
    const selectionRef = (0, import_element269.useRef)();
    const { value, type, id } = (0, import_data176.useSelect)((select9) => {
      const { getCurrentPostType: getCurrentPostType2, getCurrentPostId: getCurrentPostId2, getEditedPostContent: getEditedPostContent2 } = select9(store);
      return {
        value: getEditedPostContent2(),
        type: getCurrentPostType2(),
        id: getCurrentPostId2()
      };
    }, []);
    const { editEntityRecord } = (0, import_data176.useDispatch)(import_core_data103.store);
    (0, import_element269.useLayoutEffect)(() => {
      const textarea = textareaRef.current;
      const previousValue = previousValueRef.current;
      previousValueRef.current = value;
      if (!textarea || previousValue === void 0 || previousValue === value || !selectionRef.current) {
        return;
      }
      const { selectionStart, selectionEnd, selectionDirection } = selectionRef.current;
      const changes = getDiff(previousValue, value);
      const adjustedSelectionStart = adjustPosition(
        selectionStart,
        changes,
        previousValue,
        value
      );
      const adjustedSelectionEnd = adjustPosition(
        selectionEnd,
        changes,
        previousValue,
        value
      );
      textarea.setSelectionRange(
        adjustedSelectionStart,
        adjustedSelectionEnd,
        selectionDirection
      );
      selectionRef.current = {
        selectionStart: adjustedSelectionStart,
        selectionEnd: adjustedSelectionEnd,
        selectionDirection
      };
    }, [value]);
    const updateSelection = (event) => {
      const { selectionStart, selectionEnd, selectionDirection } = event.target;
      selectionRef.current = {
        selectionStart,
        selectionEnd,
        selectionDirection
      };
    };
    return /* @__PURE__ */ (0, import_jsx_runtime466.jsxs)(import_jsx_runtime466.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime466.jsx)(
        VisuallyHidden,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime466.jsx)("label", { htmlFor: `post-content-${instanceId}` }),
          children: (0, import_i18n269.__)("Type text or HTML")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime466.jsx)(
        import_react_autosize_textarea.default,
        {
          autoComplete: "off",
          dir: "auto",
          ref: textareaRef,
          value,
          onChange: (event) => {
            updateSelection(event);
            previousValueRef.current = event.target.value;
            editEntityRecord("postType", type, id, {
              content: event.target.value,
              blocks: void 0,
              selection: void 0
            });
          },
          onFocus: updateSelection,
          onMouseUp: updateSelection,
          onKeyUp: updateSelection,
          className: "editor-post-text-editor",
          id: `post-content-${instanceId}`,
          placeholder: (0, import_i18n269.__)("Start writing with text or HTML")
        }
      )
    ] });
  }

  // packages/editor/build-module/components/post-title/index.mjs
  var import_i18n270 = __toESM(require_i18n(), 1);
  var import_element271 = __toESM(require_element(), 1);
  var import_html_entities29 = __toESM(require_html_entities(), 1);
  var import_data179 = __toESM(require_data(), 1);
  var import_block_editor59 = __toESM(require_block_editor(), 1);
  var import_keycodes15 = __toESM(require_keycodes(), 1);
  var import_blocks27 = __toESM(require_blocks(), 1);
  var import_rich_text6 = __toESM(require_rich_text(), 1);
  var import_compose57 = __toESM(require_compose(), 1);
  var import_dom24 = __toESM(require_dom(), 1);

  // packages/editor/build-module/components/post-title/constants.mjs
  var DEFAULT_CLASSNAMES = "wp-block wp-block-post-title block-editor-block-list__block editor-post-title editor-post-title__input rich-text";
  var REGEXP_NEWLINES = /[\r\n]+/g;

  // packages/editor/build-module/components/post-title/use-post-title-focus.mjs
  var import_element270 = __toESM(require_element(), 1);
  var import_data177 = __toESM(require_data(), 1);
  function usePostTitleFocus(forwardedRef) {
    const ref = (0, import_element270.useRef)();
    const { isCleanNewPost: isCleanNewPost2 } = (0, import_data177.useSelect)((select9) => {
      const { isCleanNewPost: _isCleanNewPost } = select9(store);
      return {
        isCleanNewPost: _isCleanNewPost()
      };
    }, []);
    (0, import_element270.useImperativeHandle)(forwardedRef, () => ({
      focus: () => {
        ref?.current?.focus();
      }
    }));
    (0, import_element270.useEffect)(() => {
      if (!ref.current) {
        return;
      }
      const { defaultView } = ref.current.ownerDocument;
      const { name: name2, parent } = defaultView;
      const ownerDocument2 = name2 === "editor-canvas" ? parent.document : defaultView.document;
      const { activeElement: activeElement2, body } = ownerDocument2;
      if (isCleanNewPost2 && (!activeElement2 || body === activeElement2)) {
        ref.current.focus();
      }
    }, [isCleanNewPost2]);
    return { ref };
  }

  // packages/editor/build-module/components/post-title/use-post-title.mjs
  var import_data178 = __toESM(require_data(), 1);
  function usePostTitle() {
    const { editPost: editPost2 } = (0, import_data178.useDispatch)(store);
    const { title } = (0, import_data178.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
      return {
        title: getEditedPostAttribute2("title")
      };
    }, []);
    function updateTitle(newTitle) {
      editPost2({ title: newTitle });
    }
    return { title, setTitle: updateTitle };
  }

  // packages/editor/build-module/components/post-title/index.mjs
  var import_jsx_runtime467 = __toESM(require_jsx_runtime(), 1);
  var { useRichText: useRichText2 } = unlock(import_rich_text6.privateApis);
  var PostTitle = (0, import_element271.forwardRef)((_, forwardedRef) => {
    const { placeholder, isEditingContentOnlySection, isPreview } = (0, import_data179.useSelect)(
      (select9) => {
        const { getSettings: getSettings10, getEditedContentOnlySection } = unlock(
          select9(import_block_editor59.store)
        );
        const { titlePlaceholder, isPreviewMode } = getSettings10();
        return {
          placeholder: titlePlaceholder,
          isEditingContentOnlySection: !!getEditedContentOnlySection(),
          isPreview: isPreviewMode
        };
      },
      []
    );
    const [isSelected2, setIsSelected] = (0, import_element271.useState)(false);
    const { ref: focusRef } = usePostTitleFocus(forwardedRef);
    const { title, setTitle: onUpdate } = usePostTitle();
    const [selection, setSelection] = (0, import_element271.useState)({});
    const { clearSelectedBlock: clearSelectedBlock2, insertBlocks: insertBlocks2, insertDefaultBlock: insertDefaultBlock2 } = (0, import_data179.useDispatch)(import_block_editor59.store);
    const decodedPlaceholder = (0, import_html_entities29.decodeEntities)(placeholder) || (0, import_i18n270.__)("Add title");
    const {
      value,
      onChange,
      ref: richTextRef
    } = useRichText2({
      value: title,
      onChange(newValue) {
        onUpdate(newValue.replace(REGEXP_NEWLINES, " "));
      },
      placeholder: decodedPlaceholder,
      selectionStart: selection.start,
      selectionEnd: selection.end,
      onSelectionChange(newStart, newEnd) {
        setSelection((sel) => {
          const { start: start2, end } = sel;
          if (start2 === newStart && end === newEnd) {
            return sel;
          }
          return {
            start: newStart,
            end: newEnd
          };
        });
      },
      __unstableDisableFormats: false
    });
    function onInsertBlockAfter(blocks) {
      insertBlocks2(blocks, 0);
    }
    function onSelect() {
      setIsSelected(true);
      clearSelectedBlock2();
    }
    function onUnselect() {
      setIsSelected(false);
      setSelection({});
    }
    function onEnterPress() {
      insertDefaultBlock2(void 0, void 0, 0);
    }
    function onKeyDown(event) {
      if (event.keyCode === import_keycodes15.ENTER) {
        event.preventDefault();
        onEnterPress();
      }
    }
    function onPaste(event) {
      const clipboardData = event.clipboardData;
      let plainText = "";
      let html = "";
      try {
        plainText = clipboardData.getData("text/plain");
        html = clipboardData.getData("text/html");
      } catch {
        return;
      }
      const content = (0, import_blocks27.pasteHandler)({
        HTML: html,
        plainText
      });
      event.preventDefault();
      if (!content.length) {
        return;
      }
      if (typeof content !== "string") {
        const [firstBlock] = content;
        if (!title && (firstBlock.name === "core/heading" || firstBlock.name === "core/paragraph")) {
          const contentNoHTML = (0, import_dom24.__unstableStripHTML)(
            firstBlock.attributes.content
          );
          onUpdate(contentNoHTML);
          onInsertBlockAfter(content.slice(1));
        } else {
          onInsertBlockAfter(content);
        }
      } else {
        const contentNoHTML = (0, import_dom24.__unstableStripHTML)(content);
        onChange((0, import_rich_text6.insert)(value, (0, import_rich_text6.create)({ html: contentNoHTML })));
      }
    }
    const className = clsx_default(DEFAULT_CLASSNAMES, {
      "is-selected": isSelected2
    });
    const style = isEditingContentOnlySection ? { opacity: 0.2 } : void 0;
    return (
      /* eslint-disable jsx-a11y/no-noninteractive-element-to-interactive-role */
      /* @__PURE__ */ (0, import_jsx_runtime467.jsx)(
        "h1",
        {
          ref: (0, import_compose57.useMergeRefs)([richTextRef, focusRef]),
          contentEditable: !isEditingContentOnlySection && !isPreview,
          className,
          "aria-label": decodedPlaceholder,
          role: "textbox",
          "aria-multiline": "true",
          onFocus: onSelect,
          onBlur: onUnselect,
          onKeyDown,
          onPaste,
          style
        }
      )
    );
  });
  var post_title_default = (0, import_element271.forwardRef)((_, forwardedRef) => /* @__PURE__ */ (0, import_jsx_runtime467.jsx)(post_type_support_check_default, { supportKeys: "title", children: /* @__PURE__ */ (0, import_jsx_runtime467.jsx)(PostTitle, { ref: forwardedRef }) }));

  // packages/editor/build-module/components/post-title/post-title-raw.mjs
  var import_components224 = __toESM(require_components(), 1);
  var import_i18n271 = __toESM(require_i18n(), 1);
  var import_html_entities30 = __toESM(require_html_entities(), 1);
  var import_data180 = __toESM(require_data(), 1);
  var import_block_editor60 = __toESM(require_block_editor(), 1);
  var import_element272 = __toESM(require_element(), 1);
  var import_jsx_runtime468 = __toESM(require_jsx_runtime(), 1);
  function PostTitleRaw(_, forwardedRef) {
    const { placeholder } = (0, import_data180.useSelect)((select9) => {
      const { getSettings: getSettings10 } = select9(import_block_editor60.store);
      const { titlePlaceholder } = getSettings10();
      return {
        placeholder: titlePlaceholder
      };
    }, []);
    const [isSelected2, setIsSelected] = (0, import_element272.useState)(false);
    const { title, setTitle: onUpdate } = usePostTitle();
    const { ref: focusRef } = usePostTitleFocus(forwardedRef);
    function onChange(value) {
      onUpdate(value.replace(REGEXP_NEWLINES, " "));
    }
    function onSelect() {
      setIsSelected(true);
    }
    function onUnselect() {
      setIsSelected(false);
    }
    const className = clsx_default(DEFAULT_CLASSNAMES, {
      "is-selected": isSelected2,
      "is-raw-text": true
    });
    const decodedPlaceholder = (0, import_html_entities30.decodeEntities)(placeholder) || (0, import_i18n271.__)("Add title");
    return /* @__PURE__ */ (0, import_jsx_runtime468.jsx)(
      import_components224.TextareaControl,
      {
        ref: focusRef,
        value: title,
        onChange,
        onFocus: onSelect,
        onBlur: onUnselect,
        label: placeholder,
        className,
        placeholder: decodedPlaceholder,
        hideLabelFromVision: true,
        autoComplete: "off",
        dir: "auto",
        rows: 1
      }
    );
  }
  var post_title_raw_default = (0, import_element272.forwardRef)(PostTitleRaw);

  // packages/editor/build-module/components/post-trash/index.mjs
  var import_i18n272 = __toESM(require_i18n(), 1);
  var import_components225 = __toESM(require_components(), 1);
  var import_data182 = __toESM(require_data(), 1);
  var import_element273 = __toESM(require_element(), 1);

  // packages/editor/build-module/components/post-trash/check.mjs
  var import_data181 = __toESM(require_data(), 1);
  var import_core_data104 = __toESM(require_core_data(), 1);
  function PostTrashCheck({ children }) {
    const { canTrashPost } = (0, import_data181.useSelect)((select9) => {
      const { isEditedPostNew: isEditedPostNew2, getCurrentPostId: getCurrentPostId2, getCurrentPostType: getCurrentPostType2 } = select9(store);
      const { canUser } = select9(import_core_data104.store);
      const postType2 = getCurrentPostType2();
      const postId2 = getCurrentPostId2();
      const isNew = isEditedPostNew2();
      const canUserDelete = !!postId2 ? canUser("delete", {
        kind: "postType",
        name: postType2,
        id: postId2
      }) : false;
      return {
        canTrashPost: (!isNew || postId2) && canUserDelete && !GLOBAL_POST_TYPES.includes(postType2)
      };
    }, []);
    if (!canTrashPost) {
      return null;
    }
    return children;
  }

  // packages/editor/build-module/components/post-trash/index.mjs
  var import_jsx_runtime469 = __toESM(require_jsx_runtime(), 1);
  function PostTrash({ onActionPerformed }) {
    const registry = (0, import_data182.useRegistry)();
    const { isNew, isDeleting, postId: postId2, title } = (0, import_data182.useSelect)((select9) => {
      const store4 = select9(store);
      return {
        isNew: store4.isEditedPostNew(),
        isDeleting: store4.isDeletingPost(),
        postId: store4.getCurrentPostId(),
        title: store4.getCurrentPostAttribute("title")
      };
    }, []);
    const { trashPost: trashPost3 } = (0, import_data182.useDispatch)(store);
    const [showConfirmDialog, setShowConfirmDialog] = (0, import_element273.useState)(false);
    if (isNew || !postId2) {
      return null;
    }
    const handleConfirm = async () => {
      setShowConfirmDialog(false);
      await trashPost3();
      const item = await registry.resolveSelect(store).getCurrentPost();
      onActionPerformed?.("move-to-trash", [item]);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime469.jsxs)(PostTrashCheck, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime469.jsx)(
        import_components225.Button,
        {
          __next40pxDefaultSize: true,
          className: "editor-post-trash",
          isDestructive: true,
          variant: "secondary",
          isBusy: isDeleting,
          "aria-disabled": isDeleting,
          onClick: isDeleting ? void 0 : () => setShowConfirmDialog(true),
          children: (0, import_i18n272.__)("Move to trash")
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime469.jsx)(
        import_components225.__experimentalConfirmDialog,
        {
          isOpen: showConfirmDialog,
          onConfirm: handleConfirm,
          onCancel: () => setShowConfirmDialog(false),
          confirmButtonText: (0, import_i18n272.__)("Move to trash"),
          size: "small",
          children: (0, import_i18n272.sprintf)(
            // translators: %s: The item's title.
            (0, import_i18n272.__)('Are you sure you want to move "%s" to the trash?'),
            title
          )
        }
      )
    ] });
  }

  // packages/editor/build-module/components/post-url/index.mjs
  var import_data183 = __toESM(require_data(), 1);
  var import_url21 = __toESM(require_url(), 1);
  var import_element274 = __toESM(require_element(), 1);
  var import_block_editor61 = __toESM(require_block_editor(), 1);
  var import_i18n273 = __toESM(require_i18n(), 1);
  var import_components226 = __toESM(require_components(), 1);
  var import_notices28 = __toESM(require_notices(), 1);
  var import_core_data105 = __toESM(require_core_data(), 1);
  var import_compose58 = __toESM(require_compose(), 1);
  var import_jsx_runtime470 = __toESM(require_jsx_runtime(), 1);
  function PostURL({ onClose }) {
    const {
      isEditable,
      postSlug,
      postLink,
      permalinkPrefix,
      permalinkSuffix,
      permalink
    } = (0, import_data183.useSelect)((select9) => {
      const post2 = select9(store).getCurrentPost();
      const postTypeSlug = select9(store).getCurrentPostType();
      const postType2 = select9(import_core_data105.store).getPostType(postTypeSlug);
      const permalinkParts = select9(store).getPermalinkParts();
      const hasPublishAction = post2?._links?.["wp:action-publish"] ?? false;
      return {
        isEditable: select9(store).isPermalinkEditable() && hasPublishAction,
        postSlug: (0, import_url21.safeDecodeURIComponent)(
          select9(store).getEditedPostSlug()
        ),
        viewPostLabel: postType2?.labels?.view_item,
        postLink: post2.link,
        permalinkPrefix: permalinkParts?.prefix,
        permalinkSuffix: permalinkParts?.suffix,
        permalink: (0, import_url21.safeDecodeURIComponent)(
          select9(store).getPermalink()
        )
      };
    }, []);
    const { editPost: editPost2 } = (0, import_data183.useDispatch)(store);
    const { createNotice } = (0, import_data183.useDispatch)(import_notices28.store);
    const [forceEmptyField, setForceEmptyField] = (0, import_element274.useState)(false);
    const copyButtonRef = (0, import_compose58.useCopyToClipboard)(permalink, () => {
      createNotice("info", (0, import_i18n273.__)("Copied Permalink to clipboard."), {
        isDismissible: true,
        type: "snackbar"
      });
    });
    const postUrlSlugDescriptionId = "editor-post-url__slug-description-" + (0, import_compose58.useInstanceId)(PostURL);
    return /* @__PURE__ */ (0, import_jsx_runtime470.jsxs)("div", { className: "editor-post-url", children: [
      /* @__PURE__ */ (0, import_jsx_runtime470.jsx)(
        import_block_editor61.__experimentalInspectorPopoverHeader,
        {
          title: (0, import_i18n273.__)("Slug"),
          onClose
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime470.jsxs)(import_components226.__experimentalVStack, { spacing: 3, children: [
        isEditable && /* @__PURE__ */ (0, import_jsx_runtime470.jsx)("p", { className: "editor-post-url__intro", children: (0, import_element274.createInterpolateElement)(
          (0, import_i18n273.__)(
            "<span>Customize the last part of the Permalink.</span> <a>Learn more.</a>"
          ),
          {
            span: /* @__PURE__ */ (0, import_jsx_runtime470.jsx)("span", { id: postUrlSlugDescriptionId }),
            a: /* @__PURE__ */ (0, import_jsx_runtime470.jsx)(
              import_components226.ExternalLink,
              {
                href: (0, import_i18n273.__)(
                  "https://wordpress.org/documentation/article/page-post-settings-sidebar/#permalink"
                )
              }
            )
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime470.jsxs)("div", { children: [
          isEditable && /* @__PURE__ */ (0, import_jsx_runtime470.jsxs)(import_jsx_runtime470.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime470.jsx)(
              import_components226.__experimentalInputControl,
              {
                prefix: /* @__PURE__ */ (0, import_jsx_runtime470.jsx)(import_components226.__experimentalInputControlPrefixWrapper, { children: "/" }),
                suffix: /* @__PURE__ */ (0, import_jsx_runtime470.jsx)(import_components226.__experimentalInputControlSuffixWrapper, { variant: "control", children: /* @__PURE__ */ (0, import_jsx_runtime470.jsx)(
                  import_components226.Button,
                  {
                    icon: copy_small_default,
                    ref: copyButtonRef,
                    size: "small",
                    label: "Copy"
                  }
                ) }),
                label: (0, import_i18n273.__)("Slug"),
                hideLabelFromVision: true,
                value: forceEmptyField ? "" : postSlug,
                autoComplete: "off",
                spellCheck: "false",
                type: "text",
                className: "editor-post-url__input",
                onChange: (newValue) => {
                  editPost2({ slug: newValue });
                  if (!newValue) {
                    if (!forceEmptyField) {
                      setForceEmptyField(true);
                    }
                    return;
                  }
                  if (forceEmptyField) {
                    setForceEmptyField(false);
                  }
                },
                onBlur: (event) => {
                  editPost2({
                    slug: (0, import_url21.cleanForSlug)(
                      event.target.value
                    )
                  });
                  if (forceEmptyField) {
                    setForceEmptyField(false);
                  }
                },
                "aria-describedby": postUrlSlugDescriptionId
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime470.jsxs)("p", { className: "editor-post-url__permalink", children: [
              /* @__PURE__ */ (0, import_jsx_runtime470.jsx)("span", { className: "editor-post-url__permalink-visual-label", children: (0, import_i18n273.__)("Permalink:") }),
              /* @__PURE__ */ (0, import_jsx_runtime470.jsxs)(
                import_components226.ExternalLink,
                {
                  className: "editor-post-url__link",
                  href: postLink,
                  target: "_blank",
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime470.jsx)("span", { className: "editor-post-url__link-prefix", children: permalinkPrefix }),
                    /* @__PURE__ */ (0, import_jsx_runtime470.jsx)("span", { className: "editor-post-url__link-slug", children: postSlug }),
                    /* @__PURE__ */ (0, import_jsx_runtime470.jsx)("span", { className: "editor-post-url__link-suffix", children: permalinkSuffix })
                  ]
                }
              )
            ] })
          ] }),
          !isEditable && /* @__PURE__ */ (0, import_jsx_runtime470.jsx)(
            import_components226.ExternalLink,
            {
              className: "editor-post-url__link",
              href: postLink,
              target: "_blank",
              children: postLink
            }
          )
        ] })
      ] })
    ] });
  }

  // packages/editor/build-module/components/post-url/check.mjs
  var import_data184 = __toESM(require_data(), 1);
  var import_core_data106 = __toESM(require_core_data(), 1);
  function PostURLCheck({ children }) {
    const isVisible2 = (0, import_data184.useSelect)((select9) => {
      const postTypeSlug = select9(store).getCurrentPostType();
      const postType2 = select9(import_core_data106.store).getPostType(postTypeSlug);
      if (!postType2?.viewable) {
        return false;
      }
      const post2 = select9(store).getCurrentPost();
      if (!post2.link) {
        return false;
      }
      const permalinkParts = select9(store).getPermalinkParts();
      if (!permalinkParts) {
        return false;
      }
      return true;
    }, []);
    if (!isVisible2) {
      return null;
    }
    return children;
  }

  // packages/editor/build-module/components/post-url/label.mjs
  var import_data185 = __toESM(require_data(), 1);
  var import_url22 = __toESM(require_url(), 1);
  function PostURLLabel() {
    return usePostURLLabel();
  }
  function usePostURLLabel() {
    const postLink = (0, import_data185.useSelect)(
      (select9) => select9(store).getPermalink(),
      []
    );
    return (0, import_url22.filterURLForDisplay)((0, import_url22.safeDecodeURIComponent)(postLink));
  }

  // packages/editor/build-module/components/post-url/panel.mjs
  var import_element275 = __toESM(require_element(), 1);
  var import_data186 = __toESM(require_data(), 1);
  var import_components227 = __toESM(require_components(), 1);
  var import_i18n274 = __toESM(require_i18n(), 1);
  var import_url23 = __toESM(require_url(), 1);
  var import_core_data107 = __toESM(require_core_data(), 1);
  var import_jsx_runtime471 = __toESM(require_jsx_runtime(), 1);
  function PostURLPanel() {
    const { isFrontPage } = (0, import_data186.useSelect)((select9) => {
      const { getCurrentPostId: getCurrentPostId2 } = select9(store);
      const { getEditedEntityRecord, canUser } = select9(import_core_data107.store);
      const siteSettings = canUser("read", {
        kind: "root",
        name: "site"
      }) ? getEditedEntityRecord("root", "site") : void 0;
      const _id = getCurrentPostId2();
      return {
        isFrontPage: siteSettings?.page_on_front === _id
      };
    }, []);
    const [popoverAnchor, setPopoverAnchor] = (0, import_element275.useState)(null);
    const popoverProps = (0, import_element275.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 label = isFrontPage ? (0, import_i18n274.__)("Link") : (0, import_i18n274.__)("Slug");
    return /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(PostURLCheck, { children: /* @__PURE__ */ (0, import_jsx_runtime471.jsxs)(post_panel_row_default, { label, ref: setPopoverAnchor, children: [
      !isFrontPage && /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
        import_components227.Dropdown,
        {
          popoverProps,
          className: "editor-post-url__panel-dropdown",
          contentClassName: "editor-post-url__panel-dialog",
          focusOnMount: true,
          renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
            PostURLToggle,
            {
              isOpen: isOpen2,
              onClick: onToggle
            }
          ),
          renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(PostURL, { onClose })
        }
      ),
      isFrontPage && /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(FrontPageLink, {})
    ] }) });
  }
  function PostURLToggle({ isOpen: isOpen2, onClick }) {
    const { slug } = (0, import_data186.useSelect)((select9) => {
      return {
        slug: select9(store).getEditedPostSlug()
      };
    }, []);
    const decodedSlug = (0, import_url23.safeDecodeURIComponent)(slug);
    return /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
      import_components227.Button,
      {
        size: "compact",
        className: "editor-post-url__panel-toggle",
        variant: "tertiary",
        "aria-expanded": isOpen2,
        "aria-label": (
          // translators: %s: Current post link.
          (0, import_i18n274.sprintf)((0, import_i18n274.__)("Change link: %s"), decodedSlug)
        ),
        onClick,
        children: /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(import_jsx_runtime471.Fragment, { children: decodedSlug })
      }
    );
  }
  function FrontPageLink() {
    const { postLink } = (0, import_data186.useSelect)((select9) => {
      const { getCurrentPost: getCurrentPost2 } = select9(store);
      return {
        postLink: getCurrentPost2()?.link
      };
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime471.jsx)(
      import_components227.ExternalLink,
      {
        className: "editor-post-url__front-page-link",
        href: postLink,
        target: "_blank",
        children: postLink
      }
    );
  }

  // packages/editor/build-module/components/post-visibility/check.mjs
  var import_data187 = __toESM(require_data(), 1);
  function PostVisibilityCheck({ render: render5 }) {
    const canEdit = (0, import_data187.useSelect)((select9) => {
      return select9(store).getCurrentPost()._links?.["wp:action-publish"] ?? false;
    });
    return render5({ canEdit });
  }

  // packages/editor/build-module/components/table-of-contents/index.mjs
  var import_i18n278 = __toESM(require_i18n(), 1);
  var import_components228 = __toESM(require_components(), 1);
  var import_data192 = __toESM(require_data(), 1);
  var import_element277 = __toESM(require_element(), 1);
  var import_block_editor63 = __toESM(require_block_editor(), 1);

  // packages/editor/build-module/components/table-of-contents/panel.mjs
  var import_i18n277 = __toESM(require_i18n(), 1);
  var import_data191 = __toESM(require_data(), 1);
  var import_block_editor62 = __toESM(require_block_editor(), 1);

  // packages/editor/build-module/components/word-count/index.mjs
  var import_data188 = __toESM(require_data(), 1);
  var import_i18n275 = __toESM(require_i18n(), 1);
  var import_wordcount2 = __toESM(require_wordcount(), 1);
  var import_jsx_runtime472 = __toESM(require_jsx_runtime(), 1);
  function WordCount() {
    const content = (0, import_data188.useSelect)(
      (select9) => select9(store).getEditedPostAttribute("content"),
      []
    );
    const wordCountType = (0, import_i18n275._x)("words", "Word count type. Do not translate!");
    return /* @__PURE__ */ (0, import_jsx_runtime472.jsx)("span", { className: "word-count", children: (0, import_wordcount2.count)(content, wordCountType) });
  }

  // packages/editor/build-module/components/time-to-read/index.mjs
  var import_data189 = __toESM(require_data(), 1);
  var import_i18n276 = __toESM(require_i18n(), 1);
  var import_wordcount3 = __toESM(require_wordcount(), 1);
  var import_element276 = __toESM(require_element(), 1);
  var import_jsx_runtime473 = __toESM(require_jsx_runtime(), 1);
  var AVERAGE_READING_RATE2 = 189;
  function TimeToRead() {
    const content = (0, import_data189.useSelect)(
      (select9) => select9(store).getEditedPostAttribute("content"),
      []
    );
    const wordCountType = (0, import_i18n276._x)("words", "Word count type. Do not translate!");
    const minutesToRead = Math.round(
      (0, import_wordcount3.count)(content, wordCountType) / AVERAGE_READING_RATE2
    );
    const minutesToReadString = minutesToRead === 0 ? (0, import_element276.createInterpolateElement)((0, import_i18n276.__)("<span>< 1</span> minute"), {
      span: /* @__PURE__ */ (0, import_jsx_runtime473.jsx)("span", {})
    }) : (0, import_element276.createInterpolateElement)(
      (0, import_i18n276.sprintf)(
        /* translators: %s: the number of minutes to read the post. */
        (0, import_i18n276._n)(
          "<span>%s</span> minute",
          "<span>%s</span> minutes",
          minutesToRead
        ),
        minutesToRead
      ),
      {
        span: /* @__PURE__ */ (0, import_jsx_runtime473.jsx)("span", {})
      }
    );
    return /* @__PURE__ */ (0, import_jsx_runtime473.jsx)("span", { className: "time-to-read", children: minutesToReadString });
  }

  // packages/editor/build-module/components/character-count/index.mjs
  var import_data190 = __toESM(require_data(), 1);
  var import_wordcount4 = __toESM(require_wordcount(), 1);
  function CharacterCount() {
    const content = (0, import_data190.useSelect)(
      (select9) => select9(store).getEditedPostAttribute("content"),
      []
    );
    return (0, import_wordcount4.count)(content, "characters_including_spaces");
  }

  // packages/editor/build-module/components/table-of-contents/panel.mjs
  var import_jsx_runtime474 = __toESM(require_jsx_runtime(), 1);
  function TableOfContentsPanel({ hasOutlineItemsDisabled, onRequestClose }) {
    const { headingCount, paragraphCount, numberOfBlocks } = (0, import_data191.useSelect)(
      (select9) => {
        const { getGlobalBlockCount: getGlobalBlockCount2 } = select9(import_block_editor62.store);
        return {
          headingCount: getGlobalBlockCount2("core/heading"),
          paragraphCount: getGlobalBlockCount2("core/paragraph"),
          numberOfBlocks: getGlobalBlockCount2()
        };
      },
      []
    );
    return (
      /*
       * Disable reason: The `list` ARIA role is redundant but
       * Safari+VoiceOver won't announce the list otherwise.
       */
      /* eslint-disable jsx-a11y/no-redundant-roles */
      /* @__PURE__ */ (0, import_jsx_runtime474.jsxs)(import_jsx_runtime474.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime474.jsx)(
          "div",
          {
            className: "table-of-contents__wrapper",
            role: "note",
            "aria-label": (0, import_i18n277.__)("Document Statistics"),
            tabIndex: "0",
            children: /* @__PURE__ */ (0, import_jsx_runtime474.jsxs)("ul", { role: "list", className: "table-of-contents__counts", children: [
              /* @__PURE__ */ (0, import_jsx_runtime474.jsxs)("li", { className: "table-of-contents__count", children: [
                (0, import_i18n277.__)("Words"),
                /* @__PURE__ */ (0, import_jsx_runtime474.jsx)(WordCount, {})
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime474.jsxs)("li", { className: "table-of-contents__count", children: [
                (0, import_i18n277.__)("Characters"),
                /* @__PURE__ */ (0, import_jsx_runtime474.jsx)("span", { className: "table-of-contents__number", children: /* @__PURE__ */ (0, import_jsx_runtime474.jsx)(CharacterCount, {}) })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime474.jsxs)("li", { className: "table-of-contents__count", children: [
                (0, import_i18n277.__)("Time to read"),
                /* @__PURE__ */ (0, import_jsx_runtime474.jsx)(TimeToRead, {})
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime474.jsxs)("li", { className: "table-of-contents__count", children: [
                (0, import_i18n277.__)("Headings"),
                /* @__PURE__ */ (0, import_jsx_runtime474.jsx)("span", { className: "table-of-contents__number", children: headingCount })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime474.jsxs)("li", { className: "table-of-contents__count", children: [
                (0, import_i18n277.__)("Paragraphs"),
                /* @__PURE__ */ (0, import_jsx_runtime474.jsx)("span", { className: "table-of-contents__number", children: paragraphCount })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime474.jsxs)("li", { className: "table-of-contents__count", children: [
                (0, import_i18n277.__)("Blocks"),
                /* @__PURE__ */ (0, import_jsx_runtime474.jsx)("span", { className: "table-of-contents__number", children: numberOfBlocks })
              ] })
            ] })
          }
        ),
        headingCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime474.jsxs)(import_jsx_runtime474.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime474.jsx)("hr", {}),
          /* @__PURE__ */ (0, import_jsx_runtime474.jsx)("h2", { className: "table-of-contents__title", children: (0, import_i18n277.__)("Document Outline") }),
          /* @__PURE__ */ (0, import_jsx_runtime474.jsx)(
            DocumentOutline,
            {
              onSelect: onRequestClose,
              hasOutlineItemsDisabled
            }
          )
        ] })
      ] })
    );
  }
  var panel_default3 = TableOfContentsPanel;

  // packages/editor/build-module/components/table-of-contents/index.mjs
  var import_jsx_runtime475 = __toESM(require_jsx_runtime(), 1);
  function TableOfContents({ hasOutlineItemsDisabled, repositionDropdown, ...props }, ref) {
    const hasBlocks = (0, import_data192.useSelect)(
      (select9) => !!select9(import_block_editor63.store).getBlockCount(),
      []
    );
    return /* @__PURE__ */ (0, import_jsx_runtime475.jsx)(
      import_components228.Dropdown,
      {
        popoverProps: {
          placement: repositionDropdown ? "right" : "bottom"
        },
        className: "table-of-contents",
        contentClassName: "table-of-contents__popover",
        renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime475.jsx)(
          import_components228.Button,
          {
            __next40pxDefaultSize: true,
            ...props,
            ref,
            onClick: hasBlocks ? onToggle : void 0,
            icon: info_default,
            "aria-expanded": isOpen2,
            "aria-haspopup": "true",
            label: (0, import_i18n278.__)("Details"),
            tooltipPosition: "bottom",
            "aria-disabled": !hasBlocks
          }
        ),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime475.jsx)(
          panel_default3,
          {
            onRequestClose: onClose,
            hasOutlineItemsDisabled
          }
        )
      }
    );
  }
  var table_of_contents_default = (0, import_element277.forwardRef)(TableOfContents);

  // packages/editor/build-module/components/unsaved-changes-warning/index.mjs
  var import_i18n279 = __toESM(require_i18n(), 1);
  var import_element278 = __toESM(require_element(), 1);
  var import_data193 = __toESM(require_data(), 1);
  var import_core_data108 = __toESM(require_core_data(), 1);
  function UnsavedChangesWarning() {
    const { __experimentalGetDirtyEntityRecords } = (0, import_data193.useSelect)(import_core_data108.store);
    (0, import_element278.useEffect)(() => {
      const warnIfUnsavedChanges = (event) => {
        const dirtyEntityRecords = __experimentalGetDirtyEntityRecords();
        if (dirtyEntityRecords.length > 0) {
          event.returnValue = (0, import_i18n279.__)(
            "You have unsaved changes. If you proceed, they will be lost."
          );
          return event.returnValue;
        }
      };
      window.addEventListener("beforeunload", warnIfUnsavedChanges);
      return () => {
        window.removeEventListener("beforeunload", warnIfUnsavedChanges);
      };
    }, [__experimentalGetDirtyEntityRecords]);
    return null;
  }

  // packages/editor/build-module/components/deprecated.mjs
  var import_deprecated13 = __toESM(require_deprecated(), 1);
  var import_element279 = __toESM(require_element(), 1);
  var import_block_editor64 = __toESM(require_block_editor(), 1);
  var import_server_side_render = __toESM(require_server_side_render(), 1);
  var import_jsx_runtime476 = __toESM(require_jsx_runtime(), 1);
  function deprecateComponent(name2, Wrapped, staticsToHoist = []) {
    const Component3 = (0, import_element279.forwardRef)((props, ref) => {
      (0, import_deprecated13.default)("wp.editor." + name2, {
        since: "5.3",
        alternative: "wp.blockEditor." + name2,
        version: "6.2"
      });
      return /* @__PURE__ */ (0, import_jsx_runtime476.jsx)(Wrapped, { ref, ...props });
    });
    staticsToHoist.forEach((staticName) => {
      Component3[staticName] = deprecateComponent(
        name2 + "." + staticName,
        Wrapped[staticName]
      );
    });
    return Component3;
  }
  function deprecateFunction(name2, func) {
    return (...args) => {
      (0, import_deprecated13.default)("wp.editor." + name2, {
        since: "5.3",
        alternative: "wp.blockEditor." + name2,
        version: "6.2"
      });
      return func(...args);
    };
  }
  var RichText2 = deprecateComponent("RichText", import_block_editor64.RichText, ["Content"]);
  RichText2.isEmpty = deprecateFunction(
    "RichText.isEmpty",
    import_block_editor64.RichText.isEmpty
  );
  var Autocomplete = deprecateComponent(
    "Autocomplete",
    import_block_editor64.Autocomplete
  );
  var AlignmentToolbar = deprecateComponent(
    "AlignmentToolbar",
    import_block_editor64.AlignmentToolbar
  );
  var BlockAlignmentToolbar = deprecateComponent(
    "BlockAlignmentToolbar",
    import_block_editor64.BlockAlignmentToolbar
  );
  var BlockControls = deprecateComponent(
    "BlockControls",
    import_block_editor64.BlockControls,
    ["Slot"]
  );
  var BlockEdit = deprecateComponent("BlockEdit", import_block_editor64.BlockEdit);
  var BlockEditorKeyboardShortcuts2 = deprecateComponent(
    "BlockEditorKeyboardShortcuts",
    import_block_editor64.BlockEditorKeyboardShortcuts
  );
  var BlockFormatControls = deprecateComponent(
    "BlockFormatControls",
    import_block_editor64.BlockFormatControls,
    ["Slot"]
  );
  var BlockIcon3 = deprecateComponent("BlockIcon", import_block_editor64.BlockIcon);
  var BlockInspector = deprecateComponent(
    "BlockInspector",
    import_block_editor64.BlockInspector
  );
  var BlockList4 = deprecateComponent("BlockList", import_block_editor64.BlockList);
  var BlockMover = deprecateComponent("BlockMover", import_block_editor64.BlockMover);
  var BlockNavigationDropdown = deprecateComponent(
    "BlockNavigationDropdown",
    import_block_editor64.BlockNavigationDropdown
  );
  var BlockSelectionClearer = deprecateComponent(
    "BlockSelectionClearer",
    import_block_editor64.BlockSelectionClearer
  );
  var BlockSettingsMenu = deprecateComponent(
    "BlockSettingsMenu",
    import_block_editor64.BlockSettingsMenu
  );
  var BlockTitle = deprecateComponent("BlockTitle", import_block_editor64.BlockTitle);
  var BlockToolbar = deprecateComponent(
    "BlockToolbar",
    import_block_editor64.BlockToolbar
  );
  var ColorPalette2 = deprecateComponent(
    "ColorPalette",
    import_block_editor64.ColorPalette
  );
  var ContrastChecker = deprecateComponent(
    "ContrastChecker",
    import_block_editor64.ContrastChecker
  );
  var CopyHandler = deprecateComponent("CopyHandler", import_block_editor64.CopyHandler);
  var DefaultBlockAppender = deprecateComponent(
    "DefaultBlockAppender",
    import_block_editor64.DefaultBlockAppender
  );
  var FontSizePicker = deprecateComponent(
    "FontSizePicker",
    import_block_editor64.FontSizePicker
  );
  var Inserter = deprecateComponent("Inserter", import_block_editor64.Inserter);
  var InnerBlocks = deprecateComponent("InnerBlocks", import_block_editor64.InnerBlocks, [
    "ButtonBlockAppender",
    "DefaultBlockAppender",
    "Content"
  ]);
  var InspectorAdvancedControls = deprecateComponent(
    "InspectorAdvancedControls",
    import_block_editor64.InspectorAdvancedControls,
    ["Slot"]
  );
  var InspectorControls = deprecateComponent(
    "InspectorControls",
    import_block_editor64.InspectorControls,
    ["Slot"]
  );
  var PanelColorSettings = deprecateComponent(
    "PanelColorSettings",
    import_block_editor64.PanelColorSettings
  );
  var PlainText = deprecateComponent("PlainText", import_block_editor64.PlainText);
  var RichTextShortcut = deprecateComponent(
    "RichTextShortcut",
    import_block_editor64.RichTextShortcut
  );
  var RichTextToolbarButton = deprecateComponent(
    "RichTextToolbarButton",
    import_block_editor64.RichTextToolbarButton
  );
  var __unstableRichTextInputEvent = deprecateComponent(
    "__unstableRichTextInputEvent",
    import_block_editor64.__unstableRichTextInputEvent
  );
  var MediaPlaceholder = deprecateComponent(
    "MediaPlaceholder",
    import_block_editor64.MediaPlaceholder
  );
  var MediaUpload3 = deprecateComponent("MediaUpload", import_block_editor64.MediaUpload);
  var MediaUploadCheck2 = deprecateComponent(
    "MediaUploadCheck",
    import_block_editor64.MediaUploadCheck
  );
  var MultiSelectScrollIntoView = deprecateComponent(
    "MultiSelectScrollIntoView",
    import_block_editor64.MultiSelectScrollIntoView
  );
  var NavigableToolbar = deprecateComponent(
    "NavigableToolbar",
    import_block_editor64.NavigableToolbar
  );
  var ObserveTyping = deprecateComponent(
    "ObserveTyping",
    import_block_editor64.ObserveTyping
  );
  var SkipToSelectedBlock = deprecateComponent(
    "SkipToSelectedBlock",
    import_block_editor64.SkipToSelectedBlock
  );
  var URLInput = deprecateComponent("URLInput", import_block_editor64.URLInput);
  var URLInputButton = deprecateComponent(
    "URLInputButton",
    import_block_editor64.URLInputButton
  );
  var URLPopover = deprecateComponent("URLPopover", import_block_editor64.URLPopover);
  var Warning = deprecateComponent("Warning", import_block_editor64.Warning);
  var WritingFlow = deprecateComponent("WritingFlow", import_block_editor64.WritingFlow);
  var createCustomColorsHOC = deprecateFunction(
    "createCustomColorsHOC",
    import_block_editor64.createCustomColorsHOC
  );
  var getColorClassName2 = deprecateFunction(
    "getColorClassName",
    import_block_editor64.getColorClassName
  );
  var getColorObjectByAttributeValues = deprecateFunction(
    "getColorObjectByAttributeValues",
    import_block_editor64.getColorObjectByAttributeValues
  );
  var getColorObjectByColorValue = deprecateFunction(
    "getColorObjectByColorValue",
    import_block_editor64.getColorObjectByColorValue
  );
  var getFontSize = deprecateFunction("getFontSize", import_block_editor64.getFontSize);
  var getFontSizeClass = deprecateFunction(
    "getFontSizeClass",
    import_block_editor64.getFontSizeClass
  );
  var withColorContext = deprecateFunction(
    "withColorContext",
    import_block_editor64.withColorContext
  );
  var withColors = deprecateFunction("withColors", import_block_editor64.withColors);
  var withFontSizes = deprecateFunction(
    "withFontSizes",
    import_block_editor64.withFontSizes
  );

  // packages/editor/build-module/components/index.mjs
  var VisualEditorGlobalKeyboardShortcuts = EditorKeyboardShortcuts;
  var TextEditorGlobalKeyboardShortcuts = EditorKeyboardShortcuts;

  // packages/editor/build-module/hooks/default-autocompleters.mjs
  function setDefaultCompleters(completers = []) {
    completers.push({ ...link_default2 }, { ...user_default });
    return completers;
  }
  (0, import_hooks52.addFilter)(
    "editor.Autocomplete.completers",
    "editor/autocompleters/set-default-completers",
    setDefaultCompleters
  );

  // packages/editor/build-module/hooks/media-upload.mjs
  var import_element280 = __toESM(require_element(), 1);
  var import_hooks53 = __toESM(require_hooks(), 1);
  var import_deprecated14 = __toESM(require_deprecated(), 1);
  var import_media_utils8 = __toESM(require_media_utils(), 1);
  var import_jsx_runtime477 = __toESM(require_jsx_runtime(), 1);
  var { MediaUploadModal: MediaUploadModalComponent } = unlock(
    import_media_utils8.privateApis
  );
  var MediaUploadModalWrapper = class extends import_element280.Component {
    constructor(props) {
      super(props);
      this.state = {
        isOpen: false
      };
      this.openModal = this.openModal.bind(this);
      this.closeModal = this.closeModal.bind(this);
    }
    openModal() {
      this.setState({ isOpen: true });
    }
    closeModal() {
      this.setState({ isOpen: false });
      this.props.onClose?.();
    }
    render() {
      const {
        allowedTypes,
        multiple,
        value,
        onSelect,
        title,
        modalClass,
        render: render5
      } = this.props;
      const { isOpen: isOpen2 } = this.state;
      return /* @__PURE__ */ (0, import_jsx_runtime477.jsxs)(import_jsx_runtime477.Fragment, { children: [
        render5({ open: this.openModal }),
        /* @__PURE__ */ (0, import_jsx_runtime477.jsx)(
          MediaUploadModalComponent,
          {
            allowedTypes,
            multiple,
            value,
            onSelect: (media) => {
              onSelect(media);
              this.closeModal();
            },
            onClose: this.closeModal,
            title,
            isOpen: isOpen2,
            modalClass
          }
        )
      ] });
    }
  };
  if (window.__experimentalDataViewsMediaModal) {
    (0, import_hooks53.addFilter)(
      "editor.MediaUpload",
      "core/editor/components/media-upload",
      () => {
        (0, import_deprecated14.default)("Extending MediaUpload as a class component", {
          since: "7.0",
          version: "7.2",
          hint: "MediaUpload will become a function component in WordPress 7.2 Please update any custom implementations to use function components instead."
        });
        return MediaUploadModalWrapper;
      }
    );
  } else {
    (0, import_hooks53.addFilter)(
      "editor.MediaUpload",
      "core/editor/components/media-upload",
      () => {
        return import_media_utils8.MediaUpload;
      }
    );
  }

  // packages/editor/build-module/hooks/pattern-overrides.mjs
  var import_hooks54 = __toESM(require_hooks(), 1);
  var import_patterns9 = __toESM(require_patterns(), 1);
  var import_compose59 = __toESM(require_compose(), 1);
  var import_block_editor65 = __toESM(require_block_editor(), 1);
  var import_data194 = __toESM(require_data(), 1);
  var import_blocks28 = __toESM(require_blocks(), 1);
  var import_jsx_runtime478 = __toESM(require_jsx_runtime(), 1);
  var {
    PatternOverridesControls,
    ResetOverridesControl,
    PATTERN_TYPES: PATTERN_TYPES5,
    PATTERN_SYNC_TYPES: PATTERN_SYNC_TYPES2
  } = unlock(import_patterns9.privateApis);
  var withPatternOverrideControls = (0, import_compose59.createHigherOrderComponent)(
    (BlockEdit2) => (props) => {
      const isSupportedBlock = (0, import_data194.useSelect)(
        (select9) => {
          const { __experimentalBlockBindingsSupportedAttributes } = select9(import_block_editor65.store).getSettings();
          return !!__experimentalBlockBindingsSupportedAttributes?.[props.name];
        },
        [props.name]
      );
      return /* @__PURE__ */ (0, import_jsx_runtime478.jsxs)(import_jsx_runtime478.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime478.jsx)(BlockEdit2, { ...props }, "edit"),
        props.isSelected && isSupportedBlock && /* @__PURE__ */ (0, import_jsx_runtime478.jsx)(ControlsWithStoreSubscription, { ...props })
      ] });
    },
    "withPatternOverrideControls"
  );
  function ControlsWithStoreSubscription(props) {
    const blockEditingMode = (0, import_block_editor65.useBlockEditingMode)();
    const { hasPatternOverridesSource, isEditingSyncedPattern } = (0, import_data194.useSelect)(
      (select9) => {
        const { getCurrentPostType: getCurrentPostType2, getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
        return {
          // For editing link to the site editor if the theme and user permissions support it.
          hasPatternOverridesSource: !!(0, import_blocks28.getBlockBindingsSource)(
            "core/pattern-overrides"
          ),
          isEditingSyncedPattern: getCurrentPostType2() === PATTERN_TYPES5.user && getEditedPostAttribute2("meta")?.wp_pattern_sync_status !== PATTERN_SYNC_TYPES2.unsynced && getEditedPostAttribute2("wp_pattern_sync_status") !== PATTERN_SYNC_TYPES2.unsynced
        };
      },
      []
    );
    const bindings = props.attributes.metadata?.bindings;
    const hasPatternBindings = !!bindings && Object.values(bindings).some(
      (binding) => binding.source === "core/pattern-overrides"
    );
    const shouldShowPatternOverridesControls = isEditingSyncedPattern && blockEditingMode === "default";
    const shouldShowResetOverridesControl = !isEditingSyncedPattern && !!props.attributes.metadata?.name && blockEditingMode !== "disabled" && hasPatternBindings;
    if (!hasPatternOverridesSource) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime478.jsxs)(import_jsx_runtime478.Fragment, { children: [
      shouldShowPatternOverridesControls && /* @__PURE__ */ (0, import_jsx_runtime478.jsx)(PatternOverridesControls, { ...props }),
      shouldShowResetOverridesControl && /* @__PURE__ */ (0, import_jsx_runtime478.jsx)(ResetOverridesControl, { ...props })
    ] });
  }
  (0, import_hooks54.addFilter)(
    "editor.BlockEdit",
    "core/editor/with-pattern-override-controls",
    withPatternOverrideControls
  );

  // packages/editor/build-module/hooks/navigation-link-view-button.mjs
  var import_hooks55 = __toESM(require_hooks(), 1);
  var import_compose60 = __toESM(require_compose(), 1);
  var import_element281 = __toESM(require_element(), 1);
  var import_i18n280 = __toESM(require_i18n(), 1);
  var import_block_editor66 = __toESM(require_block_editor(), 1);
  var import_components230 = __toESM(require_components(), 1);
  var import_data195 = __toESM(require_data(), 1);
  var import_jsx_runtime479 = __toESM(require_jsx_runtime(), 1);
  var SUPPORTED_BLOCKS = ["core/navigation-link", "core/navigation-submenu"];
  function NavigationViewButton({ attributes }) {
    const { kind, id, type } = attributes;
    const blockEditingMode = (0, import_block_editor66.useBlockEditingMode)();
    const onNavigateToEntityRecord = (0, import_data195.useSelect)(
      (select9) => select9(import_block_editor66.store).getSettings().onNavigateToEntityRecord,
      []
    );
    const onViewPage = (0, import_element281.useCallback)(() => {
      if (kind === "post-type" && type === "page" && id && onNavigateToEntityRecord) {
        onNavigateToEntityRecord({
          postId: id,
          postType: type
        });
      }
    }, [kind, id, type, onNavigateToEntityRecord]);
    if (kind !== "post-type" || type !== "page" || !id || !onNavigateToEntityRecord || blockEditingMode !== "contentOnly") {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime479.jsx)(import_block_editor66.__unstableBlockToolbarLastItem, { children: /* @__PURE__ */ (0, import_jsx_runtime479.jsx)(import_components230.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime479.jsx)(
      import_components230.ToolbarButton,
      {
        name: "view",
        title: (0, import_i18n280.__)("View"),
        onClick: onViewPage,
        children: (0, import_i18n280.__)("View")
      }
    ) }) });
  }
  var withNavigationViewButton = (0, import_compose60.createHigherOrderComponent)(
    (BlockEdit2) => (props) => {
      const isSupportedBlock = SUPPORTED_BLOCKS.includes(props.name);
      return /* @__PURE__ */ (0, import_jsx_runtime479.jsxs)(import_jsx_runtime479.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime479.jsx)(BlockEdit2, { ...props }, "edit"),
        props.isSelected && isSupportedBlock && /* @__PURE__ */ (0, import_jsx_runtime479.jsx)(NavigationViewButton, { ...props })
      ] });
    },
    "withNavigationViewButton"
  );
  (0, import_hooks55.addFilter)(
    "editor.BlockEdit",
    "core/editor/with-navigation-view-button",
    withNavigationViewButton
  );

  // packages/editor/build-module/hooks/template-part-navigation-edit-button.mjs
  var import_hooks56 = __toESM(require_hooks(), 1);
  var import_compose61 = __toESM(require_compose(), 1);
  var import_element282 = __toESM(require_element(), 1);
  var import_i18n281 = __toESM(require_i18n(), 1);
  var import_block_editor67 = __toESM(require_block_editor(), 1);
  var import_components231 = __toESM(require_components(), 1);
  var import_data196 = __toESM(require_data(), 1);
  var import_jsx_runtime480 = __toESM(require_jsx_runtime(), 1);
  var NAVIGATION_BLOCK_NAME = "core/navigation";
  var TEMPLATE_PART_BLOCK_NAME = "core/template-part";
  var BLOCK_INSPECTOR_AREA = "edit-post/block";
  function TemplatePartNavigationEditButton({ clientId }) {
    const registry = (0, import_data196.useRegistry)();
    const { selectBlock: selectBlock2, flashBlock } = (0, import_data196.useDispatch)(import_block_editor67.store);
    const { requestInspectorTab } = unlock((0, import_data196.useDispatch)(import_block_editor67.store));
    const { enableComplementaryArea: enableComplementaryArea2 } = (0, import_data196.useDispatch)(store3);
    const {
      hasNavigationBlocks,
      firstNavigationBlockId,
      isNavigationEditable
    } = (0, import_data196.useSelect)(
      (select9) => {
        const {
          getClientIdsOfDescendants: getClientIdsOfDescendants2,
          getBlockName: getBlockName2,
          getBlockEditingMode
        } = select9(import_block_editor67.store);
        const descendants = getClientIdsOfDescendants2(clientId);
        const navigationBlocksInTemplatePart = descendants.filter(
          (blockId) => getBlockName2(blockId) === NAVIGATION_BLOCK_NAME
        );
        const _hasNavigationBlocks = navigationBlocksInTemplatePart.length > 0;
        const _firstNavigationBlockId = _hasNavigationBlocks ? navigationBlocksInTemplatePart[0] : null;
        return {
          hasNavigationBlocks: _hasNavigationBlocks,
          firstNavigationBlockId: _firstNavigationBlockId,
          // We can't use the useBlockEditingMode hook here because the current
          // context is the template part, not the navigation block.
          isNavigationEditable: getBlockEditingMode(_firstNavigationBlockId) !== "disabled"
        };
      },
      [clientId]
    );
    const onEditNavigation = (0, import_element282.useCallback)(() => {
      if (firstNavigationBlockId) {
        registry.batch(() => {
          selectBlock2(firstNavigationBlockId);
          flashBlock(firstNavigationBlockId, 500);
          enableComplementaryArea2("core", BLOCK_INSPECTOR_AREA);
          requestInspectorTab("list", {
            openPanel: firstNavigationBlockId
          });
        });
      }
    }, [
      firstNavigationBlockId,
      registry,
      selectBlock2,
      flashBlock,
      enableComplementaryArea2,
      requestInspectorTab
    ]);
    if (!hasNavigationBlocks || !isNavigationEditable) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime480.jsx)(import_block_editor67.__unstableBlockToolbarLastItem, { children: /* @__PURE__ */ (0, import_jsx_runtime480.jsx)(import_components231.ToolbarGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime480.jsx)(
      import_components231.ToolbarButton,
      {
        label: (0, import_i18n281.__)("Edit navigation"),
        onClick: onEditNavigation,
        children: (0, import_i18n281.__)("Edit navigation")
      }
    ) }) });
  }
  var withTemplatePartNavigationEditButton = (0, import_compose61.createHigherOrderComponent)(
    (BlockEdit2) => (props) => {
      const isTemplatePart2 = props.name === TEMPLATE_PART_BLOCK_NAME;
      return /* @__PURE__ */ (0, import_jsx_runtime480.jsxs)(import_jsx_runtime480.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime480.jsx)(BlockEdit2, { ...props }, "edit"),
        props.isSelected && isTemplatePart2 && /* @__PURE__ */ (0, import_jsx_runtime480.jsx)(
          TemplatePartNavigationEditButton,
          {
            clientId: props.clientId
          }
        )
      ] });
    },
    "withTemplatePartNavigationEditButton"
  );
  (0, import_hooks56.addFilter)(
    "editor.BlockEdit",
    "core/editor/with-template-part-navigation-edit-button",
    withTemplatePartNavigationEditButton
  );

  // packages/editor/build-module/hooks/push-changes-to-global-styles/index.mjs
  var import_hooks58 = __toESM(require_hooks(), 1);
  var import_compose62 = __toESM(require_compose(), 1);
  var import_block_editor68 = __toESM(require_block_editor(), 1);
  var import_components233 = __toESM(require_components(), 1);
  var import_i18n284 = __toESM(require_i18n(), 1);
  var import_blocks30 = __toESM(require_blocks(), 1);
  var import_element285 = __toESM(require_element(), 1);
  var import_data197 = __toESM(require_data(), 1);
  var import_notices29 = __toESM(require_notices(), 1);
  var import_core_data109 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/utils/set-nested-value.mjs
  function setNestedValue(object, path, value) {
    if (!object || typeof object !== "object") {
      return object;
    }
    path.reduce((acc, key, idx) => {
      if (acc[key] === void 0) {
        if (Number.isInteger(path[idx + 1])) {
          acc[key] = [];
        } else {
          acc[key] = {};
        }
      }
      if (idx === path.length - 1) {
        acc[key] = value;
      }
      return acc[key];
    }, object);
    return object;
  }

  // packages/editor/build-module/hooks/push-changes-to-global-styles/apply-globally-modal.mjs
  var import_components232 = __toESM(require_components(), 1);
  var import_i18n283 = __toESM(require_i18n(), 1);
  var import_blocks29 = __toESM(require_blocks(), 1);
  var import_element284 = __toESM(require_element(), 1);

  // packages/editor/build-module/hooks/push-changes-to-global-styles/use-review-rows.mjs
  var import_element283 = __toESM(require_element(), 1);

  // packages/editor/build-module/hooks/push-changes-to-global-styles/style-labels.mjs
  var import_i18n282 = __toESM(require_i18n(), 1);
  var STYLE_LABELS = {
    // Typography.
    "typography.fontFamily": (0, import_i18n282.__)("Font family"),
    "typography.fontSize": (0, import_i18n282.__)("Font size"),
    "typography.fontStyle": (0, import_i18n282.__)("Font style"),
    "typography.fontWeight": (0, import_i18n282.__)("Font weight"),
    "typography.lineHeight": (0, import_i18n282.__)("Line height"),
    "typography.letterSpacing": (0, import_i18n282.__)("Letter spacing"),
    "typography.textDecoration": (0, import_i18n282.__)("Text decoration"),
    "typography.textTransform": (0, import_i18n282.__)("Letter case"),
    "typography.textColumns": (0, import_i18n282.__)("Text columns"),
    "typography.writingMode": (0, import_i18n282.__)("Orientation"),
    // Color.
    "color.text": (0, import_i18n282.__)("Text color"),
    "color.background": (0, import_i18n282.__)("Background color"),
    "color.gradient": (0, import_i18n282.__)("Gradient"),
    "elements.link.color.text": (0, import_i18n282.__)("Link color"),
    // Spacing.
    "spacing.padding": (0, import_i18n282.__)("Padding"),
    "spacing.margin": (0, import_i18n282.__)("Margin"),
    "spacing.blockGap": (0, import_i18n282.__)("Block spacing"),
    // Border.
    border: (0, import_i18n282.__)("Border"),
    "border.top": (0, import_i18n282.__)("Border top"),
    "border.right": (0, import_i18n282.__)("Border right"),
    "border.bottom": (0, import_i18n282.__)("Border bottom"),
    "border.left": (0, import_i18n282.__)("Border left"),
    "border.color": (0, import_i18n282.__)("Border color"),
    "border.width": (0, import_i18n282.__)("Border width"),
    "border.style": (0, import_i18n282.__)("Border style"),
    "border.radius": (0, import_i18n282.__)("Border radius"),
    // Dimensions.
    "dimensions.minHeight": (0, import_i18n282.__)("Minimum height"),
    "dimensions.aspectRatio": (0, import_i18n282.__)("Aspect ratio")
  };
  function getStyleLabel(path) {
    const key = path.join(".");
    if (STYLE_LABELS[key]) {
      return STYLE_LABELS[key];
    }
    return capitalCase(path[path.length - 1] ?? "");
  }

  // packages/editor/build-module/hooks/push-changes-to-global-styles/format-style-value.mjs
  var EMPTY_VALUE_LABEL = "\u2014";
  var PRESET_USER_PREFIX = "var:preset|";
  var PRESET_CSS_VAR_REGEX = /^var\(\s*--wp--preset--[a-z0-9-]+?\s*(?:,[^)]*)?\)$/i;
  function getPresetSlug(value) {
    if (value.startsWith(PRESET_USER_PREFIX)) {
      return value.split("|").pop();
    }
    if (PRESET_CSS_VAR_REGEX.test(value)) {
      return value.replace(/^var\(\s*/, "").replace(/\s*(?:,[^)]*)?\)$/, "").split("--").pop();
    }
    return void 0;
  }
  var isSet = (value) => value !== void 0 && value !== null && value !== "";
  var BORDER_SIDES = ["top", "right", "bottom", "left"];
  function flattenBorder(border) {
    if (isSet(border.width) || isSet(border.style) || isSet(border.color)) {
      return border;
    }
    const setSides = BORDER_SIDES.filter((side) => border[side]);
    if (!setSides.length) {
      return border;
    }
    const collapse = (property) => {
      const values = setSides.map((side) => border[side]?.[property]);
      return values.every((value) => value === values[0]) ? values[0] : void 0;
    };
    return {
      width: collapse("width"),
      style: collapse("style"),
      color: collapse("color")
    };
  }
  function formatStyleValue(value) {
    if (!isSet(value)) {
      return EMPTY_VALUE_LABEL;
    }
    if (typeof value === "string") {
      const presetSlug = getPresetSlug(value);
      if (presetSlug) {
        return capitalCase(presetSlug);
      }
      return value;
    }
    if (typeof value === "number") {
      return String(value);
    }
    if (typeof value === "object") {
      try {
        const stringified = JSON.stringify(value);
        return stringified && stringified !== "{}" && stringified !== "[]" ? stringified : EMPTY_VALUE_LABEL;
      } catch {
        return EMPTY_VALUE_LABEL;
      }
    }
    return String(value);
  }
  function formatBorderShorthand(border) {
    if (!border || typeof border !== "object") {
      return formatStyleValue(border);
    }
    const { width, style, color } = flattenBorder(border);
    const parts = [width, style, color].filter(isSet).map((part) => formatStyleValue(part));
    return parts.length ? parts.join(" ") : EMPTY_VALUE_LABEL;
  }
  var RADIUS_CORNERS = ["topLeft", "topRight", "bottomRight", "bottomLeft"];
  function formatBorderRadius(radius) {
    if (radius && typeof radius === "object") {
      const parts = RADIUS_CORNERS.map(
        (corner) => radius[corner]
      ).filter(isSet);
      return parts.length ? parts.join(" ") : EMPTY_VALUE_LABEL;
    }
    return formatStyleValue(radius);
  }
  function formatSpacingShorthand(spacing, resolve = (value) => value) {
    const format6 = (value) => formatStyleValue(resolve(value));
    if (!spacing || typeof spacing !== "object") {
      return format6(spacing);
    }
    const { top, right, bottom, left } = spacing;
    if (isSet(top) && isSet(right) && isSet(bottom) && isSet(left)) {
      if (top === right && right === bottom && bottom === left) {
        return format6(top);
      }
      if (top === bottom && left === right) {
        return `${format6(top)} ${format6(left)}`;
      }
      return [top, right, bottom, left].map(format6).join(" ");
    }
    if (!isSet(top) && !isSet(right) && !isSet(bottom) && !isSet(left)) {
      return EMPTY_VALUE_LABEL;
    }
    return [top, right, bottom, left].map(
      (value) => isSet(value) ? format6(value) : EMPTY_VALUE_LABEL
    ).join(" ");
  }
  function formatBlockGap(gap, resolve = (value) => value) {
    const format6 = (value) => formatStyleValue(resolve(value));
    if (!gap || typeof gap !== "object") {
      return format6(gap);
    }
    const { top: row, left: column } = gap;
    if (!isSet(row) && !isSet(column)) {
      return EMPTY_VALUE_LABEL;
    }
    if (row === column) {
      return format6(row);
    }
    const rowLabel = isSet(row) ? format6(row) : EMPTY_VALUE_LABEL;
    const columnLabel = isSet(column) ? format6(column) : EMPTY_VALUE_LABEL;
    return `${rowLabel} - ${columnLabel}`;
  }

  // packages/editor/build-module/hooks/push-changes-to-global-styles/use-review-rows.mjs
  function formatReviewValue(format6, value, resolve) {
    if (format6 === "border") {
      return formatBorderShorthand(value);
    }
    if (format6 === "borderRadius") {
      return formatBorderRadius(value);
    }
    if (format6 === "spacing") {
      return formatSpacingShorthand(value, resolve);
    }
    if (format6 === "blockGap") {
      return formatBlockGap(value, resolve);
    }
    return formatStyleValue(value);
  }
  function useReviewRows(rows, merged, name2) {
    return (0, import_element283.useMemo)(() => {
      const resolve = (value) => getValueFromVariable(merged, name2, value);
      return rows.map((row) => {
        const currentValue = getStyle(
          merged,
          row.primaryPath.join("."),
          name2,
          // Keep preset values encoded (e.g. `var:preset|color|vivid-red`)
          // so they show by name, matching the new value.
          false
        );
        return {
          ...row,
          label: getStyleLabel(row.primaryPath),
          currentValue,
          formattedCurrentValue: formatReviewValue(
            row.format,
            currentValue,
            resolve
          ),
          formattedNewValue: formatReviewValue(
            row.format,
            row.newValue,
            resolve
          )
        };
      });
    }, [rows, merged, name2]);
  }

  // packages/editor/build-module/hooks/push-changes-to-global-styles/apply-globally-modal.mjs
  var import_jsx_runtime481 = __toESM(require_jsx_runtime(), 1);
  var DEFAULT_LAYOUTS = { pickerTable: {} };
  var getItemId = (row) => row.id;
  function ApplyGloballyModal({
    name: name2,
    rows,
    onApply,
    onRequestClose
  }) {
    const { merged } = useGlobalStyles();
    const reviewRows = useReviewRows(rows, merged, name2);
    const [selection, setSelection] = (0, import_element284.useState)(
      () => reviewRows.map((row) => row.id)
    );
    const [view, setView] = (0, import_element284.useState)(() => ({
      type: "pickerTable",
      titleField: "label",
      fields: ["current", "new"],
      page: 1,
      perPage: reviewRows.length,
      layout: { enableMoving: false }
    }));
    const fields2 = (0, import_element284.useMemo)(
      () => [
        {
          id: "label",
          label: (0, import_i18n283.__)("Style"),
          enableSorting: false,
          enableHiding: false,
          filterBy: false,
          getValue: ({ item }) => item.label,
          render: ({ item }) => item.label
        },
        {
          id: "current",
          label: (0, import_i18n283.__)("Current"),
          enableSorting: false,
          enableHiding: false,
          filterBy: false,
          getValue: ({ item }) => item.formattedCurrentValue,
          render: ({ item }) => /* @__PURE__ */ (0, import_jsx_runtime481.jsx)("span", { className: "editor-push-changes-to-global-styles-modal__value", children: item.formattedCurrentValue })
        },
        {
          id: "new",
          label: (0, import_i18n283.__)("New"),
          enableSorting: false,
          enableHiding: false,
          filterBy: false,
          getValue: ({ item }) => item.formattedNewValue,
          render: ({ item }) => /* @__PURE__ */ (0, import_jsx_runtime481.jsx)("span", { className: "editor-push-changes-to-global-styles-modal__value", children: item.formattedNewValue })
        }
      ],
      []
    );
    const actions2 = (0, import_element284.useMemo)(
      () => [
        {
          id: "apply",
          label: (0, import_i18n283.__)("Apply"),
          isPrimary: true,
          supportsBulk: true,
          callback(items) {
            onApply(items);
            onRequestClose();
          }
        }
      ],
      [onApply, onRequestClose]
    );
    const blockTitle = (0, import_blocks29.getBlockType)(name2)?.title;
    return /* @__PURE__ */ (0, import_jsx_runtime481.jsxs)(
      import_components232.Modal,
      {
        title: (0, import_i18n283.sprintf)(
          // translators: %s: Title of the block e.g. 'Heading'.
          (0, import_i18n283.__)("Apply %s styles globally"),
          blockTitle
        ),
        onRequestClose,
        size: "large",
        className: "editor-push-changes-to-global-styles-modal",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime481.jsx)("p", { children: (0, import_i18n283.sprintf)(
            // translators: %s: Title of the block e.g. 'Heading'.
            (0, import_i18n283.__)(
              "Choose which styles to make default for all %s blocks."
            ),
            blockTitle
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime481.jsxs)(
            dataviews_picker_default,
            {
              data: reviewRows,
              fields: fields2,
              view,
              onChangeView: setView,
              actions: actions2,
              selection,
              onChangeSelection: setSelection,
              getItemId,
              paginationInfo: {
                totalItems: reviewRows.length,
                totalPages: 1
              },
              defaultLayouts: DEFAULT_LAYOUTS,
              search: false,
              itemListLabel: (0, import_i18n283.__)("Styles to apply"),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime481.jsx)(dataviews_picker_default.Layout, {}),
                /* @__PURE__ */ (0, import_jsx_runtime481.jsx)(dataviews_picker_default.Footer, {})
              ]
            }
          )
        ]
      }
    );
  }

  // packages/editor/build-module/hooks/push-changes-to-global-styles/index.mjs
  var import_jsx_runtime482 = __toESM(require_jsx_runtime(), 1);
  var { cleanEmptyObject: cleanEmptyObject2 } = unlock(import_block_editor68.privateApis);
  var STYLE_PROPERTY2 = {
    ...import_blocks30.__EXPERIMENTAL_STYLE_PROPERTY,
    blockGap: { value: ["spacing", "blockGap"] }
  };
  var STYLE_PATH_TO_CSS_VAR_INFIX = {
    "border.color": "color",
    "color.background": "color",
    "color.text": "color",
    "elements.link.color.text": "color",
    "elements.link.:hover.color.text": "color",
    "elements.link.typography.fontFamily": "font-family",
    "elements.link.typography.fontSize": "font-size",
    "elements.button.color.text": "color",
    "elements.button.color.background": "color",
    "elements.button.typography.fontFamily": "font-family",
    "elements.button.typography.fontSize": "font-size",
    "elements.caption.color.text": "color",
    "elements.heading.color": "color",
    "elements.heading.color.background": "color",
    "elements.heading.typography.fontFamily": "font-family",
    "elements.heading.gradient": "gradient",
    "elements.heading.color.gradient": "gradient",
    "elements.h1.color": "color",
    "elements.h1.color.background": "color",
    "elements.h1.typography.fontFamily": "font-family",
    "elements.h1.color.gradient": "gradient",
    "elements.h2.color": "color",
    "elements.h2.color.background": "color",
    "elements.h2.typography.fontFamily": "font-family",
    "elements.h2.color.gradient": "gradient",
    "elements.h3.color": "color",
    "elements.h3.color.background": "color",
    "elements.h3.typography.fontFamily": "font-family",
    "elements.h3.color.gradient": "gradient",
    "elements.h4.color": "color",
    "elements.h4.color.background": "color",
    "elements.h4.typography.fontFamily": "font-family",
    "elements.h4.color.gradient": "gradient",
    "elements.h5.color": "color",
    "elements.h5.color.background": "color",
    "elements.h5.typography.fontFamily": "font-family",
    "elements.h5.color.gradient": "gradient",
    "elements.h6.color": "color",
    "elements.h6.color.background": "color",
    "elements.h6.typography.fontFamily": "font-family",
    "elements.h6.color.gradient": "gradient",
    "color.gradient": "gradient",
    blockGap: "spacing",
    "typography.fontSize": "font-size",
    "typography.fontFamily": "font-family"
  };
  var STYLE_PATH_TO_PRESET_BLOCK_ATTRIBUTE = {
    "border.color": "borderColor",
    "color.background": "backgroundColor",
    "color.text": "textColor",
    "color.gradient": "gradient",
    "typography.fontSize": "fontSize",
    "typography.fontFamily": "fontFamily"
  };
  var SUPPORTED_STYLES = ["border", "color", "spacing", "typography"];
  var getValueFromObjectPath2 = (object, path) => {
    let value = object;
    path.forEach((fieldName) => {
      value = value?.[fieldName];
    });
    return value;
  };
  var sides2 = ["top", "right", "bottom", "left"];
  function getBorderRows(supports, attributes, blockUserConfig) {
    const rows = [];
    const border = attributes.style?.border;
    const userBorder = blockUserConfig?.border;
    const colorSupported = supports.includes("borderColor");
    const widthSupported = supports.includes("borderWidth");
    const styleSupported = supports.includes("borderStyle");
    const presetBorderColor = attributes.borderColor;
    const flatColor = presetBorderColor ? `var:preset|color|${presetBorderColor}` : border?.color;
    const flatRow = buildBorderScopeRow({
      id: "border",
      primaryPath: ["border"],
      side: null,
      color: colorSupported ? flatColor : void 0,
      width: widthSupported ? border?.width : void 0,
      style: styleSupported ? border?.style : void 0,
      userBorder,
      presetAttributes: presetBorderColor ? ["borderColor"] : []
    });
    if (flatRow) {
      rows.push(flatRow);
    }
    sides2.forEach((side) => {
      const sideBorder = border?.[side];
      const sideRow = buildBorderScopeRow({
        id: `border.${side}`,
        primaryPath: ["border", side],
        side,
        color: colorSupported ? sideBorder?.color : void 0,
        width: widthSupported ? sideBorder?.width : void 0,
        style: styleSupported ? sideBorder?.style : void 0,
        userBorder,
        presetAttributes: []
      });
      if (sideRow) {
        rows.push(sideRow);
      }
    });
    if (supports.includes("borderRadius") && border?.radius !== void 0 && border?.radius !== "") {
      rows.push({
        id: "border.radius",
        primaryPath: ["border", "radius"],
        paths: [{ path: ["border", "radius"], value: border.radius }],
        presetAttributes: [],
        newValue: border.radius,
        format: "borderRadius"
      });
    }
    return rows;
  }
  function buildBorderScopeRow({
    id,
    primaryPath,
    side,
    color,
    width,
    style,
    userBorder,
    presetAttributes
  }) {
    if (!color && !width && !style) {
      return null;
    }
    const paths = [];
    const targetSides = side ? [side] : sides2;
    const addChange = (property, value) => {
      if (value === void 0) {
        return;
      }
      if (!side) {
        paths.push({ path: ["border", property], value });
      }
      targetSides.forEach((targetSide) => {
        paths.push({ path: ["border", targetSide, property], value });
      });
    };
    addChange("color", color);
    addChange("width", width);
    addChange("style", style);
    let effectiveStyle = style;
    if (!style && (color || width)) {
      const sideStyles = targetSides.map(
        (targetSide) => userBorder?.[targetSide]?.style
      );
      targetSides.forEach((targetSide, index2) => {
        if (!sideStyles[index2]) {
          paths.push({
            path: ["border", targetSide, "style"],
            value: "solid"
          });
        }
      });
      const sharedStyle = sideStyles.every(
        (sideStyle) => sideStyle === sideStyles[0]
      ) ? sideStyles[0] : void 0;
      effectiveStyle = sharedStyle || "solid";
    }
    return {
      id,
      primaryPath,
      paths,
      presetAttributes,
      newValue: { color, width, style: effectiveStyle },
      format: "border"
    };
  }
  function getChangesToPush(supports, attributes, blockUserConfig) {
    const rows = [];
    supports.forEach((key) => {
      if (!STYLE_PROPERTY2[key]) {
        return;
      }
      if (key.startsWith("border")) {
        return;
      }
      if (STYLE_PROPERTY2[key].rootOnly) {
        return;
      }
      const { value: path } = STYLE_PROPERTY2[key];
      const presetAttributeKey = path.join(".");
      const presetAttributeName = STYLE_PATH_TO_PRESET_BLOCK_ATTRIBUTE[presetAttributeKey];
      const presetAttributeValue = presetAttributeName ? attributes[presetAttributeName] : void 0;
      const value = presetAttributeValue ? `var:preset|${STYLE_PATH_TO_CSS_VAR_INFIX[presetAttributeKey]}|${presetAttributeValue}` : getValueFromObjectPath2(attributes.style, path);
      const presetAttributes = presetAttributeValue ? [presetAttributeName] : [];
      if (key === "linkColor") {
        const paths = value ? [{ path, value }] : [];
        const hoverPath = ["elements", "link", ":hover", "color", "text"];
        const hoverValue = getValueFromObjectPath2(
          attributes.style,
          hoverPath
        );
        if (hoverValue) {
          paths.push({ path: hoverPath, value: hoverValue });
        }
        if (paths.length === 0) {
          return;
        }
        rows.push({
          id: presetAttributeKey,
          primaryPath: path,
          paths,
          presetAttributes,
          newValue: value ?? hoverValue
        });
        return;
      }
      if (value) {
        let format6;
        if (key === "padding" || key === "margin") {
          format6 = "spacing";
        } else if (key === "blockGap") {
          format6 = "blockGap";
        }
        rows.push({
          id: presetAttributeKey,
          primaryPath: path,
          paths: [{ path, value }],
          presetAttributes,
          newValue: value,
          format: format6
        });
      }
    });
    rows.push(...getBorderRows(supports, attributes, blockUserConfig));
    return rows;
  }
  function useChangesToPush(name2, attributes, userConfig) {
    const supports = (0, import_data197.useSelect)(
      (select9) => {
        return unlock(select9(import_blocks30.store)).getSupportedStyles(name2);
      },
      [name2]
    );
    const blockUserConfig = userConfig?.styles?.blocks?.[name2];
    return (0, import_element285.useMemo)(
      () => getChangesToPush(supports, attributes, blockUserConfig),
      [supports, attributes, blockUserConfig]
    );
  }
  function getStylesUpdate({
    rowsToPush,
    attributes,
    userConfig,
    name: name2
  }) {
    if (!rowsToPush || rowsToPush.length === 0) {
      return null;
    }
    const selectedChanges = rowsToPush.flatMap((row) => row.paths);
    if (selectedChanges.length === 0) {
      return null;
    }
    const { style: blockStyles } = attributes;
    const newBlockStyles = structuredClone(blockStyles);
    const newUserConfig = structuredClone(userConfig);
    for (const { path, value } of selectedChanges) {
      setNestedValue(newBlockStyles, path, void 0);
      setNestedValue(
        newUserConfig,
        ["styles", "blocks", name2, ...path],
        value
      );
    }
    const newBlockAttributes = {
      style: cleanEmptyObject2(newBlockStyles)
    };
    for (const presetAttribute of rowsToPush.flatMap(
      (row) => row.presetAttributes
    )) {
      newBlockAttributes[presetAttribute] = void 0;
    }
    return { newBlockAttributes, newUserConfig };
  }
  function PushChangesToGlobalStylesControl({
    name: name2,
    attributes,
    setAttributes
  }) {
    const { user: userConfig, setUser: setUserConfig } = useGlobalStyles();
    const rows = useChangesToPush(name2, attributes, userConfig);
    const [isModalOpen, setIsModalOpen] = (0, import_element285.useState)(false);
    const { __unstableMarkNextChangeAsNotPersistent } = (0, import_data197.useDispatch)(import_block_editor68.store);
    const { createSuccessNotice } = (0, import_data197.useDispatch)(import_notices29.store);
    const pushChanges = (0, import_element285.useCallback)(
      (rowsToPush) => {
        const update4 = getStylesUpdate({
          rowsToPush,
          attributes,
          userConfig,
          name: name2
        });
        if (!update4) {
          return;
        }
        const { newBlockAttributes, newUserConfig } = update4;
        __unstableMarkNextChangeAsNotPersistent();
        setAttributes(newBlockAttributes);
        setUserConfig(newUserConfig, { undoIgnore: true });
        createSuccessNotice(
          (0, import_i18n284.sprintf)(
            // translators: %s: Title of the block e.g. 'Heading'.
            (0, import_i18n284.__)("%s styles applied."),
            (0, import_blocks30.getBlockType)(name2).title
          ),
          {
            type: "snackbar",
            actions: [
              {
                label: (0, import_i18n284.__)("Undo"),
                onClick() {
                  __unstableMarkNextChangeAsNotPersistent();
                  setAttributes(attributes);
                  setUserConfig(userConfig, {
                    undoIgnore: true
                  });
                }
              }
            ]
          }
        );
      },
      [
        __unstableMarkNextChangeAsNotPersistent,
        attributes,
        createSuccessNotice,
        name2,
        setAttributes,
        setUserConfig,
        userConfig
      ]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime482.jsxs)(
      import_components233.BaseControl,
      {
        className: "editor-push-changes-to-global-styles-control",
        help: (0, import_i18n284.sprintf)(
          // translators: %s: Title of the block e.g. 'Heading'.
          (0, import_i18n284.__)(
            "Review and apply this block\u2019s typography, spacing, dimensions, and color styles to all %s blocks."
          ),
          (0, import_blocks30.getBlockType)(name2).title
        ),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime482.jsx)(import_components233.BaseControl.VisualLabel, { children: (0, import_i18n284.__)("Styles") }),
          /* @__PURE__ */ (0, import_jsx_runtime482.jsx)(
            import_components233.Button,
            {
              __next40pxDefaultSize: true,
              variant: "secondary",
              accessibleWhenDisabled: true,
              disabled: rows.length === 0,
              onClick: () => setIsModalOpen(true),
              children: (0, import_i18n284.__)("Apply globally")
            }
          ),
          isModalOpen && /* @__PURE__ */ (0, import_jsx_runtime482.jsx)(
            ApplyGloballyModal,
            {
              name: name2,
              rows,
              onApply: pushChanges,
              onRequestClose: () => setIsModalOpen(false)
            }
          )
        ]
      }
    );
  }
  function PushChangesToGlobalStyles(props) {
    const blockEditingMode = (0, import_block_editor68.useBlockEditingMode)();
    const isBlockBasedTheme = (0, import_data197.useSelect)(
      (select9) => select9(import_core_data109.store).getCurrentTheme()?.is_block_theme,
      []
    );
    const supportsStyles = SUPPORTED_STYLES.some(
      (feature) => (0, import_blocks30.hasBlockSupport)(props.name, feature)
    );
    const isDisplayed = blockEditingMode === "default" && supportsStyles && isBlockBasedTheme;
    if (!isDisplayed) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime482.jsx)(import_block_editor68.InspectorAdvancedControls, { children: /* @__PURE__ */ (0, import_jsx_runtime482.jsx)(PushChangesToGlobalStylesControl, { ...props }) });
  }
  var withPushChangesToGlobalStyles = (0, import_compose62.createHigherOrderComponent)(
    (BlockEdit2) => (props) => /* @__PURE__ */ (0, import_jsx_runtime482.jsxs)(import_jsx_runtime482.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime482.jsx)(BlockEdit2, { ...props }, "edit"),
      props.isSelected && /* @__PURE__ */ (0, import_jsx_runtime482.jsx)(PushChangesToGlobalStyles, { ...props })
    ] })
  );
  (0, import_hooks58.addFilter)(
    "editor.BlockEdit",
    "core/editor/push-changes-to-global-styles",
    withPushChangesToGlobalStyles
  );

  // packages/editor/build-module/hooks/note-format.mjs
  var import_rich_text7 = __toESM(require_rich_text(), 1);

  // packages/editor/build-module/components/collab-sidebar/format.mjs
  var import_i18n285 = __toESM(require_i18n(), 1);
  var import_element286 = __toESM(require_element(), 1);
  var import_data198 = __toESM(require_data(), 1);

  // packages/editor/build-module/components/collab-sidebar/constants.mjs
  var ALL_NOTES_SIDEBAR = "edit-post/collab-history-sidebar";
  var FLOATING_NOTES_SIDEBAR = "edit-post/collab-sidebar";
  var SIDEBARS = [ALL_NOTES_SIDEBAR, FLOATING_NOTES_SIDEBAR];

  // packages/editor/build-module/components/collab-sidebar/format.mjs
  var NOTE_FORMAT_NAME = "core/note";
  var noteFormat = {
    title: (0, import_i18n285.__)("Note"),
    tagName: "mark",
    className: "wp-note",
    attributes: {
      "data-id": "data-id"
    },
    edit: NoteFormat
  };
  function NoteFormat({ isActive, activeAttributes }) {
    const { getActiveComplementaryArea: getActiveComplementaryArea2 } = (0, import_data198.useSelect)(store3);
    const { getSelectedNote: getSelectedNote2 } = unlock((0, import_data198.useSelect)(store));
    const { selectNote: selectNote2 } = unlock((0, import_data198.useDispatch)(store));
    const noteId = activeAttributes?.["data-id"];
    (0, import_element286.useEffect)(() => {
      if (!isActive || !noteId) {
        return;
      }
      if (!SIDEBARS.includes(getActiveComplementaryArea2("core"))) {
        return;
      }
      if (String(getSelectedNote2()) === String(noteId)) {
        return;
      }
      selectNote2(Number(noteId));
    }, [
      isActive,
      noteId,
      getActiveComplementaryArea2,
      getSelectedNote2,
      selectNote2
    ]);
    return null;
  }

  // packages/editor/build-module/hooks/note-format.mjs
  (0, import_rich_text7.registerFormatType)(NOTE_FORMAT_NAME, noteFormat);

  // packages/editor/build-module/components/header/back-button.mjs
  var import_components234 = __toESM(require_components(), 1);
  var import_jsx_runtime483 = __toESM(require_jsx_runtime(), 1);
  var slotName = "__experimentalMainDashboardButton";
  var useHasBackButton = () => {
    const fills = (0, import_components234.__experimentalUseSlotFills)(slotName);
    return Boolean(fills && fills.length);
  };
  var { Fill: Fill10, Slot: Slot10 } = (0, import_components234.createSlotFill)(slotName);
  var BackButton = Fill10;
  var BackButtonSlot = () => {
    const fills = (0, import_components234.__experimentalUseSlotFills)(slotName);
    return /* @__PURE__ */ (0, import_jsx_runtime483.jsx)(
      Slot10,
      {
        bubblesVirtually: true,
        fillProps: { length: !fills ? 0 : fills.length }
      }
    );
  };
  BackButton.Slot = BackButtonSlot;
  var back_button_default = BackButton;

  // packages/editor/build-module/components/editor/index.mjs
  var import_data270 = __toESM(require_data(), 1);
  var import_core_data142 = __toESM(require_core_data(), 1);
  var import_components287 = __toESM(require_components(), 1);
  var import_i18n348 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/components/editor-interface/index.mjs
  var import_data226 = __toESM(require_data(), 1);
  var import_i18n310 = __toESM(require_i18n(), 1);
  var import_preferences24 = __toESM(require_preferences(), 1);
  var import_block_editor85 = __toESM(require_block_editor(), 1);
  var import_compose79 = __toESM(require_compose(), 1);
  var import_element311 = __toESM(require_element(), 1);
  var import_html_entities31 = __toESM(require_html_entities(), 1);
  var import_notices32 = __toESM(require_notices(), 1);
  var import_theme = __toESM(require_theme(), 1);

  // packages/editor/build-module/components/header/index.mjs
  var import_block_editor74 = __toESM(require_block_editor(), 1);
  var import_data209 = __toESM(require_data(), 1);
  var import_compose68 = __toESM(require_compose(), 1);
  var import_preferences21 = __toESM(require_preferences(), 1);
  var import_element298 = __toESM(require_element(), 1);

  // packages/editor/build-module/components/collapsible-block-toolbar/index.mjs
  var import_block_editor69 = __toESM(require_block_editor(), 1);
  var import_element287 = __toESM(require_element(), 1);
  var import_components235 = __toESM(require_components(), 1);
  var import_i18n286 = __toESM(require_i18n(), 1);
  var import_data199 = __toESM(require_data(), 1);
  var import_jsx_runtime484 = __toESM(require_jsx_runtime(), 1);
  var { useHasBlockToolbar } = unlock(import_block_editor69.privateApis);
  function CollapsibleBlockToolbar({ isCollapsed, onToggle }) {
    const { blockSelectionStart } = (0, import_data199.useSelect)((select9) => {
      return {
        blockSelectionStart: select9(import_block_editor69.store).getBlockSelectionStart()
      };
    }, []);
    const hasBlockToolbar = useHasBlockToolbar();
    const hasBlockSelection = !!blockSelectionStart;
    (0, import_element287.useEffect)(() => {
      if (blockSelectionStart) {
        onToggle(false);
      }
    }, [blockSelectionStart, onToggle]);
    if (!hasBlockToolbar) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime484.jsxs)(import_jsx_runtime484.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime484.jsx)(
        "div",
        {
          className: clsx_default("editor-collapsible-block-toolbar", {
            "is-collapsed": isCollapsed || !hasBlockSelection
          }),
          children: /* @__PURE__ */ (0, import_jsx_runtime484.jsx)(import_block_editor69.BlockToolbar, { hideDragHandle: true })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime484.jsx)(import_components235.Popover.Slot, { name: "block-toolbar" }),
      /* @__PURE__ */ (0, import_jsx_runtime484.jsx)(
        import_components235.Button,
        {
          className: "editor-collapsible-block-toolbar__toggle",
          icon: isCollapsed ? next_default : previous_default,
          onClick: () => {
            onToggle(!isCollapsed);
          },
          label: isCollapsed ? (0, import_i18n286.__)("Show block tools") : (0, import_i18n286.__)("Hide block tools"),
          size: "compact"
        }
      )
    ] });
  }

  // packages/editor/build-module/components/document-tools/index.mjs
  var import_compose63 = __toESM(require_compose(), 1);
  var import_data200 = __toESM(require_data(), 1);
  var import_i18n287 = __toESM(require_i18n(), 1);
  var import_block_editor70 = __toESM(require_block_editor(), 1);
  var import_components236 = __toESM(require_components(), 1);
  var import_element288 = __toESM(require_element(), 1);
  var import_keyboard_shortcuts6 = __toESM(require_keyboard_shortcuts(), 1);
  var import_preferences15 = __toESM(require_preferences(), 1);
  var import_jsx_runtime485 = __toESM(require_jsx_runtime(), 1);
  function DocumentTools({ className, disableBlockTools = false }) {
    const { setIsInserterOpened: setIsInserterOpened2, setIsListViewOpened: setIsListViewOpened2 } = (0, import_data200.useDispatch)(store);
    const {
      isDistractionFree,
      isInserterOpened: isInserterOpened2,
      isListViewOpen,
      listViewShortcut,
      inserterSidebarToggleRef: inserterSidebarToggleRef2,
      listViewToggleRef: listViewToggleRef2,
      showIconLabels
    } = (0, import_data200.useSelect)((select9) => {
      const { get } = select9(import_preferences15.store);
      const {
        isListViewOpened: isListViewOpened2,
        getEditorMode: getEditorMode2,
        getInserterSidebarToggleRef: getInserterSidebarToggleRef2,
        getListViewToggleRef: getListViewToggleRef2
      } = unlock(select9(store));
      const { getShortcutRepresentation } = select9(import_keyboard_shortcuts6.store);
      return {
        isInserterOpened: select9(store).isInserterOpened(),
        isListViewOpen: isListViewOpened2(),
        listViewShortcut: getShortcutRepresentation(
          "core/editor/toggle-list-view"
        ),
        inserterSidebarToggleRef: getInserterSidebarToggleRef2(),
        listViewToggleRef: getListViewToggleRef2(),
        showIconLabels: get("core", "showIconLabels"),
        isDistractionFree: get("core", "distractionFree"),
        isVisualMode: getEditorMode2() === "visual"
      };
    }, []);
    const preventDefault = (event) => {
      if (isInserterOpened2) {
        event.preventDefault();
      }
    };
    const isWideViewport = (0, import_compose63.useViewportMatch)("wide");
    const toolbarAriaLabel = (0, import_i18n287.__)("Document tools");
    const toggleListView = (0, import_element288.useCallback)(
      () => setIsListViewOpened2(!isListViewOpen),
      [setIsListViewOpened2, isListViewOpen]
    );
    const toggleInserter = (0, import_element288.useCallback)(
      () => setIsInserterOpened2(!isInserterOpened2),
      [isInserterOpened2, setIsInserterOpened2]
    );
    const longLabel = (0, import_i18n287._x)(
      "Block Inserter",
      "Generic label for block inserter button"
    );
    const shortLabel = !isInserterOpened2 ? (0, import_i18n287.__)("Add") : (0, import_i18n287.__)("Close");
    return (
      // Some plugins expect and use the `edit-post-header-toolbar` CSS class to
      // find the toolbar and inject UI elements into it. This is not officially
      // supported, but we're keeping it in the list of class names for backwards
      // compatibility.
      /* @__PURE__ */ (0, import_jsx_runtime485.jsx)(
        import_block_editor70.NavigableToolbar,
        {
          className: clsx_default(
            "editor-document-tools",
            "edit-post-header-toolbar",
            className
          ),
          "aria-label": toolbarAriaLabel,
          variant: "unstyled",
          children: /* @__PURE__ */ (0, import_jsx_runtime485.jsxs)("div", { className: "editor-document-tools__left", children: [
            !isDistractionFree && /* @__PURE__ */ (0, import_jsx_runtime485.jsx)(
              import_components236.ToolbarButton,
              {
                ref: inserterSidebarToggleRef2,
                className: "editor-document-tools__inserter-toggle",
                variant: "primary",
                isPressed: isInserterOpened2,
                onMouseDown: preventDefault,
                onClick: toggleInserter,
                disabled: disableBlockTools,
                icon: plus_default,
                label: showIconLabels ? shortLabel : longLabel,
                showTooltip: !showIconLabels,
                "aria-expanded": isInserterOpened2
              }
            ),
            (isWideViewport || !showIconLabels) && /* @__PURE__ */ (0, import_jsx_runtime485.jsxs)(import_jsx_runtime485.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime485.jsx)(
                import_components236.ToolbarItem,
                {
                  as: undo_default2,
                  showTooltip: !showIconLabels,
                  variant: showIconLabels ? "tertiary" : void 0,
                  size: "compact"
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime485.jsx)(
                import_components236.ToolbarItem,
                {
                  as: redo_default2,
                  showTooltip: !showIconLabels,
                  variant: showIconLabels ? "tertiary" : void 0,
                  size: "compact"
                }
              ),
              !isDistractionFree && /* @__PURE__ */ (0, import_jsx_runtime485.jsx)(
                import_components236.ToolbarButton,
                {
                  className: "editor-document-tools__document-overview-toggle",
                  icon: list_view_default,
                  disabled: disableBlockTools,
                  isPressed: isListViewOpen,
                  label: (0, import_i18n287.__)("Document Overview"),
                  onClick: toggleListView,
                  shortcut: listViewShortcut,
                  showTooltip: !showIconLabels,
                  variant: showIconLabels ? "tertiary" : void 0,
                  "aria-expanded": isListViewOpen,
                  ref: listViewToggleRef2
                }
              )
            ] })
          ] })
        }
      )
    );
  }
  var document_tools_default = DocumentTools;

  // packages/editor/build-module/components/header/header-skeleton.mjs
  var import_components237 = __toESM(require_components(), 1);
  var import_jsx_runtime486 = __toESM(require_jsx_runtime(), 1);
  var toolbarVariations = {
    distractionFreeDisabled: { y: "-50px" },
    distractionFreeHover: { y: 0 },
    distractionFreeHidden: { y: "-50px" },
    visible: { y: 0 },
    hidden: { y: 0 }
  };
  var backButtonVariations = {
    distractionFreeDisabled: { x: "-100%" },
    distractionFreeHover: { x: 0 },
    distractionFreeHidden: { x: "-100%" },
    visible: { x: 0 },
    hidden: { x: 0 }
  };
  function HeaderSkeleton({
    className,
    toolbar,
    center,
    settings
  }) {
    const hasBackButton = useHasBackButton();
    return /* @__PURE__ */ (0, import_jsx_runtime486.jsxs)("div", { className: clsx_default("editor-header edit-post-header", className), children: [
      hasBackButton && /* @__PURE__ */ (0, import_jsx_runtime486.jsx)(
        import_components237.__unstableMotion.div,
        {
          className: "editor-header__back-button",
          variants: backButtonVariations,
          transition: { type: "tween" },
          children: /* @__PURE__ */ (0, import_jsx_runtime486.jsx)(back_button_default.Slot, {})
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime486.jsx)(
        import_components237.__unstableMotion.div,
        {
          variants: toolbarVariations,
          className: "editor-header__toolbar",
          transition: { type: "tween" },
          children: toolbar
        }
      ),
      center && /* @__PURE__ */ (0, import_jsx_runtime486.jsx)(
        import_components237.__unstableMotion.div,
        {
          variants: toolbarVariations,
          className: "editor-header__center",
          transition: { type: "tween" },
          children: center
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime486.jsx)(
        import_components237.__unstableMotion.div,
        {
          variants: toolbarVariations,
          transition: { type: "tween" },
          className: "editor-header__settings",
          children: settings
        }
      )
    ] });
  }

  // packages/editor/build-module/components/more-menu/index.mjs
  var import_i18n290 = __toESM(require_i18n(), 1);
  var import_data203 = __toESM(require_data(), 1);
  var import_keycodes16 = __toESM(require_keycodes(), 1);
  var import_components242 = __toESM(require_components(), 1);
  var import_preferences16 = __toESM(require_preferences(), 1);

  // packages/editor/build-module/components/more-menu/copy-content-menu-item.mjs
  var import_components238 = __toESM(require_components(), 1);
  var import_data201 = __toESM(require_data(), 1);
  var import_i18n288 = __toESM(require_i18n(), 1);
  var import_compose64 = __toESM(require_compose(), 1);
  var import_notices30 = __toESM(require_notices(), 1);
  var import_jsx_runtime487 = __toESM(require_jsx_runtime(), 1);
  function CopyContentMenuItem() {
    const { createNotice } = (0, import_data201.useDispatch)(import_notices30.store);
    const { getEditedPostContent: getEditedPostContent2 } = (0, import_data201.useSelect)(store);
    function getText() {
      return getEditedPostContent2();
    }
    function onSuccess() {
      createNotice("info", (0, import_i18n288.__)("All content copied."), {
        isDismissible: true,
        type: "snackbar"
      });
    }
    const ref = (0, import_compose64.useCopyToClipboard)(getText, onSuccess);
    return /* @__PURE__ */ (0, import_jsx_runtime487.jsx)(import_components238.MenuItem, { ref, children: (0, import_i18n288.__)("Copy all blocks") });
  }

  // packages/editor/build-module/components/mode-switcher/index.mjs
  var import_i18n289 = __toESM(require_i18n(), 1);
  var import_components239 = __toESM(require_components(), 1);
  var import_data202 = __toESM(require_data(), 1);
  var import_keyboard_shortcuts7 = __toESM(require_keyboard_shortcuts(), 1);
  var import_jsx_runtime488 = __toESM(require_jsx_runtime(), 1);
  var MODES = [
    {
      value: "visual",
      label: (0, import_i18n289.__)("Visual editor")
    },
    {
      value: "text",
      label: (0, import_i18n289.__)("Code editor")
    }
  ];
  function ModeSwitcher() {
    const { shortcut, isRichEditingEnabled, isCodeEditingEnabled, mode } = (0, import_data202.useSelect)(
      (select9) => ({
        shortcut: select9(
          import_keyboard_shortcuts7.store
        ).getShortcutRepresentation("core/editor/toggle-mode"),
        isRichEditingEnabled: select9(store).getEditorSettings().richEditingEnabled,
        isCodeEditingEnabled: select9(store).getEditorSettings().codeEditingEnabled,
        mode: select9(store).getEditorMode()
      }),
      []
    );
    const { switchEditorMode: switchEditorMode2 } = (0, import_data202.useDispatch)(store);
    let selectedMode = mode;
    if (!isRichEditingEnabled && mode === "visual") {
      selectedMode = "text";
    }
    if (!isCodeEditingEnabled && mode === "text") {
      selectedMode = "visual";
    }
    const choices = MODES.map((choice) => {
      if (!isCodeEditingEnabled && choice.value === "text") {
        choice = {
          ...choice,
          disabled: true
        };
      }
      if (!isRichEditingEnabled && choice.value === "visual") {
        choice = {
          ...choice,
          disabled: true,
          info: (0, import_i18n289.__)(
            "You can enable the visual editor in your profile settings."
          )
        };
      }
      if (choice.value !== selectedMode && !choice.disabled) {
        return { ...choice, shortcut };
      }
      return choice;
    });
    return /* @__PURE__ */ (0, import_jsx_runtime488.jsx)(import_components239.MenuGroup, { label: (0, import_i18n289.__)("Editor"), children: /* @__PURE__ */ (0, import_jsx_runtime488.jsx)(
      import_components239.MenuItemsChoice,
      {
        choices,
        value: selectedMode,
        onSelect: switchEditorMode2
      }
    ) });
  }
  var mode_switcher_default = ModeSwitcher;

  // packages/editor/build-module/components/more-menu/tools-more-menu-group.mjs
  var import_components240 = __toESM(require_components(), 1);
  var import_jsx_runtime489 = __toESM(require_jsx_runtime(), 1);
  var { Fill: ToolsMoreMenuGroup, Slot: Slot11 } = (0, import_components240.createSlotFill)("ToolsMoreMenuGroup");
  ToolsMoreMenuGroup.Slot = ({ fillProps }) => /* @__PURE__ */ (0, import_jsx_runtime489.jsx)(Slot11, { fillProps });
  var tools_more_menu_group_default = ToolsMoreMenuGroup;

  // packages/editor/build-module/components/more-menu/view-more-menu-group.mjs
  var import_components241 = __toESM(require_components(), 1);
  var import_jsx_runtime490 = __toESM(require_jsx_runtime(), 1);
  var { Fill: ViewMoreMenuGroup, Slot: Slot12 } = (0, import_components241.createSlotFill)(
    /* @__PURE__ */ Symbol("ViewMoreMenuGroup")
  );
  ViewMoreMenuGroup.Slot = ({ fillProps }) => /* @__PURE__ */ (0, import_jsx_runtime490.jsx)(Slot12, { fillProps });
  var view_more_menu_group_default = ViewMoreMenuGroup;

  // packages/editor/build-module/components/more-menu/index.mjs
  var import_jsx_runtime491 = __toESM(require_jsx_runtime(), 1);
  function MoreMenu({ disabled: disabled2 = false }) {
    const { openModal: openModal2 } = (0, import_data203.useDispatch)(store3);
    const { set: setPreference } = (0, import_data203.useDispatch)(import_preferences16.store);
    const { toggleDistractionFree: toggleDistractionFree2 } = (0, import_data203.useDispatch)(store);
    const showIconLabels = (0, import_data203.useSelect)(
      (select9) => select9(import_preferences16.store).get("core", "showIconLabels"),
      []
    );
    const turnOffDistractionFree = () => {
      setPreference("core", "distractionFree", false);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(import_jsx_runtime491.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
      import_components242.DropdownMenu,
      {
        icon: more_vertical_default,
        label: (0, import_i18n290.__)("Options"),
        popoverProps: {
          placement: "bottom-end",
          className: "more-menu-dropdown__content"
        },
        toggleProps: {
          showTooltip: !showIconLabels,
          ...showIconLabels && { variant: "tertiary" },
          tooltipPosition: "bottom",
          size: "compact",
          disabled: disabled2
        },
        children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime491.jsxs)(import_jsx_runtime491.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime491.jsxs)(import_components242.MenuGroup, { label: (0, import_i18n290._x)("View", "noun"), children: [
            /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
              import_preferences16.PreferenceToggleMenuItem,
              {
                scope: "core",
                name: "fixedToolbar",
                onToggle: turnOffDistractionFree,
                label: (0, import_i18n290.__)("Top toolbar"),
                info: (0, import_i18n290.__)(
                  "Access all block and document tools in a single place"
                ),
                messageActivated: (0, import_i18n290.__)(
                  "Top toolbar activated."
                ),
                messageDeactivated: (0, import_i18n290.__)(
                  "Top toolbar deactivated."
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
              import_preferences16.PreferenceToggleMenuItem,
              {
                scope: "core",
                name: "distractionFree",
                label: (0, import_i18n290.__)("Distraction free"),
                info: (0, import_i18n290.__)("Write with calmness"),
                handleToggling: false,
                onToggle: () => toggleDistractionFree2({
                  createNotice: false
                }),
                messageActivated: (0, import_i18n290.__)(
                  "Distraction free mode activated."
                ),
                messageDeactivated: (0, import_i18n290.__)(
                  "Distraction free mode deactivated."
                ),
                shortcut: import_keycodes16.displayShortcut.primaryShift(
                  "\\"
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
              import_preferences16.PreferenceToggleMenuItem,
              {
                scope: "core",
                name: "focusMode",
                label: (0, import_i18n290.__)("Spotlight mode"),
                info: (0, import_i18n290.__)("Focus on one block at a time"),
                messageActivated: (0, import_i18n290.__)(
                  "Spotlight mode activated."
                ),
                messageDeactivated: (0, import_i18n290.__)(
                  "Spotlight mode deactivated."
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(view_more_menu_group_default.Slot, { fillProps: { onClose } })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(mode_switcher_default, {}),
          /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
            action_item_default.Slot,
            {
              name: "core/plugin-more-menu",
              label: (0, import_i18n290.__)("Panels"),
              fillProps: { onClick: onClose }
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime491.jsxs)(import_components242.MenuGroup, { label: (0, import_i18n290.__)("Tools"), children: [
            /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
              import_components242.MenuItem,
              {
                onClick: () => openModal2("editor/keyboard-shortcut-help"),
                shortcut: import_keycodes16.displayShortcut.access("h"),
                children: (0, import_i18n290.__)("Keyboard shortcuts")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(CopyContentMenuItem, {}),
            /* @__PURE__ */ (0, import_jsx_runtime491.jsxs)(
              import_components242.MenuItem,
              {
                icon: external_default,
                href: (0, import_i18n290.__)(
                  "https://wordpress.org/documentation/article/wordpress-block-editor/"
                ),
                target: "_blank",
                rel: "noopener",
                children: [
                  (0, import_i18n290.__)("Help"),
                  /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(VisuallyHidden, {
                    render: /* @__PURE__ */ (0, import_jsx_runtime491.jsx)("span", {}),
                    /* translators: accessibility text */
                    children: (0, import_i18n290.__)("(opens in a new tab)")
                  })
                ]
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
              tools_more_menu_group_default.Slot,
              {
                fillProps: { onClose }
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(import_components242.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime491.jsx)(
            import_components242.MenuItem,
            {
              onClick: () => openModal2("editor/preferences"),
              children: (0, import_i18n290.__)("Preferences")
            }
          ) })
        ] })
      }
    ) });
  }

  // packages/editor/build-module/components/post-publish-button/post-publish-button-or-toggle.mjs
  var import_compose65 = __toESM(require_compose(), 1);
  var import_data204 = __toESM(require_data(), 1);
  var import_jsx_runtime492 = __toESM(require_jsx_runtime(), 1);
  var IS_TOGGLE = "toggle";
  var IS_BUTTON = "button";
  function PostPublishButtonOrToggle({
    forceIsDirty,
    setEntitiesSavedStatesCallback
  }) {
    let component;
    const isSmallerThanMediumViewport = (0, import_compose65.useViewportMatch)("medium", "<");
    const { togglePublishSidebar: togglePublishSidebar2 } = (0, import_data204.useDispatch)(store);
    const {
      hasPublishAction,
      isBeingScheduled,
      isPending,
      isPublished,
      isPublishSidebarEnabled: isPublishSidebarEnabled2,
      isPublishSidebarOpened: isPublishSidebarOpened2,
      isScheduled,
      postStatus,
      postStatusHasChanged,
      postType: postType2
    } = (0, import_data204.useSelect)((select9) => {
      return {
        hasPublishAction: !!select9(store).getCurrentPost()?._links?.["wp:action-publish"],
        isBeingScheduled: select9(store).isEditedPostBeingScheduled(),
        isPending: select9(store).isCurrentPostPending(),
        isPublished: select9(store).isCurrentPostPublished(),
        isPublishSidebarEnabled: select9(store).isPublishSidebarEnabled(),
        isPublishSidebarOpened: select9(store).isPublishSidebarOpened(),
        isScheduled: select9(store).isCurrentPostScheduled(),
        postStatus: select9(store).getEditedPostAttribute("status"),
        postStatusHasChanged: select9(store).getPostEdits()?.status,
        postType: select9(store).getCurrentPostType()
      };
    }, []);
    if (postType2 === ATTACHMENT_POST_TYPE) {
      component = IS_BUTTON;
    } else if (isPublished || postStatusHasChanged && !["future", "publish"].includes(postStatus) || isScheduled && isBeingScheduled || isPending && !hasPublishAction && !isSmallerThanMediumViewport) {
      component = IS_BUTTON;
    } else if (isSmallerThanMediumViewport || isPublishSidebarEnabled2) {
      component = IS_TOGGLE;
    } else {
      component = IS_BUTTON;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime492.jsx)(
      post_publish_button_default,
      {
        forceIsDirty,
        isOpen: isPublishSidebarOpened2,
        isToggle: component === IS_TOGGLE,
        onToggle: togglePublishSidebar2,
        setEntitiesSavedStatesCallback
      }
    );
  }

  // packages/editor/build-module/components/post-view-link/index.mjs
  var import_i18n291 = __toESM(require_i18n(), 1);
  var import_components243 = __toESM(require_components(), 1);
  var import_core_data110 = __toESM(require_core_data(), 1);
  var import_data205 = __toESM(require_data(), 1);
  var import_preferences17 = __toESM(require_preferences(), 1);
  var import_jsx_runtime493 = __toESM(require_jsx_runtime(), 1);
  function PostViewLink() {
    const { hasLoaded, permalink, isPublished, label, showIconLabels } = (0, import_data205.useSelect)((select9) => {
      const postTypeSlug = select9(store).getCurrentPostType();
      const postType2 = select9(import_core_data110.store).getPostType(postTypeSlug);
      const { get } = select9(import_preferences17.store);
      return {
        permalink: select9(store).getPermalink(),
        isPublished: select9(store).isCurrentPostPublished(),
        label: postType2?.labels?.view_item,
        hasLoaded: !!postType2,
        showIconLabels: get("core", "showIconLabels")
      };
    }, []);
    if (!isPublished || !permalink || !hasLoaded) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime493.jsx)(
      import_components243.Button,
      {
        icon: external_default,
        label: label || (0, import_i18n291.__)("View post"),
        href: permalink,
        target: "_blank",
        showTooltip: !showIconLabels,
        size: "compact"
      }
    );
  }

  // packages/editor/build-module/components/preview-dropdown/index.mjs
  var import_compose66 = __toESM(require_compose(), 1);
  var import_components244 = __toESM(require_components(), 1);
  var import_i18n292 = __toESM(require_i18n(), 1);
  var import_data206 = __toESM(require_data(), 1);
  var import_core_data111 = __toESM(require_core_data(), 1);
  var import_preferences18 = __toESM(require_preferences(), 1);
  var import_block_editor71 = __toESM(require_block_editor(), 1);

  // packages/editor/build-module/components/sidebar/constants.mjs
  var sidebars = {
    document: "edit-post/document",
    block: "edit-post/block"
  };

  // packages/editor/build-module/components/preview-dropdown/index.mjs
  var import_jsx_runtime494 = __toESM(require_jsx_runtime(), 1);
  var { getViewportBreakpoints: getViewportBreakpoints5 } = unlock(privateApis);
  function PreviewDropdown({ forceIsAutosaveable, disabled: disabled2 }) {
    const {
      deviceType,
      homeUrl,
      hasMobileViewport,
      hasTabletViewport,
      isTemplate: isTemplate2,
      isViewable,
      showIconLabels,
      isTemplateHidden,
      templateId: templateId2,
      isResponsiveEditing,
      isResponsiveEditingEnabled,
      hasBlockSelection,
      activeComplementaryArea
    } = (0, import_data206.useSelect)((select9) => {
      const {
        getCurrentPostType: getCurrentPostType2,
        getCurrentTemplateId: getCurrentTemplateId2,
        getRenderingMode: getRenderingMode2,
        getDeviceType: getDeviceType2,
        getEditorSettings: getEditorSettings2
      } = unlock(select9(store));
      const {
        isResponsiveEditing: _isResponsiveEditing,
        getBlockSelectionStart: getBlockSelectionStart2,
        getSettings: getSettings10
      } = unlock(select9(import_block_editor71.store));
      const { getEntityRecord, getPostType } = select9(import_core_data111.store);
      const { get } = select9(import_preferences18.store);
      const _currentPostType = getCurrentPostType2();
      const viewportBreakpoints = getViewportBreakpoints5(
        getSettings10().__experimentalFeatures?.viewport
      );
      return {
        deviceType: getDeviceType2(),
        homeUrl: getEntityRecord("root", "__unstableBase")?.home,
        hasMobileViewport: viewportBreakpoints.mobile !== void 0,
        hasTabletViewport: viewportBreakpoints.tablet !== void 0,
        isTemplate: _currentPostType === "wp_template",
        isViewable: getPostType(_currentPostType)?.viewable ?? false,
        showIconLabels: get("core", "showIconLabels"),
        isTemplateHidden: getRenderingMode2() === "post-only",
        templateId: getCurrentTemplateId2(),
        isResponsiveEditing: _isResponsiveEditing(),
        isResponsiveEditingEnabled: getEditorSettings2().responsiveEditingEnabled,
        hasBlockSelection: !!getBlockSelectionStart2(),
        activeComplementaryArea: select9(store3).getActiveComplementaryArea("core")
      };
    }, []);
    const { setDeviceType: setDeviceType2, setRenderingMode: setRenderingMode2, setDefaultRenderingMode: setDefaultRenderingMode2 } = unlock(
      (0, import_data206.useDispatch)(store)
    );
    const { resetZoomLevel, setStyleStateViewport, setResponsiveEditing } = unlock((0, import_data206.useDispatch)(import_block_editor71.store));
    const { enableComplementaryArea: enableComplementaryArea2 } = (0, import_data206.useDispatch)(store3);
    const handleDevicePreviewChange = (newDeviceType) => {
      setDeviceType2(newDeviceType);
      resetZoomLevel();
    };
    const handleResponsiveEditingChange = () => {
      const newIsResponsiveEditing = !isResponsiveEditing;
      setResponsiveEditing(newIsResponsiveEditing);
      setStyleStateViewport(
        newIsResponsiveEditing ? VIEWPORT_STATE_BY_DEVICE_TYPE[deviceType] ?? "default" : "default"
      );
      if (newIsResponsiveEditing && hasBlockSelection && !activeComplementaryArea) {
        enableComplementaryArea2("core", sidebars.block);
      }
    };
    const isMobile = (0, import_compose66.useViewportMatch)("medium", "<");
    if (isMobile) {
      return null;
    }
    const popoverProps = {
      placement: "bottom-end"
    };
    const toggleProps = {
      className: "editor-preview-dropdown__toggle",
      iconPosition: "right",
      size: "compact",
      showTooltip: !showIconLabels,
      disabled: disabled2,
      accessibleWhenDisabled: disabled2
    };
    const menuProps = {
      "aria-label": (0, import_i18n292.__)("View options")
    };
    const deviceIcons = {
      desktop: desktop_default,
      mobile: mobile_default,
      tablet: tablet_default
    };
    const choices = [
      {
        value: "Desktop",
        label: (0, import_i18n292.__)("Desktop"),
        icon: desktop_default,
        info: isResponsiveEditing ? (0, import_i18n292.__)("Style all viewports.") : (0, import_i18n292.__)("Preview desktop viewport.")
      },
      ...hasTabletViewport ? [
        {
          value: "Tablet",
          label: (0, import_i18n292.__)("Tablet"),
          icon: tablet_default,
          info: isResponsiveEditing ? (0, import_i18n292.__)("Style tablet only.") : (0, import_i18n292.__)("Preview tablet viewport.")
        }
      ] : [],
      ...hasMobileViewport ? [
        {
          value: "Mobile",
          label: (0, import_i18n292.__)("Mobile"),
          icon: mobile_default,
          info: isResponsiveEditing ? (0, import_i18n292.__)("Style mobile only.") : (0, import_i18n292.__)("Preview mobile viewport.")
        }
      ] : []
    ];
    return /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(
      import_components244.DropdownMenu,
      {
        className: clsx_default(
          "editor-preview-dropdown",
          `editor-preview-dropdown--${deviceType.toLowerCase()}`,
          { "is-responsive-editing": isResponsiveEditing }
        ),
        popoverProps,
        toggleProps,
        menuProps,
        icon: deviceIcons[deviceType.toLowerCase()],
        label: (0, import_i18n292.__)("View"),
        disableOpenOnArrowDown: disabled2,
        children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime494.jsxs)(import_jsx_runtime494.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(import_components244.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(
            import_components244.MenuItemsChoice,
            {
              choices,
              value: deviceType,
              onSelect: handleDevicePreviewChange
            }
          ) }),
          isResponsiveEditingEnabled && /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(import_components244.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(
            import_components244.MenuItem,
            {
              icon: isResponsiveEditing ? check_default : void 0,
              isSelected: isResponsiveEditing,
              role: "menuitemcheckbox",
              onClick: handleResponsiveEditingChange,
              info: (0, import_i18n292.__)(
                "Style changes apply only to the selected viewport."
              ),
              children: (0, import_i18n292.__)("Responsive styles")
            }
          ) }),
          isTemplate2 && /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(import_components244.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime494.jsxs)(
            import_components244.MenuItem,
            {
              href: homeUrl,
              target: "_blank",
              icon: external_default,
              onClick: onClose,
              children: [
                (0, import_i18n292.__)("View site"),
                /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(VisuallyHidden, {
                  render: /* @__PURE__ */ (0, import_jsx_runtime494.jsx)("span", {}),
                  /* translators: accessibility text */
                  children: (0, import_i18n292.__)("(opens in a new tab)")
                })
              ]
            }
          ) }),
          !isTemplate2 && !!templateId2 && /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(import_components244.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(
            import_components244.MenuItem,
            {
              icon: !isTemplateHidden ? check_default : void 0,
              isSelected: !isTemplateHidden,
              role: "menuitemcheckbox",
              onClick: () => {
                const newRenderingMode = isTemplateHidden ? "template-locked" : "post-only";
                setRenderingMode2(newRenderingMode);
                setDefaultRenderingMode2(newRenderingMode);
                resetZoomLevel();
              },
              children: (0, import_i18n292.__)("Show template")
            }
          ) }),
          isViewable && /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(import_components244.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(
            PostPreviewMenuItem,
            {
              forceIsAutosaveable,
              onPreview: onClose
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime494.jsx)(
            action_item_default.Slot,
            {
              name: "core/plugin-preview-menu",
              fillProps: { onClick: onClose }
            }
          )
        ] })
      }
    );
  }

  // packages/editor/build-module/components/zoom-out-toggle/index.mjs
  var import_components245 = __toESM(require_components(), 1);
  var import_i18n293 = __toESM(require_i18n(), 1);
  var import_element289 = __toESM(require_element(), 1);
  var import_data207 = __toESM(require_data(), 1);
  var import_block_editor72 = __toESM(require_block_editor(), 1);
  var import_preferences19 = __toESM(require_preferences(), 1);
  var import_keyboard_shortcuts8 = __toESM(require_keyboard_shortcuts(), 1);
  var import_keycodes17 = __toESM(require_keycodes(), 1);
  var import_jsx_runtime495 = __toESM(require_jsx_runtime(), 1);
  var ZoomOutToggle = ({ disabled: disabled2 }) => {
    const { isZoomOut, showIconLabels, isDistractionFree } = (0, import_data207.useSelect)(
      (select9) => ({
        isZoomOut: unlock(select9(import_block_editor72.store)).isZoomOut(),
        showIconLabels: select9(import_preferences19.store).get(
          "core",
          "showIconLabels"
        ),
        isDistractionFree: select9(import_preferences19.store).get(
          "core",
          "distractionFree"
        )
      })
    );
    const { resetZoomLevel, setZoomLevel } = unlock(
      (0, import_data207.useDispatch)(import_block_editor72.store)
    );
    const { registerShortcut, unregisterShortcut } = (0, import_data207.useDispatch)(
      import_keyboard_shortcuts8.store
    );
    (0, import_element289.useEffect)(() => {
      registerShortcut({
        name: "core/editor/zoom",
        category: "global",
        description: (0, import_i18n293.__)("Enter or exit zoom out."),
        keyCombination: {
          // `primaryShift+0` (`ctrl+shift+0`) is the shortcut for switching
          // to input mode in Windows, so apply a different key combination.
          modifier: (0, import_keycodes17.isAppleOS)() ? "primaryShift" : "secondary",
          character: "0"
        }
      });
      return () => {
        unregisterShortcut("core/editor/zoom");
      };
    }, [registerShortcut, unregisterShortcut]);
    (0, import_keyboard_shortcuts8.useShortcut)(
      "core/editor/zoom",
      () => {
        if (isZoomOut) {
          resetZoomLevel();
        } else {
          setZoomLevel("auto-scaled");
        }
      },
      {
        isDisabled: isDistractionFree
      }
    );
    const handleZoomOut = () => {
      if (isZoomOut) {
        resetZoomLevel();
      } else {
        setZoomLevel("auto-scaled");
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime495.jsx)(
      import_components245.Button,
      {
        accessibleWhenDisabled: true,
        disabled: disabled2,
        onClick: handleZoomOut,
        icon: square_default,
        label: (0, import_i18n293.__)("Zoom Out"),
        isPressed: isZoomOut,
        size: "compact",
        showTooltip: !showIconLabels,
        className: "editor-zoom-out-toggle"
      }
    );
  };
  var zoom_out_toggle_default = ZoomOutToggle;

  // packages/editor/build-module/components/collaborators-presence/index.mjs
  var import_components248 = __toESM(require_components(), 1);
  var import_element297 = __toESM(require_element(), 1);
  var import_core_data115 = __toESM(require_core_data(), 1);
  var import_i18n298 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/components/collaborators-presence/avatar/component.mjs
  var import_components246 = __toESM(require_components(), 1);
  var import_element291 = __toESM(require_element(), 1);

  // packages/editor/build-module/components/collaborators-presence/avatar/use-image-loading-status.mjs
  var import_element290 = __toESM(require_element(), 1);
  function useImageLoadingStatus(src) {
    const [prevSrc, setPrevSrc] = (0, import_element290.useState)(src);
    const [status, setStatus] = (0, import_element290.useState)(
      src ? "loading" : "idle"
    );
    if (prevSrc !== src) {
      setPrevSrc(src);
      setStatus(src ? "loading" : "idle");
    }
    const handleLoad = (0, import_element290.useCallback)(() => setStatus("loaded"), []);
    const handleError = (0, import_element290.useCallback)(() => setStatus("error"), []);
    return { status, handleLoad, handleError };
  }

  // packages/editor/build-module/components/collaborators-presence/avatar/component.mjs
  var import_jsx_runtime496 = __toESM(require_jsx_runtime(), 1);
  k([a11y_default]);
  var GRAY_900 = "#1e1e1e";
  var WHITE = "#fff";
  function Avatar({
    className,
    src,
    name: name2,
    label,
    variant,
    size: size4 = "default",
    borderColor,
    dimmed = false,
    statusIndicator,
    style,
    ...props
  }) {
    const {
      status: imageStatus,
      handleLoad,
      handleError
    } = useImageLoadingStatus(src);
    const imageLoaded = imageStatus === "loaded";
    const showBadge = variant === "badge" && !!name2;
    const initials = name2 ? name2.split(/\s+/).slice(0, 2).map((word) => word[0]).join("").toUpperCase() : void 0;
    const nameColor = (0, import_element291.useMemo)(
      () => borderColor && w(borderColor).isReadable(GRAY_900, {
        level: "AA",
        size: "normal"
      }) ? GRAY_900 : WHITE,
      [borderColor]
    );
    const customProperties = {
      ...style,
      ...borderColor ? {
        "--editor-avatar-outline-color": borderColor,
        "--editor-avatar-name-color": nameColor
      } : {}
    };
    const avatar = /* @__PURE__ */ (0, import_jsx_runtime496.jsxs)(
      "div",
      {
        className: clsx_default("editor-avatar", className, {
          "has-avatar-border-color": !!borderColor,
          "has-src": imageLoaded,
          "is-badge": showBadge,
          "is-small": size4 === "small",
          "is-dimmed": dimmed
        }),
        style: customProperties,
        role: name2 ? "img" : void 0,
        "aria-label": name2 || void 0,
        ...props,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime496.jsxs)("span", { className: "editor-avatar__image", children: [
            src && /* @__PURE__ */ (0, import_jsx_runtime496.jsx)(
              "img",
              {
                src,
                alt: "",
                crossOrigin: "anonymous",
                className: "editor-avatar__img",
                onLoad: handleLoad,
                onError: handleError
              }
            ),
            !imageLoaded && initials
          ] }),
          dimmed && !!statusIndicator && /* @__PURE__ */ (0, import_jsx_runtime496.jsx)("span", { className: "editor-avatar__status-indicator", children: /* @__PURE__ */ (0, import_jsx_runtime496.jsx)(import_components246.Icon, { icon: statusIndicator }) }),
          showBadge && /* @__PURE__ */ (0, import_jsx_runtime496.jsx)("span", { className: "editor-avatar__name", children: label || name2 })
        ]
      }
    );
    if (name2 && (!showBadge || label)) {
      return /* @__PURE__ */ (0, import_jsx_runtime496.jsxs)(tooltip_exports.Root, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime496.jsx)(tooltip_exports.Trigger, { render: avatar }),
        /* @__PURE__ */ (0, import_jsx_runtime496.jsx)(tooltip_exports.Popup, { children: name2 })
      ] });
    }
    return avatar;
  }
  var component_default = Avatar;

  // packages/editor/build-module/components/collaborators-presence/avatar-group/component.mjs
  var import_element292 = __toESM(require_element(), 1);
  var import_i18n294 = __toESM(require_i18n(), 1);
  var import_jsx_runtime497 = __toESM(require_jsx_runtime(), 1);
  function AvatarGroup({
    className,
    max: max3 = 3,
    children,
    ...props
  }) {
    const childArray = import_element292.Children.toArray(children);
    const visible = childArray.slice(0, max3);
    const overflowCount = childArray.length - max3;
    return /* @__PURE__ */ (0, import_jsx_runtime497.jsxs)(
      "div",
      {
        role: "group",
        className: clsx_default("editor-avatar-group", className),
        ...props,
        children: [
          visible,
          overflowCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime497.jsx)(
            "span",
            {
              className: "editor-avatar-group__overflow",
              "aria-label": (0, import_i18n294.sprintf)(
                /* translators: %d: number of additional collaborators not shown */
                (0, import_i18n294._n)(
                  "%d more collaborator",
                  "%d more collaborators",
                  overflowCount
                ),
                overflowCount
              ),
              children: `+${overflowCount}`
            }
          )
        ]
      }
    );
  }
  var component_default2 = AvatarGroup;

  // packages/editor/build-module/components/collaborators-presence/list.mjs
  var import_i18n296 = __toESM(require_i18n(), 1);
  var import_components247 = __toESM(require_components(), 1);
  var import_a11y11 = __toESM(require_a11y(), 1);

  // packages/editor/build-module/components/collaborators-overlay/get-avatar-url.mjs
  function getAvatarUrl(avatarUrls) {
    return avatarUrls?.["48"] || avatarUrls?.["96"] || avatarUrls?.["24"];
  }

  // packages/editor/build-module/components/collab-sidebar/utils.mjs
  var import_i18n295 = __toESM(require_i18n(), 1);
  var import_rich_text8 = __toESM(require_rich_text(), 1);
  var import_dom25 = __toESM(require_dom(), 1);
  function sanitizeNoteContent(str3) {
    return str3.trim();
  }
  var THREAD_ALIGN_OFFSET = -16;
  var THREAD_GAP = 16;
  var OVERLAP_MARGIN = 20;
  var AVATAR_BORDER_COLORS = [
    "#6F42C1",
    // Purple
    "#D94145",
    // Red
    "#FBBF24",
    // Orange
    "#FF35EE",
    // Magenta
    "#879F11",
    // Olive
    "#0F766E",
    // Teal
    "#00CFFF"
    // Cyan
  ];
  function getAvatarBorderColor(userId) {
    return AVATAR_BORDER_COLORS[userId % AVATAR_BORDER_COLORS.length];
  }
  function getNoteExcerpt(text, excerptLength = 10) {
    if (!text) {
      return "";
    }
    const wordCountType = (0, import_i18n295._x)("words", "Word count type. Do not translate!");
    const rawText = text.trim();
    let trimmedExcerpt = "";
    if (wordCountType === "words") {
      trimmedExcerpt = rawText.split(" ", excerptLength).join(" ");
    } else if (wordCountType === "characters_excluding_spaces") {
      const textWithSpaces = rawText.split("", excerptLength).join("");
      const numberOfSpaces = textWithSpaces.length - textWithSpaces.replaceAll(" ", "").length;
      trimmedExcerpt = rawText.split("", excerptLength + numberOfSpaces).join("");
    } else if (wordCountType === "characters_including_spaces") {
      trimmedExcerpt = rawText.split("", excerptLength).join("");
    }
    const isTrimmed = trimmedExcerpt !== rawText;
    return isTrimmed ? trimmedExcerpt + "\u2026" : trimmedExcerpt;
  }
  function getNoteIdsFromMetadata(metadata) {
    const noteId = metadata?.noteId;
    const raw = Array.isArray(noteId) ? noteId : [noteId];
    const ids = /* @__PURE__ */ new Set();
    for (const value of raw) {
      const id = Number(value);
      if (Number.isFinite(id) && id > 0) {
        ids.add(id);
      }
    }
    return [...ids];
  }
  function addNoteIdToMetadata(metadata, noteId) {
    const ids = new Set(getNoteIdsFromMetadata(metadata));
    const id = Number(noteId);
    if (ids.has(id)) {
      return metadata;
    }
    ids.add(id);
    return { ...metadata, noteId: [...ids] };
  }
  var NOTE_FORMAT_TYPE = "core/note";
  function findNoteRange(value, noteId) {
    if (noteId === void 0 || noteId === null) {
      return null;
    }
    let html = null;
    if (value instanceof import_rich_text8.RichTextData) {
      html = value.toHTMLString();
    } else if (typeof value === "string") {
      html = value;
    }
    if (!html || html.indexOf("wp-note") === -1) {
      return null;
    }
    const target = String(noteId);
    const record = (0, import_rich_text8.create)({ html });
    const formats = record.formats;
    let start2 = -1;
    for (let i3 = 0; i3 < formats.length; i3++) {
      const stack = formats[i3];
      const hit = stack?.find(
        (f3) => f3.type === NOTE_FORMAT_TYPE && f3.attributes && f3.attributes["data-id"] === target
      );
      if (hit) {
        if (start2 === -1) {
          start2 = i3;
        }
      } else if (start2 !== -1) {
        return { start: start2, end: i3 };
      }
    }
    if (start2 !== -1) {
      return { start: start2, end: formats.length };
    }
    return null;
  }
  function findNoteInBlock(attributes, noteId) {
    if (!attributes) {
      return null;
    }
    for (const attributeKey of Object.keys(attributes)) {
      const range = findNoteRange(attributes[attributeKey], noteId);
      if (range) {
        return { attributeKey, start: range.start, end: range.end };
      }
    }
    return null;
  }
  function getNoteMarkerSelector(noteId) {
    const escapedId = String(noteId).replace(
      /["\\\n\r\f]/g,
      (char) => char === '"' || char === "\\" ? `\\${char}` : `\\${char.codePointAt(0).toString(16)} `
    );
    return `mark.wp-note[data-id="${escapedId}"]`;
  }
  function getSelectionRect(blockEl) {
    const selection = blockEl.ownerDocument.defaultView?.getSelection();
    if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
      return null;
    }
    const range = selection.getRangeAt(0);
    if (range.collapsed) {
      return null;
    }
    if (!blockEl.contains(range.commonAncestorContainer)) {
      return null;
    }
    const rect = (0, import_dom25.getRectangleFromRange)(range);
    if (!rect || rect.width === 0 && rect.height === 0) {
      return null;
    }
    return rect;
  }
  var BLOCK_LEVEL_NOTE_START = -1;
  function getInlineMarkerStart(thread, attributes) {
    const found = findNoteInBlock(attributes, thread?.id);
    return found ? found.start : BLOCK_LEVEL_NOTE_START;
  }
  function applyNoteFormat(record, format6, start2, end) {
    const formats = record.formats.slice();
    for (let i3 = start2; i3 < end; i3++) {
      const stack = formats[i3] ? formats[i3].slice() : [];
      stack.push(format6);
      formats[i3] = stack;
    }
    const spans = /* @__PURE__ */ new Map();
    for (let i3 = 0; i3 < formats.length; i3++) {
      const stack = formats[i3];
      if (!stack) {
        continue;
      }
      for (const fmt of stack) {
        if (fmt.type !== NOTE_FORMAT_TYPE) {
          continue;
        }
        const id = fmt.attributes?.["data-id"];
        const span = spans.get(id);
        if (span) {
          span.end = i3;
        } else {
          spans.set(id, { start: i3, end: i3 });
        }
      }
    }
    const sizeOf = (id) => {
      const span = spans.get(id);
      return span ? span.end - span.start : 0;
    };
    for (let i3 = 0; i3 < formats.length; i3++) {
      const stack = formats[i3];
      if (!stack || stack.length < 2) {
        continue;
      }
      const notes = stack.filter((fmt) => fmt.type === NOTE_FORMAT_TYPE);
      if (notes.length === 0) {
        continue;
      }
      if (notes.length > 1) {
        notes.sort(
          (a3, b3) => sizeOf(b3.attributes?.["data-id"]) - sizeOf(a3.attributes?.["data-id"])
        );
      }
      const others = stack.filter((fmt) => fmt.type !== NOTE_FORMAT_TYPE);
      formats[i3] = [...notes, ...others];
    }
    return { ...record, formats };
  }
  function removeNoteFormat(value, noteId) {
    if (!(value instanceof import_rich_text8.RichTextData)) {
      return null;
    }
    const target = String(noteId);
    const record = (0, import_rich_text8.create)({ html: value.toHTMLString() });
    let changed = false;
    const formats = record.formats.map((stack) => {
      if (!stack) {
        return stack;
      }
      const filtered = stack.filter(
        (format6) => !(format6.type === NOTE_FORMAT_TYPE && format6.attributes?.["data-id"] === target)
      );
      if (filtered.length === stack.length) {
        return stack;
      }
      changed = true;
      return filtered.length ? filtered : void 0;
    });
    return changed ? import_rich_text8.RichTextData.fromHTMLString(
      new import_rich_text8.RichTextData({ ...record, formats }).toHTMLString()
    ) : null;
  }
  function pickPrimaryNote(threads) {
    return threads.find((thread) => thread.status === "hold") ?? threads[0] ?? null;
  }
  function removeNoteIdFromMetadata(metadata, noteId) {
    const ids = new Set(getNoteIdsFromMetadata(metadata));
    ids.delete(Number(noteId));
    return {
      ...metadata,
      noteId: ids.size > 0 ? [...ids] : void 0
    };
  }
  function calculateNotePositions({
    threads,
    selectedNoteId,
    blockRects,
    heights,
    scrollTop = 0
  }) {
    const offsets = {};
    const orderedThreads = [...threads].sort(
      (a3, b3) => (blockRects[a3.id]?.top ?? Number.MAX_VALUE) - (blockRects[b3.id]?.top ?? Number.MAX_VALUE)
    );
    const anchorIndex = Math.max(
      0,
      orderedThreads.findIndex((thread) => thread.id === selectedNoteId)
    );
    const anchorThread = orderedThreads[anchorIndex];
    if (!anchorThread || !blockRects[anchorThread.id]) {
      return { positions: {} };
    }
    const anchorRect = blockRects[anchorThread.id];
    const anchorTop = anchorRect.top || 0;
    const anchorHeight = heights[anchorThread.id] || 0;
    offsets[anchorThread.id] = THREAD_ALIGN_OFFSET;
    let prevAdjustedTop = anchorTop + THREAD_ALIGN_OFFSET;
    let prevHeight = anchorHeight;
    for (let i3 = anchorIndex + 1; i3 < orderedThreads.length; i3++) {
      const thread = orderedThreads[i3];
      const threadRect = blockRects[thread.id];
      if (!threadRect) {
        continue;
      }
      const threadTop = threadRect.top || 0;
      const threadHeight = heights[thread.id] || 0;
      let offset4 = THREAD_ALIGN_OFFSET;
      const prevBottom = prevAdjustedTop + prevHeight;
      if (threadTop < prevBottom + THREAD_GAP) {
        offset4 = prevBottom - threadTop + OVERLAP_MARGIN;
      }
      offsets[thread.id] = offset4;
      prevAdjustedTop = threadTop + offset4;
      prevHeight = threadHeight;
    }
    let belowAdjustedTop = anchorTop + THREAD_ALIGN_OFFSET;
    for (let i3 = anchorIndex - 1; i3 >= 0; i3--) {
      const thread = orderedThreads[i3];
      const threadRect = blockRects[thread.id];
      if (!threadRect) {
        continue;
      }
      const threadTop = threadRect.top || 0;
      const threadHeight = heights[thread.id] || 0;
      let offset4 = THREAD_ALIGN_OFFSET;
      const threadBottom = threadTop + threadHeight;
      if (threadBottom > belowAdjustedTop) {
        offset4 = belowAdjustedTop - threadTop - threadHeight - OVERLAP_MARGIN;
      }
      offsets[thread.id] = offset4;
      belowAdjustedTop = threadTop + offset4;
    }
    const positions = {};
    for (const thread of orderedThreads) {
      const blockRect = blockRects[thread.id];
      if (blockRect && offsets[thread.id] !== void 0) {
        positions[thread.id] = blockRect.top + scrollTop + offsets[thread.id];
      }
    }
    return { positions };
  }
  function findNoteThread(noteId, container, additionalSelector) {
    if (!container) {
      return Promise.resolve(null);
    }
    const threadSelector = noteId && noteId !== "new" ? `[role=treeitem][id="note-thread-${noteId}"]` : "[role=treeitem]:not([id])";
    const selector2 = additionalSelector ? `${threadSelector} ${additionalSelector}` : threadSelector;
    return new Promise((resolve) => {
      if (container.querySelector(selector2)) {
        return resolve(container.querySelector(selector2));
      }
      let timer = null;
      const observer = new window.MutationObserver(() => {
        if (container.querySelector(selector2)) {
          clearTimeout(timer);
          observer.disconnect();
          resolve(container.querySelector(selector2));
        }
      });
      observer.observe(container, { childList: true, subtree: true });
      timer = setTimeout(() => {
        observer.disconnect();
        resolve(null);
      }, 3e3);
    });
  }
  function focusNoteThread(noteId, container, additionalSelector) {
    return findNoteThread(noteId, container, additionalSelector).then(
      (element) => {
        if (!element) {
          return;
        }
        element.focus();
        element.scrollIntoView({ block: "nearest" });
      }
    );
  }
  function scrollNoteThreadIntoView(noteId, container) {
    return findNoteThread(noteId, container).then((element) => {
      element?.scrollIntoView({ block: "nearest" });
    });
  }

  // packages/editor/build-module/components/collaborators-presence/list.mjs
  var import_jsx_runtime498 = __toESM(require_jsx_runtime(), 1);
  function CollaboratorsList({
    activeCollaborators,
    popoverAnchor,
    setIsPopoverVisible,
    cursorRegistry
  }) {
    const handleCollaboratorClick = (clientId) => {
      const success = cursorRegistry.scrollToCursor(clientId, {
        behavior: "smooth",
        block: "center",
        highlightDuration: 2e3
      });
      if (success) {
        (0, import_a11y11.speak)((0, import_i18n296.__)("Scrolled to cursor"), "polite");
        setIsPopoverVisible(false);
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime498.jsx)(
      import_components247.Popover,
      {
        anchor: popoverAnchor,
        placement: "bottom",
        offset: 8,
        className: "editor-collaborators-presence__list",
        onClose: () => setIsPopoverVisible(false),
        children: /* @__PURE__ */ (0, import_jsx_runtime498.jsxs)("div", { className: "editor-collaborators-presence__list-content", children: [
          /* @__PURE__ */ (0, import_jsx_runtime498.jsxs)("div", { className: "editor-collaborators-presence__list-header", children: [
            /* @__PURE__ */ (0, import_jsx_runtime498.jsxs)("div", { className: "editor-collaborators-presence__list-header-title", children: [
              (0, import_i18n296.__)("Collaborators"),
              /* @__PURE__ */ (0, import_jsx_runtime498.jsx)("span", { children: activeCollaborators.length })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime498.jsx)("div", { className: "editor-collaborators-presence__list-header-action", children: /* @__PURE__ */ (0, import_jsx_runtime498.jsx)(
              import_components247.Button,
              {
                __next40pxDefaultSize: true,
                icon: close_small_default,
                iconSize: 24,
                label: (0, import_i18n296.__)("Close Collaborators List"),
                onClick: () => setIsPopoverVisible(false)
              }
            ) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime498.jsx)("div", { className: "editor-collaborators-presence__list-items", children: activeCollaborators.map((collaboratorState) => {
            const isCurrentUser = collaboratorState.isMe;
            return /* @__PURE__ */ (0, import_jsx_runtime498.jsxs)(
              "button",
              {
                className: "editor-collaborators-presence__list-item",
                disabled: isCurrentUser,
                onClick: () => handleCollaboratorClick(
                  collaboratorState.clientId
                ),
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime498.jsx)(
                    component_default,
                    {
                      src: getAvatarUrl(
                        collaboratorState.collaboratorInfo.avatar_urls
                      ),
                      name: collaboratorState.collaboratorInfo.name,
                      borderColor: isCurrentUser ? "var(--wp-admin-theme-color)" : getAvatarBorderColor(
                        collaboratorState.collaboratorInfo.id
                      ),
                      dimmed: !collaboratorState.isConnected
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime498.jsx)("div", { className: "editor-collaborators-presence__list-item-info", children: /* @__PURE__ */ (0, import_jsx_runtime498.jsx)("div", { className: "editor-collaborators-presence__list-item-name", children: isCurrentUser ? (0, import_i18n296.__)("You") : collaboratorState.collaboratorInfo.name }) })
                ]
              },
              collaboratorState.clientId
            );
          }) })
        ] })
      }
    );
  }

  // packages/editor/build-module/components/collaborators-overlay/cursor-registry.mjs
  function highlightCursor(element, duration) {
    element.classList.add("collaborators-overlay-cursor-highlighted");
    setTimeout(() => {
      element.classList.remove("collaborators-overlay-cursor-highlighted");
    }, duration);
  }
  function createCursorRegistry() {
    const cursorMap = /* @__PURE__ */ new Map();
    return {
      /**
       * Register a cursor element when it's created.
       *
       * @param clientId - The clientId of the cursor to register.
       * @param element  - The cursor element to register.
       */
      registerCursor(clientId, element) {
        cursorMap.set(clientId, element);
      },
      /**
       * Unregister a cursor element when it's removed.
       *
       * @param clientId - The clientId of the cursor to unregister.
       */
      unregisterCursor(clientId) {
        cursorMap.delete(clientId);
      },
      /**
       * Scroll to a cursor by clientId.
       *
       * @param clientId - The clientId of the cursor to scroll to.
       * @param options  - The options for the scroll.
       * @return true if cursor was found and scrolled to, false otherwise.
       */
      scrollToCursor(clientId, options) {
        const cursorElement = cursorMap.get(clientId);
        if (!cursorElement) {
          return false;
        }
        cursorElement.scrollIntoView({
          behavior: options?.behavior ?? "smooth",
          block: options?.block ?? "center",
          inline: options?.inline ?? "nearest"
        });
        if (options?.highlightDuration) {
          highlightCursor(cursorElement, options.highlightDuration);
        }
        return true;
      },
      /**
       * Clear the registry.
       */
      removeAll() {
        cursorMap.clear();
      }
    };
  }

  // packages/editor/build-module/components/collaborators-overlay/index.mjs
  var import_block_editor73 = __toESM(require_block_editor(), 1);

  // packages/editor/build-module/components/collaborators-overlay/overlay.mjs
  var import_compose67 = __toESM(require_compose(), 1);
  var import_element296 = __toESM(require_element(), 1);
  var import_i18n297 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/components/collaborators-overlay/collaborator-styles.mjs
  var ELEVATION_X_SMALL = "0 1px 1px rgba(0, 0, 0, 0.03), 0 1px 2px rgba(0, 0, 0, 0.02), 0 3px 3px rgba(0, 0, 0, 0.02), 0 4px 4px rgba(0, 0, 0, 0.01)";
  var RADIUS_FULL = "9999px";
  var BUTTON_SIZE_COMPACT = "32px";
  var BUTTON_SIZE_SMALL = "24px";
  var GRID_UNIT_05 = "4px";
  var GRID_UNIT_10 = "8px";
  var BORDER_WIDTH = "1px";
  var BORDER_WIDTH_FOCUS_FALLBACK = "2px";
  var WHITE2 = "#fff";
  var FONT_SIZE_X_SMALL = "11px";
  var FONT_SIZE_MEDIUM = "13px";
  var FONT_WEIGHT_EMPHASIS = "var(--wpds-typography-font-weight-emphasis, 600)";
  var FONT_LINE_HEIGHT_SMALL = "20px";

  // packages/editor/build-module/components/collaborators-overlay/avatar-iframe-styles.mjs
  var AVATAR_IFRAME_STYLES = `
.editor-avatar {
	position: relative;
	display: inline-flex;
	align-items: center;
	border-radius: ${RADIUS_FULL};
	flex-shrink: 0;
	box-shadow: 0 0 0 var(--wp-admin-border-width-focus, 2px) ${WHITE2}, ${ELEVATION_X_SMALL};
}
.editor-avatar__image {
	box-sizing: border-box;
	position: relative;
	width: ${BUTTON_SIZE_COMPACT};
	height: ${BUTTON_SIZE_COMPACT};
	border-radius: ${RADIUS_FULL};
	border: 0;
	background-color: var(--wp-admin-theme-color, #3858e9);
	overflow: hidden;
	overflow: clip;
	flex-shrink: 0;
	font-size: 0;
	color: ${WHITE2};
}
.is-small > .editor-avatar__image {
	width: ${BUTTON_SIZE_SMALL};
	height: ${BUTTON_SIZE_SMALL};
}
.has-avatar-border-color > .editor-avatar__image {
	border: var(--wp-admin-border-width-focus, 2px) solid var(--editor-avatar-outline-color);
	background-clip: padding-box;
}
.has-avatar-border-color > .editor-avatar__image::after {
	content: "";
	position: absolute;
	inset: 0;
	border-radius: inherit;
	box-shadow: inset 0 0 0 var(--wp-admin-border-width-focus, 2px) ${WHITE2};
	pointer-events: none;
	z-index: 1;
}
.editor-avatar__img {
	position: absolute;
	inset: 0;
	width: 100%;
	height: 100%;
	object-fit: cover;
	border-radius: inherit;
	opacity: 0;
}
.has-src > .editor-avatar__image > .editor-avatar__img {
	opacity: 1;
}
.editor-avatar:not(.has-src) > .editor-avatar__image {
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: ${FONT_SIZE_X_SMALL};
	font-weight: ${FONT_WEIGHT_EMPHASIS};
	border: 0;
	background-clip: border-box;
}
.editor-avatar:not(.has-src) > .editor-avatar__image::after {
	content: none;
}
.editor-avatar:not(.has-src).has-avatar-border-color > .editor-avatar__image {
	background-color: var(--editor-avatar-outline-color);
}
.editor-avatar__name {
	font-size: ${FONT_SIZE_MEDIUM};
	font-weight: ${FONT_WEIGHT_EMPHASIS};
	line-height: ${FONT_LINE_HEIGHT_SMALL};
	color: var(--editor-avatar-name-color, ${WHITE2});
	min-width: 0;
	padding-bottom: 2px; /* $grid-unit-05 / 2 */
	overflow: hidden;
	opacity: 0;
	white-space: nowrap;
	transition: opacity 0.15s cubic-bezier(0.15, 0, 0.15, 1);
}
.editor-avatar.is-badge {
	display: inline-grid;
	grid-template-columns: min-content 0fr;
	column-gap: 0;
	padding-inline-end: 0;
	background-color: var(--wp-admin-theme-color, #3858e9);
	transition:
		grid-template-columns 0.3s cubic-bezier(0.15, 0, 0.15, 1),
		column-gap 0.3s cubic-bezier(0.15, 0, 0.15, 1),
		padding-inline-end 0.3s cubic-bezier(0.15, 0, 0.15, 1);
}
.editor-avatar.is-badge:hover {
	grid-template-columns: min-content 1fr;
	column-gap: ${GRID_UNIT_05};
	padding-inline-end: ${GRID_UNIT_10};
	transition-timing-function: cubic-bezier(0.85, 0, 0.85, 1);
}
.editor-avatar.is-badge:hover .editor-avatar__name {
	opacity: 1;
	transition-timing-function: cubic-bezier(0.85, 0, 0.85, 1);
}
.editor-avatar.is-badge.has-avatar-border-color {
	background-color: var(--editor-avatar-outline-color);
}
@media (prefers-reduced-motion: reduce) {
	.editor-avatar.is-badge,
	.editor-avatar__name {
		transition: none;
	}
}
`;

  // packages/editor/build-module/components/collaborators-overlay/overlay-iframe-styles.mjs
  var OVERLAY_IFRAME_STYLES = `
.block-canvas-cover {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	pointer-events: none;
	z-index: 20000;
}
.block-canvas-cover .collaborators-overlay-full {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
}
.block-canvas-cover .collaborators-overlay-fixed {
	position: fixed;
	width: 100%;
	height: 100%;
}
.collaborators-overlay-user {
	position: absolute;
}
/* Cursor lines render below avatar labels across all users. The parent
   .collaborators-overlay-user has no z-index so it does not create a
   stacking context \u2014 children participate in the shared overlay context. */
.collaborators-overlay-user-cursor {
	position: absolute;
	z-index: 0;
	width: ${BORDER_WIDTH_FOCUS_FALLBACK};
	border-radius: ${BORDER_WIDTH};
	outline: ${BORDER_WIDTH} solid ${WHITE2};
	box-shadow: ${ELEVATION_X_SMALL};
	animation: collaborators-overlay-cursor-blink 1s infinite;
}
.collaborators-overlay-selection-rect {
	position: absolute;
	opacity: 0.15;
	pointer-events: none;
	border-radius: 2px;
}

/* Overlay-specific positioning applied to the Avatar cursor label. */
.collaborators-overlay-user-label.editor-avatar {
	position: absolute;
	z-index: 1;
	transform: translate(-11px, -100%);
	margin-top: -${GRID_UNIT_05};
	pointer-events: auto;
	overflow: visible;
	width: max-content;
}
/* Avatar positioned above a highlighted block as a label. */
.collaborators-overlay-block-label.editor-avatar {
	position: absolute;
	z-index: 1;
	transform: translateY(calc(-100% - ${GRID_UNIT_10}));
	pointer-events: auto;
	overflow: visible;
	width: max-content;
}

@keyframes collaborators-overlay-cursor-blink {
	0%, 45% { opacity: 1; }
	55%, 95% { opacity: 0; }
	100% { opacity: 1; }
}
.collaborators-overlay-cursor-highlighted .collaborators-overlay-user-cursor {
	animation: collaborators-overlay-cursor-highlight 0.6s ease-in-out 3;
}
.collaborators-overlay-cursor-highlighted .collaborators-overlay-user-label {
	animation: collaborators-overlay-label-highlight 0.6s ease-in-out 3;
}
@keyframes collaborators-overlay-cursor-highlight {
	0%, 100% {
		transform: scale(1);
		filter: drop-shadow(0 0 0 transparent);
	}
	50% {
		transform: scale(1.2);
		filter: drop-shadow(0 0 8px currentColor);
	}
}
@keyframes collaborators-overlay-label-highlight {
	0%, 100% {
		transform: translate(-11px, -100%) scale(1);
		filter: drop-shadow(0 0 0 transparent);
	}
	50% {
		transform: translate(-11px, -100%) scale(1.1);
		filter: drop-shadow(0 0 6px currentColor);
	}
}
.block-editor-block-list__block.is-collaborator-selected:not(:focus)::after {
	content: "";
	position: absolute;
	pointer-events: none;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	outline-color: var(--collaborator-outline-color);
	outline-style: solid;
	outline-width: calc(var(--wp-admin-border-width-focus) / var(--wp-block-editor-iframe-zoom-out-scale, 1));
	outline-offset: calc(-1 * var(--wp-admin-border-width-focus) / var(--wp-block-editor-iframe-zoom-out-scale, 1));
	box-shadow: inset 0 0 0 calc((var(--wp-admin-border-width-focus) / var(--wp-block-editor-iframe-zoom-out-scale, 1)) + 0.5px) rgba(${WHITE2}, 0.7);
	z-index: 1;
}
@media (prefers-reduced-motion: reduce) {
	.collaborators-overlay-user-label,
	.collaborators-overlay-user-cursor {
		animation: none;
	}
}
`;

  // packages/editor/build-module/components/collaborators-overlay/timing-utils.mjs
  function setDelayedInterval(callback, delayMs) {
    let timerHandle = null;
    const runner = () => {
      try {
        callback();
      } catch {
      }
      timerHandle = setTimeout(runner, delayMs);
    };
    timerHandle = setTimeout(runner, delayMs);
    return () => {
      if (timerHandle) {
        clearTimeout(timerHandle);
      }
    };
  }

  // packages/editor/build-module/components/collaborators-overlay/use-block-highlighting.mjs
  var import_core_data112 = __toESM(require_core_data(), 1);
  var import_element294 = __toESM(require_element(), 1);

  // packages/editor/build-module/components/collaborators-overlay/use-debounced-recompute.mjs
  var import_element293 = __toESM(require_element(), 1);
  function useDebouncedRecompute(delayMs) {
    const [recomputeToken, setRecomputeToken] = (0, import_element293.useState)(0);
    const timeoutRef = (0, import_element293.useRef)(null);
    const rerenderAfterDelay = (0, import_element293.useCallback)(() => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      timeoutRef.current = setTimeout(() => {
        setRecomputeToken((t4) => t4 + 1);
      }, delayMs);
      return () => {
        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current);
        }
      };
    }, [delayMs]);
    return [recomputeToken, rerenderAfterDelay];
  }

  // packages/editor/build-module/components/collaborators-overlay/use-block-highlighting.mjs
  var { useActiveCollaborators, useResolvedSelection } = unlock(import_core_data112.privateApis);
  var { SelectionType } = unlock(import_core_data112.privateApis);
  function useBlockHighlighting(overlayElement, blockEditorDocument, postId2, postType2, delayMs) {
    const highlightedBlockIds = (0, import_element294.useRef)(/* @__PURE__ */ new Set());
    const userStates = useActiveCollaborators(
      postId2 ?? null,
      postType2 ?? null
    );
    const resolveSelection = useResolvedSelection(
      postId2 ?? null,
      postType2 ?? null
    );
    const [highlights, setHighlights] = (0, import_element294.useState)(
      []
    );
    const [recomputeToken, rerenderHighlightsAfterDelay] = useDebouncedRecompute(delayMs);
    (0, import_element294.useEffect)(() => {
      if (!blockEditorDocument) {
        setHighlights([]);
        return;
      }
      const currentHighlightedIds = highlightedBlockIds.current;
      const seen = /* @__PURE__ */ new Set();
      const blocksToHighlight = userStates.filter((userState) => {
        const isWholeBlockSelected = userState.editorState?.selection?.type === SelectionType.WholeBlock;
        return !userState.isMe && isWholeBlockSelected;
      }).map((userState) => {
        let localClientId;
        try {
          ({ localClientId } = resolveSelection(
            userState.editorState?.selection
          ));
        } catch {
          return null;
        }
        if (!localClientId) {
          return null;
        }
        return {
          blockId: localClientId,
          color: userState.isMe ? "var(--wp-admin-theme-color)" : getAvatarBorderColor(userState.collaboratorInfo.id),
          userName: userState.collaboratorInfo.name,
          avatarUrl: getAvatarUrl(
            userState.collaboratorInfo.avatar_urls
          )
        };
      }).filter((block) => {
        if (!block) {
          return false;
        }
        if (seen.has(block.blockId)) {
          return false;
        }
        seen.add(block.blockId);
        return true;
      });
      const selectedBlockIds = new Set(
        blocksToHighlight.map((block) => block.blockId)
      );
      for (const blockId of currentHighlightedIds) {
        if (!selectedBlockIds.has(blockId)) {
          const blockElement = getBlockElementById(
            blockEditorDocument,
            blockId
          );
          if (blockElement) {
            blockElement.classList.remove("is-collaborator-selected");
            blockElement.style.removeProperty(
              "--collaborator-outline-color"
            );
          }
          currentHighlightedIds.delete(blockId);
        }
      }
      const results = [];
      const overlayRect = overlayElement?.getBoundingClientRect() ?? null;
      blocksToHighlight.forEach((block) => {
        const { color, blockId, userName, avatarUrl } = block;
        const blockElement = getBlockElementById(
          blockEditorDocument,
          blockId
        );
        if (!blockElement) {
          return;
        }
        blockElement.classList.add("is-collaborator-selected");
        blockElement.style.setProperty(
          "--collaborator-outline-color",
          color
        );
        currentHighlightedIds.add(blockId);
        if (overlayRect) {
          const blockRect = blockElement.getBoundingClientRect();
          results.push({
            blockId,
            userName,
            avatarUrl,
            color,
            x: blockRect.left - overlayRect.left,
            y: blockRect.top - overlayRect.top
          });
        }
      });
      setHighlights(results);
      return () => {
        for (const blockId of currentHighlightedIds) {
          const el = getBlockElementById(blockEditorDocument, blockId);
          if (el) {
            el.classList.remove("is-collaborator-selected");
            el.style.removeProperty("--collaborator-outline-color");
          }
        }
        currentHighlightedIds.clear();
      };
    }, [
      userStates,
      blockEditorDocument,
      overlayElement,
      recomputeToken,
      resolveSelection
    ]);
    return { highlights, rerenderHighlightsAfterDelay };
  }
  var getBlockElementById = (blockEditorDocument, blockId) => {
    return blockEditorDocument.querySelector(`[data-block="${blockId}"]`);
  };

  // packages/editor/build-module/components/collaborators-overlay/use-render-cursors.mjs
  var import_core_data114 = __toESM(require_core_data(), 1);
  var import_data208 = __toESM(require_data(), 1);
  var import_element295 = __toESM(require_element(), 1);
  var import_preferences20 = __toESM(require_preferences(), 1);

  // packages/editor/build-module/components/collaborators-overlay/compute-selection.mjs
  var import_core_data113 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/collaborators-overlay/cursor-dom-utils.mjs
  var MAX_NODE_OFFSET_COUNT = 500;
  var getCursorPosition = (absolutePositionIndex, blockElement, editorDocument, overlayRect) => {
    if (absolutePositionIndex === null || !blockElement) {
      return null;
    }
    return getOffsetPositionInBlock(
      blockElement,
      absolutePositionIndex,
      editorDocument,
      overlayRect
    ) ?? null;
  };
  var getOffsetPositionInBlock = (blockElement, charOffset, editorDocument, overlayRect) => {
    const { node, offset: offset4 } = findInnerBlockOffset(
      blockElement,
      charOffset,
      editorDocument
    );
    const cursorRange = editorDocument.createRange();
    try {
      cursorRange.setStart(node, offset4);
    } catch {
      return null;
    }
    cursorRange.collapse(true);
    const cursorRect = cursorRange.getBoundingClientRect();
    const blockRect = blockElement.getBoundingClientRect();
    let cursorX = 0;
    let cursorY = 0;
    if (cursorRect.x === 0 && cursorRect.y === 0 && cursorRect.width === 0 && cursorRect.height === 0) {
      cursorX = blockRect.left - overlayRect.left;
      cursorY = blockRect.top - overlayRect.top;
    } else {
      cursorX = cursorRect.left - overlayRect.left;
      cursorY = cursorRect.top - overlayRect.top;
    }
    let cursorHeight = cursorRect.height;
    if (cursorHeight === 0) {
      const view = editorDocument.defaultView ?? window;
      cursorHeight = parseInt(view.getComputedStyle(blockElement).lineHeight, 10) || blockRect.height;
    }
    return {
      x: cursorX,
      y: cursorY,
      height: cursorHeight
    };
  };
  var getSelectionRects = (blockElement, startOffset, endOffset, editorDocument, overlayRect) => {
    let normalizedStart = startOffset;
    let normalizedEnd = endOffset;
    if (normalizedStart > normalizedEnd) {
      [normalizedStart, normalizedEnd] = [normalizedEnd, normalizedStart];
    }
    const startPos = findInnerBlockOffset(
      blockElement,
      normalizedStart,
      editorDocument
    );
    const endPos = findInnerBlockOffset(
      blockElement,
      normalizedEnd,
      editorDocument
    );
    const range = editorDocument.createRange();
    try {
      range.setStart(startPos.node, startPos.offset);
      range.setEnd(endPos.node, endPos.offset);
    } catch {
      return null;
    }
    const clientRects = range.getClientRects();
    const rects = [];
    for (const rect of clientRects) {
      if (rect.width === 0 && rect.height === 0) {
        continue;
      }
      const x2 = rect.left - overlayRect.left;
      const y3 = rect.top - overlayRect.top;
      const isDuplicate = rects.some(
        (r4) => r4.x === x2 && r4.y === y3 && r4.width === rect.width && r4.height === rect.height
      );
      if (isDuplicate) {
        continue;
      }
      rects.push({
        x: x2,
        y: y3,
        width: rect.width,
        height: rect.height
      });
    }
    return rects.length > 0 ? rects : null;
  };
  var getFullBlockSelectionRects = (blockElement, editorDocument, overlayRect) => {
    const range = editorDocument.createRange();
    range.selectNodeContents(blockElement);
    const clientRects = range.getClientRects();
    const rects = [];
    for (const rect of clientRects) {
      if (rect.width === 0 && rect.height === 0) {
        continue;
      }
      rects.push({
        x: rect.left - overlayRect.left,
        y: rect.top - overlayRect.top,
        width: rect.width,
        height: rect.height
      });
    }
    if (rects.length === 0) {
      const blockRect = blockElement.getBoundingClientRect();
      if (blockRect.width > 0 && blockRect.height > 0) {
        rects.push({
          x: blockRect.left - overlayRect.left,
          y: blockRect.top - overlayRect.top,
          width: blockRect.width,
          height: blockRect.height
        });
      }
    }
    return rects;
  };
  var getBlocksBetween = (startBlockId, endBlockId, editorDocument) => {
    const allBlocks = editorDocument.querySelectorAll("[data-block]");
    let startIndex = -1;
    let endIndex = -1;
    for (let i3 = 0; i3 < allBlocks.length; i3++) {
      const blockId = allBlocks[i3].getAttribute("data-block");
      if (blockId === startBlockId) {
        startIndex = i3;
      }
      if (blockId === endBlockId) {
        endIndex = i3;
      }
    }
    if (startIndex === -1 || endIndex === -1) {
      return [];
    }
    if (startIndex > endIndex) {
      [startIndex, endIndex] = [endIndex, startIndex];
    }
    const result = [];
    for (let i3 = startIndex + 1; i3 < endIndex; i3++) {
      result.push(allBlocks[i3]);
    }
    return result;
  };
  var findInnerBlockOffset = (blockElement, offset4, editorDocument) => {
    const treeWalker = editorDocument.createTreeWalker(
      blockElement,
      NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT
      // eslint-disable-line no-bitwise
    );
    let currentOffset = 0;
    let lastTextNode = null;
    let node = null;
    let nodeCount = 1;
    while (node = treeWalker.nextNode()) {
      nodeCount++;
      if (nodeCount > MAX_NODE_OFFSET_COUNT) {
        if (lastTextNode) {
          return { node: lastTextNode, offset: 0 };
        }
        return { node: blockElement, offset: 0 };
      }
      const nodeLength = node.nodeValue?.length ?? 0;
      if (node.nodeType === Node.ELEMENT_NODE) {
        if (node.nodeName === "BR") {
          if (currentOffset + 1 >= offset4) {
            const nodeAfterBr = treeWalker.nextNode();
            if (nodeAfterBr?.nodeType === Node.TEXT_NODE) {
              return { node: nodeAfterBr, offset: 0 };
            } else if (lastTextNode) {
              return {
                node: lastTextNode,
                offset: lastTextNode.nodeValue?.length ?? 0
              };
            }
            return { node: blockElement, offset: 0 };
          }
          currentOffset += 1;
          continue;
        } else {
          continue;
        }
      }
      if (nodeLength === 0) {
        continue;
      }
      if (currentOffset + nodeLength >= offset4) {
        return { node, offset: offset4 - currentOffset };
      }
      currentOffset += nodeLength;
      if (node.nodeType === Node.TEXT_NODE) {
        lastTextNode = node;
      }
    }
    if (lastTextNode && lastTextNode.nodeValue?.length) {
      return { node: lastTextNode, offset: lastTextNode.nodeValue.length };
    }
    return { node: blockElement, offset: 0 };
  };
  var isNodeBefore = (a3, b3) => a3.compareDocumentPosition(b3) === Node.DOCUMENT_POSITION_FOLLOWING;

  // packages/editor/build-module/components/collaborators-overlay/compute-selection.mjs
  var { SelectionDirection, SelectionType: SelectionType2 } = unlock(
    import_core_data113.privateApis
  );
  function resolveTargetElement(editorDocument, resolvedSelection) {
    if (!resolvedSelection.localClientId) {
      return null;
    }
    const blockElement = editorDocument.querySelector(
      `[data-block="${resolvedSelection.localClientId}"]`
    );
    if (!blockElement || !resolvedSelection.attributeKey) {
      return blockElement;
    }
    const attrKey = CSS.escape(resolvedSelection.attributeKey);
    return blockElement.querySelector(
      `[data-wp-block-attribute-key="${attrKey}"]`
    ) ?? blockElement;
  }
  function computeSelectionVisual(selection, start2, end, overlayContext) {
    if (selection.type === SelectionType2.None || selection.type === SelectionType2.WholeBlock) {
      return {};
    }
    if (selection.type === SelectionType2.Cursor) {
      return computeCursorOnly(start2, overlayContext);
    }
    if (!end) {
      return {};
    }
    return computeTextSelection(selection, start2, end, overlayContext);
  }
  function computeCursorOnly(start2, overlayContext) {
    if (!start2.localClientId) {
      return {};
    }
    const targetElement = resolveTargetElement(
      overlayContext.editorDocument,
      start2
    );
    return {
      coords: getCursorPosition(
        start2.richTextOffset,
        targetElement,
        overlayContext.editorDocument,
        overlayContext.overlayRect
      )
    };
  }
  function computeTextSelection(selection, start2, end, overlayContext) {
    if (!start2.localClientId || !end.localClientId || start2.richTextOffset === null || end.richTextOffset === null) {
      return {};
    }
    const isReverse = selection.selectionDirection === SelectionDirection.Backward;
    const activeEnd = isReverse ? start2 : end;
    let allRects;
    let activeEndBlock = null;
    if (selection.type === SelectionType2.SelectionInOneBlock) {
      const result = computeSingleBlockRects(start2, end, overlayContext);
      allRects = result.rects;
      activeEndBlock = result.blockElement;
    } else {
      const result = computeMultiBlockRects(start2, end, overlayContext);
      allRects = result.rects;
      activeEndBlock = activeEnd.localClientId === result.firstBlockClientId ? result.firstBlock : result.lastBlock;
    }
    if (allRects.length > 0) {
      return {
        coords: getCursorPosition(
          activeEnd.richTextOffset,
          activeEndBlock,
          overlayContext.editorDocument,
          overlayContext.overlayRect
        ),
        selectionRects: allRects
      };
    }
    const startBlock = resolveTargetElement(
      overlayContext.editorDocument,
      start2
    );
    return {
      coords: getCursorPosition(
        start2.richTextOffset,
        startBlock,
        overlayContext.editorDocument,
        overlayContext.overlayRect
      )
    };
  }
  function computeSingleBlockRects(start2, end, overlayContext) {
    const blockElement = resolveTargetElement(
      overlayContext.editorDocument,
      start2
    );
    if (!blockElement || start2.richTextOffset === null || end.richTextOffset === null) {
      return { rects: [], blockElement: null };
    }
    return {
      rects: getSelectionRects(
        blockElement,
        start2.richTextOffset,
        end.richTextOffset,
        overlayContext.editorDocument,
        overlayContext.overlayRect
      ) ?? [],
      blockElement
    };
  }
  function computeMultiBlockRects(start2, end, overlayContext) {
    let docFirst = start2;
    let docLast = end;
    let firstBlock = resolveTargetElement(
      overlayContext.editorDocument,
      docFirst
    );
    let lastBlock = resolveTargetElement(
      overlayContext.editorDocument,
      docLast
    );
    if (firstBlock && lastBlock && isNodeBefore(lastBlock, firstBlock)) {
      docFirst = end;
      docLast = start2;
      [firstBlock, lastBlock] = [lastBlock, firstBlock];
    }
    if (!firstBlock || !lastBlock || docFirst.richTextOffset === null || docLast.richTextOffset === null || !docFirst.localClientId || !docLast.localClientId) {
      return {
        rects: [],
        firstBlock: null,
        lastBlock: null,
        firstBlockClientId: null
      };
    }
    const allRects = [];
    const startRects = getSelectionRects(
      firstBlock,
      docFirst.richTextOffset,
      Number.MAX_SAFE_INTEGER,
      overlayContext.editorDocument,
      overlayContext.overlayRect
    );
    if (startRects) {
      allRects.push(...startRects);
    }
    const intermediateBlocks = getBlocksBetween(
      docFirst.localClientId,
      docLast.localClientId,
      overlayContext.editorDocument
    );
    for (const intermediateBlock of intermediateBlocks) {
      const rects = getFullBlockSelectionRects(
        intermediateBlock,
        overlayContext.editorDocument,
        overlayContext.overlayRect
      );
      allRects.push(...rects);
    }
    const endRects = getSelectionRects(
      lastBlock,
      0,
      docLast.richTextOffset,
      overlayContext.editorDocument,
      overlayContext.overlayRect
    );
    if (endRects) {
      allRects.push(...endRects);
    }
    return {
      rects: allRects,
      firstBlock,
      lastBlock,
      firstBlockClientId: docFirst.localClientId
    };
  }

  // packages/editor/build-module/components/collaborators-overlay/use-render-cursors.mjs
  var { useActiveCollaborators: useActiveCollaborators2, useResolvedSelection: useResolvedSelection2 } = unlock(import_core_data114.privateApis);
  var { SelectionType: SelectionType3 } = unlock(import_core_data114.privateApis);
  function useRenderCursors(overlayElement, blockEditorDocument, postId2, postType2, delayMs) {
    const sortedUsers = useActiveCollaborators2(
      postId2 ?? null,
      postType2 ?? null
    );
    const resolveSelection = useResolvedSelection2(
      postId2 ?? null,
      postType2 ?? null
    );
    const showOwnCursor = (0, import_data208.useSelect)(
      (select9) => select9(import_preferences20.store).get("core", "showCollaborationCursor"),
      []
    );
    const [cursorPositions, setCursorPositions] = (0, import_element295.useState)(
      []
    );
    const [recomputeToken, rerenderCursorsAfterDelay] = useDebouncedRecompute(delayMs);
    (0, import_element295.useEffect)(() => {
      if (!overlayElement || !blockEditorDocument) {
        setCursorPositions([]);
        return;
      }
      const overlayRect = overlayElement.getBoundingClientRect();
      const overlayContext = {
        editorDocument: blockEditorDocument,
        overlayRect
      };
      const results = [];
      const hasOtherCollaborators = sortedUsers.some(
        (u3) => !u3.isMe
      );
      sortedUsers.forEach((user) => {
        if (user.isMe && (!showOwnCursor || !hasOtherCollaborators)) {
          return;
        }
        const selection = user.editorState?.selection ?? {
          type: SelectionType3.None
        };
        let start2 = {
          richTextOffset: null,
          localClientId: null,
          attributeKey: null
        };
        let end;
        if (selection.type === SelectionType3.Cursor) {
          try {
            start2 = resolveSelection(selection);
          } catch {
            return;
          }
        } else if (selection.type === SelectionType3.SelectionInOneBlock || selection.type === SelectionType3.SelectionInMultipleBlocks) {
          try {
            start2 = resolveSelection({
              type: SelectionType3.Cursor,
              cursorPosition: selection.cursorStartPosition
            });
            end = resolveSelection({
              type: SelectionType3.Cursor,
              cursorPosition: selection.cursorEndPosition
            });
          } catch {
            return;
          }
        }
        const userName = user.collaboratorInfo.name;
        const clientId = user.clientId;
        const color = user.isMe ? "var(--wp-admin-theme-color)" : getAvatarBorderColor(user.collaboratorInfo.id);
        const avatarUrl = getAvatarUrl(user.collaboratorInfo.avatar_urls);
        const selectionVisual = computeSelectionVisual(
          selection,
          start2,
          end,
          overlayContext
        );
        if (selectionVisual.coords) {
          const cursorData = {
            userName,
            clientId,
            color,
            avatarUrl,
            isMe: user.isMe,
            ...selectionVisual.coords
          };
          if (selectionVisual.selectionRects) {
            cursorData.selectionRects = selectionVisual.selectionRects;
          }
          results.push(cursorData);
        }
      });
      setCursorPositions(results);
    }, [
      blockEditorDocument,
      resolveSelection,
      overlayElement,
      sortedUsers,
      showOwnCursor,
      recomputeToken
    ]);
    return { cursors: cursorPositions, rerenderCursorsAfterDelay };
  }

  // packages/editor/build-module/components/collaborators-overlay/overlay.mjs
  var import_jsx_runtime499 = __toESM(require_jsx_runtime(), 1);
  var RERENDER_DELAY_MS = 500;
  var CURSOR_REDRAW_INTERVAL_MS = 1e4;
  function Overlay({
    blockEditorDocument,
    postId: postId2,
    postType: postType2,
    cursorRegistry
  }) {
    const [overlayElement, setOverlayElement] = (0, import_element296.useState)(null);
    const { cursors, rerenderCursorsAfterDelay } = useRenderCursors(
      overlayElement,
      blockEditorDocument ?? null,
      postId2 ?? null,
      postType2 ?? null,
      RERENDER_DELAY_MS
    );
    const { highlights, rerenderHighlightsAfterDelay } = useBlockHighlighting(
      overlayElement,
      blockEditorDocument ?? null,
      postId2 ?? null,
      postType2 ?? null,
      RERENDER_DELAY_MS
    );
    const onResize = (0, import_element296.useCallback)(() => {
      rerenderCursorsAfterDelay();
      rerenderHighlightsAfterDelay();
    }, [rerenderCursorsAfterDelay, rerenderHighlightsAfterDelay]);
    const resizeObserverRef = (0, import_compose67.useResizeObserver)(onResize);
    (0, import_element296.useEffect)(() => {
      const cleanupCursors = rerenderCursorsAfterDelay();
      const cleanupHighlights = rerenderHighlightsAfterDelay();
      return () => {
        cleanupCursors();
        cleanupHighlights();
      };
    }, [rerenderCursorsAfterDelay, rerenderHighlightsAfterDelay]);
    (0, import_element296.useEffect)(() => {
      if (cursors.length === 0) {
        return;
      }
      return setDelayedInterval(
        rerenderCursorsAfterDelay,
        CURSOR_REDRAW_INTERVAL_MS
      );
    }, [cursors.length, rerenderCursorsAfterDelay]);
    const mergedRef = (0, import_compose67.useMergeRefs)([
      setOverlayElement,
      resizeObserverRef
    ]);
    const cursorRefsMap = (0, import_element296.useRef)(/* @__PURE__ */ new Map());
    (0, import_element296.useEffect)(() => {
      if (!cursorRegistry) {
        return;
      }
      const refs = cursorRefsMap.current;
      const currentIds = new Set(cursors.map((c6) => c6.clientId));
      for (const id of refs.keys()) {
        if (!currentIds.has(id)) {
          cursorRegistry.unregisterCursor(id);
          refs.delete(id);
        }
      }
      for (const [id, el] of refs.entries()) {
        cursorRegistry.registerCursor(id, el);
      }
      return () => cursorRegistry.removeAll();
    }, [cursors, cursorRegistry]);
    const setCursorRef = (0, import_element296.useCallback)(
      (clientId) => (el) => {
        if (el) {
          cursorRefsMap.current.set(clientId, el);
        } else {
          cursorRefsMap.current.delete(clientId);
        }
      },
      []
    );
    return /* @__PURE__ */ (0, import_jsx_runtime499.jsxs)("div", { className: "collaborators-overlay-full", ref: mergedRef, children: [
      /* @__PURE__ */ (0, import_jsx_runtime499.jsx)("style", { children: AVATAR_IFRAME_STYLES + OVERLAY_IFRAME_STYLES }),
      cursors.map((cursor) => /* @__PURE__ */ (0, import_jsx_runtime499.jsxs)("div", { children: [
        !cursor.isMe && cursor.selectionRects?.map((rect, index2) => /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
          "div",
          {
            className: "collaborators-overlay-selection-rect",
            style: {
              left: `${rect.x}px`,
              top: `${rect.y}px`,
              width: `${rect.width}px`,
              height: `${rect.height}px`,
              backgroundColor: cursor.color
            }
          },
          `${cursor.clientId}-sel-${index2}`
        )),
        /* @__PURE__ */ (0, import_jsx_runtime499.jsxs)(
          "div",
          {
            ref: setCursorRef(cursor.clientId),
            className: "collaborators-overlay-user",
            style: {
              left: `${cursor.x}px`,
              top: `${cursor.y}px`
            },
            children: [
              !cursor.isMe && /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
                "div",
                {
                  className: "collaborators-overlay-user-cursor",
                  style: {
                    backgroundColor: cursor.color,
                    height: `${cursor.height}px`
                  }
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
                component_default,
                {
                  className: "collaborators-overlay-user-label",
                  variant: "badge",
                  size: "small",
                  src: cursor.avatarUrl,
                  name: cursor.userName,
                  label: cursor.isMe ? (0, import_i18n297.__)("You") : void 0,
                  borderColor: cursor.color
                }
              )
            ]
          }
        )
      ] }, cursor.clientId)),
      highlights.map((highlight) => /* @__PURE__ */ (0, import_jsx_runtime499.jsx)(
        component_default,
        {
          className: "collaborators-overlay-block-label",
          variant: "badge",
          size: "small",
          src: highlight.avatarUrl,
          name: highlight.userName,
          borderColor: highlight.color,
          style: {
            left: `${highlight.x}px`,
            top: `${highlight.y}px`
          }
        },
        highlight.blockId
      ))
    ] });
  }

  // packages/editor/build-module/components/collaborators-overlay/index.mjs
  var import_jsx_runtime500 = __toESM(require_jsx_runtime(), 1);
  var { BlockCanvasCover } = unlock(import_block_editor73.privateApis);
  function CollaboratorsOverlay({
    postId: postId2,
    postType: postType2,
    cursorRegistry
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime500.jsx)(BlockCanvasCover.Fill, { children: ({
      containerRef
    }) => /* @__PURE__ */ (0, import_jsx_runtime500.jsx)(
      Overlay,
      {
        blockEditorDocument: containerRef.current?.ownerDocument,
        postId: postId2,
        postType: postType2,
        cursorRegistry
      }
    ) });
  }

  // packages/editor/build-module/components/collaborators-presence/index.mjs
  var import_jsx_runtime501 = __toESM(require_jsx_runtime(), 1);
  var { useActiveCollaborators: useActiveCollaborators3 } = unlock(import_core_data115.privateApis);
  function CollaboratorsPresence({
    postId: postId2,
    postType: postType2
  }) {
    const activeCollaborators = useActiveCollaborators3(
      postId2,
      postType2
    );
    const otherActiveCollaborators = activeCollaborators.filter(
      (c6) => !c6.isMe
    );
    const collaboratorsForList = (0, import_element297.useMemo)(() => {
      return [...activeCollaborators].sort((a3, b3) => {
        if (a3.isMe && !b3.isMe) {
          return -1;
        }
        if (!a3.isMe && b3.isMe) {
          return 1;
        }
        return 0;
      });
    }, [activeCollaborators]);
    const [cursorRegistry] = (0, import_element297.useState)(createCursorRegistry);
    const [isPopoverVisible, setIsPopoverVisible] = (0, import_element297.useState)(false);
    const [popoverAnchor, setPopoverAnchor] = (0, import_element297.useState)(
      null
    );
    if (otherActiveCollaborators.length === 0) {
      return null;
    }
    const me = activeCollaborators.find((c6) => c6.isMe);
    return /* @__PURE__ */ (0, import_jsx_runtime501.jsxs)(import_jsx_runtime501.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime501.jsxs)("div", { className: "editor-collaborators-presence", children: [
        /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
          import_components248.Button,
          {
            __next40pxDefaultSize: true,
            className: "editor-collaborators-presence__button",
            onClick: () => setIsPopoverVisible(!isPopoverVisible),
            isPressed: isPopoverVisible,
            ref: setPopoverAnchor,
            "aria-label": (0, import_i18n298.sprintf)(
              // translators: %d: number of online collaborators.
              (0, import_i18n298.__)("Collaborators list, %d online"),
              collaboratorsForList.length
            ),
            children: /* @__PURE__ */ (0, import_jsx_runtime501.jsxs)(component_default2, { max: 4, children: [
              me && /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
                component_default,
                {
                  src: getAvatarUrl(
                    me.collaboratorInfo.avatar_urls
                  ),
                  name: me.collaboratorInfo.name,
                  borderColor: "var(--wp-admin-theme-color)",
                  size: "small"
                },
                me.clientId
              ),
              otherActiveCollaborators.map(
                (collaboratorState) => /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
                  component_default,
                  {
                    src: getAvatarUrl(
                      collaboratorState.collaboratorInfo.avatar_urls
                    ),
                    name: collaboratorState.collaboratorInfo.name,
                    borderColor: getAvatarBorderColor(
                      collaboratorState.collaboratorInfo.id
                    ),
                    size: "small"
                  },
                  collaboratorState.clientId
                )
              )
            ] })
          }
        ),
        isPopoverVisible && /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
          CollaboratorsList,
          {
            activeCollaborators: collaboratorsForList,
            popoverAnchor,
            setIsPopoverVisible,
            cursorRegistry
          }
        )
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime501.jsx)(
        CollaboratorsOverlay,
        {
          postId: postId2,
          postType: postType2,
          cursorRegistry
        }
      )
    ] });
  }

  // packages/editor/build-module/components/header/index.mjs
  var import_jsx_runtime502 = __toESM(require_jsx_runtime(), 1);
  function Header5({
    customSaveButton,
    forceIsDirty,
    setEntitiesSavedStatesCallback
  }) {
    const isWideViewport = (0, import_compose68.useViewportMatch)("large");
    const isLargeViewport = (0, import_compose68.useViewportMatch)("medium");
    const isTooNarrowForDocumentBar = (0, import_compose68.useMediaQuery)("(max-width: 403px)");
    const {
      postId: postId2,
      postType: postType2,
      isTextEditor,
      isPublishSidebarOpened: isPublishSidebarOpened2,
      showIconLabels,
      hasFixedToolbar,
      hasBlockSelection,
      hasSectionRootClientId,
      isStylesCanvasActive
    } = (0, import_data209.useSelect)((select9) => {
      const { get: getPreference } = select9(import_preferences21.store);
      const {
        getEditorMode: getEditorMode2,
        getCurrentPostType: getCurrentPostType2,
        getCurrentPostId: getCurrentPostId2,
        isPublishSidebarOpened: _isPublishSidebarOpened
      } = select9(store);
      const { getStylesPath: getStylesPath2, getShowStylebook: getShowStylebook2 } = unlock(
        select9(store)
      );
      const { getBlockSelectionStart: getBlockSelectionStart2, getSectionRootClientId } = unlock(
        select9(import_block_editor74.store)
      );
      return {
        postId: getCurrentPostId2(),
        postType: getCurrentPostType2(),
        isTextEditor: getEditorMode2() === "text",
        isPublishSidebarOpened: _isPublishSidebarOpened(),
        showIconLabels: getPreference("core", "showIconLabels"),
        hasFixedToolbar: getPreference("core", "fixedToolbar"),
        hasBlockSelection: !!getBlockSelectionStart2(),
        hasSectionRootClientId: !!getSectionRootClientId(),
        isStylesCanvasActive: !!getStylesPath2()?.startsWith("/revisions") || getShowStylebook2()
      };
    }, []);
    const canBeZoomedOut = ["post", "page", "wp_template"].includes(postType2) && hasSectionRootClientId;
    const [isBlockToolsCollapsed, setIsBlockToolsCollapsed] = (0, import_element298.useState)(true);
    const hasCenter = !isTooNarrowForDocumentBar && (!hasFixedToolbar || hasFixedToolbar && (!hasBlockSelection || isBlockToolsCollapsed));
    return /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(
      HeaderSkeleton,
      {
        toolbar: /* @__PURE__ */ (0, import_jsx_runtime502.jsxs)(import_jsx_runtime502.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(
            document_tools_default,
            {
              disableBlockTools: isStylesCanvasActive || isTextEditor
            }
          ),
          hasFixedToolbar && isLargeViewport && /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(
            CollapsibleBlockToolbar,
            {
              isCollapsed: isBlockToolsCollapsed,
              onToggle: setIsBlockToolsCollapsed
            }
          )
        ] }),
        center: hasCenter ? /* @__PURE__ */ (0, import_jsx_runtime502.jsxs)(import_jsx_runtime502.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(
            CollaboratorsPresence,
            {
              postType: postType2,
              postId: postId2
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(DocumentBar, {})
        ] }) : void 0,
        settings: /* @__PURE__ */ (0, import_jsx_runtime502.jsxs)(import_jsx_runtime502.Fragment, { children: [
          !hasCenter && !isTooNarrowForDocumentBar && /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(
            CollaboratorsPresence,
            {
              postType: postType2,
              postId: postId2
            }
          ),
          !customSaveButton && !isPublishSidebarOpened2 && /*
          * This button isn't completely hidden by the publish sidebar.
          * We can't hide the whole toolbar when the publish sidebar is open because
          * we want to prevent mounting/unmounting the PostPublishButtonOrToggle DOM node.
          * We track that DOM node to return focus to the PostPublishButtonOrToggle
          * when the publish sidebar has been closed.
          */
          /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(PostSavedState, { forceIsDirty }),
          /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(PostViewLink, {}),
          /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(
            PreviewDropdown,
            {
              forceIsAutosaveable: forceIsDirty,
              disabled: isStylesCanvasActive
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(
            PostPreviewButton,
            {
              className: "editor-header__post-preview-button",
              forceIsAutosaveable: forceIsDirty
            }
          ),
          isWideViewport && canBeZoomedOut && /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(zoom_out_toggle_default, { disabled: isStylesCanvasActive }),
          (isWideViewport || !showIconLabels) && /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(pinned_items_default.Slot, { scope: "core" }),
          !customSaveButton && /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(
            PostPublishButtonOrToggle,
            {
              forceIsDirty,
              setEntitiesSavedStatesCallback
            }
          ),
          customSaveButton,
          /* @__PURE__ */ (0, import_jsx_runtime502.jsx)(MoreMenu, {})
        ] })
      }
    );
  }
  var header_default2 = Header5;

  // packages/editor/build-module/components/inserter-sidebar/index.mjs
  var import_data210 = __toESM(require_data(), 1);
  var import_block_editor75 = __toESM(require_block_editor(), 1);
  var import_compose69 = __toESM(require_compose(), 1);
  var import_element299 = __toESM(require_element(), 1);
  var import_preferences22 = __toESM(require_preferences(), 1);
  var import_keycodes18 = __toESM(require_keycodes(), 1);
  var import_jsx_runtime503 = __toESM(require_jsx_runtime(), 1);
  var { PrivateInserterLibrary } = unlock(import_block_editor75.privateApis);
  function InserterSidebar() {
    const {
      blockSectionRootClientId,
      inserterSidebarToggleRef: inserterSidebarToggleRef2,
      inserter,
      showMostUsedBlocks,
      sidebarIsOpened
    } = (0, import_data210.useSelect)((select9) => {
      const {
        getInserterSidebarToggleRef: getInserterSidebarToggleRef2,
        getInserter: getInserter2,
        isPublishSidebarOpened: isPublishSidebarOpened2
      } = unlock(select9(store));
      const { getBlockRootClientId: getBlockRootClientId2, isZoomOut, getSectionRootClientId } = unlock(select9(import_block_editor75.store));
      const { get } = select9(import_preferences22.store);
      const { getActiveComplementaryArea: getActiveComplementaryArea2 } = select9(store3);
      const getBlockSectionRootClientId = () => {
        if (isZoomOut()) {
          const sectionRootClientId = getSectionRootClientId();
          if (sectionRootClientId) {
            return sectionRootClientId;
          }
        }
        return getBlockRootClientId2();
      };
      return {
        inserterSidebarToggleRef: getInserterSidebarToggleRef2(),
        inserter: getInserter2(),
        showMostUsedBlocks: get("core", "mostUsedBlocks"),
        blockSectionRootClientId: getBlockSectionRootClientId(),
        sidebarIsOpened: !!(getActiveComplementaryArea2("core") || isPublishSidebarOpened2())
      };
    }, []);
    const { setIsInserterOpened: setIsInserterOpened2 } = (0, import_data210.useDispatch)(store);
    const { disableComplementaryArea: disableComplementaryArea2 } = (0, import_data210.useDispatch)(store3);
    const isMobileViewport = (0, import_compose69.useViewportMatch)("medium", "<");
    const libraryRef = (0, import_element299.useRef)();
    const closeInserterSidebar = (0, import_element299.useCallback)(() => {
      setIsInserterOpened2(false);
      inserterSidebarToggleRef2.current?.focus();
    }, [inserterSidebarToggleRef2, setIsInserterOpened2]);
    const closeOnEscape = (0, import_element299.useCallback)(
      (event) => {
        if (event.keyCode === import_keycodes18.ESCAPE && !event.defaultPrevented) {
          event.preventDefault();
          closeInserterSidebar();
        }
      },
      [closeInserterSidebar]
    );
    const inserterContents = /* @__PURE__ */ (0, import_jsx_runtime503.jsx)("div", { className: "editor-inserter-sidebar__content", children: /* @__PURE__ */ (0, import_jsx_runtime503.jsx)(
      PrivateInserterLibrary,
      {
        showMostUsedBlocks,
        showInserterHelpPanel: true,
        shouldFocusBlock: isMobileViewport,
        rootClientId: blockSectionRootClientId ?? inserter.rootClientId,
        __experimentalInsertionIndex: inserter.insertionIndex,
        onSelect: inserter.onSelect,
        __experimentalInitialTab: inserter.tab,
        __experimentalInitialCategory: inserter.category,
        __experimentalFilterValue: inserter.filterValue,
        onPatternCategorySelection: sidebarIsOpened ? () => disableComplementaryArea2("core") : void 0,
        ref: libraryRef,
        onClose: closeInserterSidebar
      }
    ) });
    return (
      // eslint-disable-next-line jsx-a11y/no-static-element-interactions
      /* @__PURE__ */ (0, import_jsx_runtime503.jsx)("div", { onKeyDown: closeOnEscape, className: "editor-inserter-sidebar", children: inserterContents })
    );
  }

  // packages/editor/build-module/components/list-view-sidebar/index.mjs
  var import_block_editor76 = __toESM(require_block_editor(), 1);
  var import_compose70 = __toESM(require_compose(), 1);
  var import_data211 = __toESM(require_data(), 1);
  var import_dom26 = __toESM(require_dom(), 1);
  var import_element300 = __toESM(require_element(), 1);
  var import_i18n300 = __toESM(require_i18n(), 1);
  var import_keyboard_shortcuts9 = __toESM(require_keyboard_shortcuts(), 1);
  var import_keycodes19 = __toESM(require_keycodes(), 1);

  // packages/editor/build-module/components/list-view-sidebar/list-view-outline.mjs
  var import_components249 = __toESM(require_components(), 1);
  var import_i18n299 = __toESM(require_i18n(), 1);
  var import_jsx_runtime504 = __toESM(require_jsx_runtime(), 1);
  function ListViewOutline() {
    return /* @__PURE__ */ (0, import_jsx_runtime504.jsxs)(import_jsx_runtime504.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime504.jsxs)("div", { className: "editor-list-view-sidebar__outline", children: [
        /* @__PURE__ */ (0, import_jsx_runtime504.jsxs)("div", { children: [
          /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(import_components249.__experimentalText, { children: (0, import_i18n299.__)("Characters:") }),
          /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(import_components249.__experimentalText, { children: /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(CharacterCount, {}) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime504.jsxs)("div", { children: [
          /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(import_components249.__experimentalText, { children: (0, import_i18n299.__)("Words:") }),
          /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(WordCount, {})
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime504.jsxs)("div", { children: [
          /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(import_components249.__experimentalText, { children: (0, import_i18n299.__)("Time to read:") }),
          /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(TimeToRead, {})
        ] })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime504.jsx)(DocumentOutline, {})
    ] });
  }

  // packages/editor/build-module/components/list-view-sidebar/index.mjs
  var import_jsx_runtime505 = __toESM(require_jsx_runtime(), 1);
  var { TabbedSidebar } = unlock(import_block_editor76.privateApis);
  function ListViewSidebar() {
    const { setIsListViewOpened: setIsListViewOpened2 } = (0, import_data211.useDispatch)(store);
    const { getListViewToggleRef: getListViewToggleRef2 } = unlock((0, import_data211.useSelect)(store));
    const focusOnMountRef = (0, import_compose70.useFocusOnMount)("firstElement");
    const closeListView = (0, import_element300.useCallback)(() => {
      setIsListViewOpened2(false);
      getListViewToggleRef2().current?.focus();
    }, [getListViewToggleRef2, setIsListViewOpened2]);
    const closeOnEscape = (0, import_element300.useCallback)(
      (event) => {
        if (event.keyCode === import_keycodes19.ESCAPE && !event.defaultPrevented) {
          event.preventDefault();
          closeListView();
        }
      },
      [closeListView]
    );
    const [dropZoneElement, setDropZoneElement] = (0, import_element300.useState)(null);
    const [tab, setTab] = (0, import_element300.useState)("list-view");
    const sidebarRef = (0, import_element300.useRef)();
    const tabsRef = (0, import_element300.useRef)();
    const listViewRef = (0, import_element300.useRef)();
    const listViewContainerRef = (0, import_compose70.useMergeRefs)([
      focusOnMountRef,
      listViewRef,
      setDropZoneElement
    ]);
    function handleSidebarFocus(currentTab) {
      const tabPanelFocus = import_dom26.focus.tabbable.find(tabsRef.current)[0];
      if (currentTab === "list-view") {
        const listViewApplicationFocus = import_dom26.focus.tabbable.find(
          listViewRef.current
        )[0];
        const listViewFocusArea = sidebarRef.current.contains(
          listViewApplicationFocus
        ) ? listViewApplicationFocus : tabPanelFocus;
        listViewFocusArea.focus();
      } else {
        tabPanelFocus.focus();
      }
    }
    const handleToggleListViewShortcut = (0, import_element300.useCallback)(() => {
      if (sidebarRef.current.contains(
        sidebarRef.current.ownerDocument.activeElement
      )) {
        closeListView();
      } else {
        handleSidebarFocus(tab);
      }
    }, [closeListView, tab]);
    (0, import_keyboard_shortcuts9.useShortcut)("core/editor/toggle-list-view", handleToggleListViewShortcut);
    return (
      // eslint-disable-next-line jsx-a11y/no-static-element-interactions
      /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(
        "div",
        {
          className: "editor-list-view-sidebar",
          onKeyDown: closeOnEscape,
          ref: sidebarRef,
          children: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(
            TabbedSidebar,
            {
              tabs: [
                {
                  name: "list-view",
                  title: (0, import_i18n300._x)("List View", "Post overview"),
                  panel: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)("div", { className: "editor-list-view-sidebar__list-view-container", children: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)("div", { className: "editor-list-view-sidebar__list-view-panel-content", children: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(
                    import_block_editor76.__experimentalListView,
                    {
                      dropZoneElement
                    }
                  ) }) }),
                  panelRef: listViewContainerRef
                },
                {
                  name: "outline",
                  title: (0, import_i18n300._x)("Outline", "Post overview"),
                  panel: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)("div", { className: "editor-list-view-sidebar__list-view-container", children: /* @__PURE__ */ (0, import_jsx_runtime505.jsx)(ListViewOutline, {}) })
                }
              ],
              onClose: closeListView,
              onSelect: (tabName) => setTab(tabName),
              defaultTabId: "list-view",
              ref: tabsRef,
              closeButtonLabel: (0, import_i18n300.__)("Close")
            }
          )
        }
      )
    );
  }

  // packages/editor/build-module/components/post-revisions-preview/revisions-header.mjs
  var import_data213 = __toESM(require_data(), 1);
  var import_components251 = __toESM(require_components(), 1);
  var import_i18n302 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/components/post-revisions-preview/revisions-slider.mjs
  var import_data212 = __toESM(require_data(), 1);
  var import_components250 = __toESM(require_components(), 1);
  var import_core_data116 = __toESM(require_core_data(), 1);
  var import_i18n301 = __toESM(require_i18n(), 1);
  var import_date19 = __toESM(require_date(), 1);
  var import_element301 = __toESM(require_element(), 1);
  var import_compose71 = __toESM(require_compose(), 1);
  var import_jsx_runtime506 = __toESM(require_jsx_runtime(), 1);
  function RevisionsSlider() {
    const {
      revisions: rawRevisions,
      perPage,
      currentRevisionId,
      revisionKey,
      revisionPage: revisionPage2,
      totalRevisions
    } = (0, import_data212.useSelect)((select9) => {
      const {
        getCurrentRevisionId: getCurrentRevisionId2,
        getRevisionPage: getRevisionPage2,
        getPageRevisions: getPageRevisions2,
        getRevisionsPerPage: getRevisionsPerPage2
      } = unlock(select9(store));
      const postType2 = select9(store).getCurrentPostType();
      if (!postType2) {
        return {};
      }
      const entityConfig = select9(import_core_data116.store).getEntityConfig(
        "postType",
        postType2
      );
      const _revisionKey = entityConfig?.revisionKey || "id";
      const _revisionPage = getRevisionPage2();
      return {
        revisions: getPageRevisions2(_revisionPage),
        perPage: getRevisionsPerPage2(),
        currentRevisionId: getCurrentRevisionId2(),
        revisionKey: _revisionKey,
        revisionPage: _revisionPage,
        totalRevisions: select9(store).getCurrentPostRevisionsCount()
      };
    }, []);
    const { setCurrentRevisionId: setCurrentRevisionId2, setRevisionPage: setRevisionPage2 } = unlock(
      (0, import_data212.useDispatch)(store)
    );
    const focusOnMountRef = (0, import_compose71.useFocusOnMount)(true);
    const isLoading = !rawRevisions;
    const totalPages = Math.ceil(totalRevisions / perPage) || 1;
    const revisions = (0, import_element301.useMemo)(
      () => rawRevisions && [...rawRevisions].reverse(),
      [rawRevisions]
    );
    const selectedIndex = revisions?.findIndex(
      (r4) => r4[revisionKey] === currentRevisionId
    );
    const handleSliderChange = (index2) => {
      const revision = revisions?.[index2];
      if (revision) {
        setCurrentRevisionId2(revision[revisionKey]);
      }
    };
    const dateSettings = (0, import_date19.getSettings)();
    const renderTooltipContent = (index2) => {
      const revision = revisions?.[index2];
      if (!revision) {
        return index2;
      }
      return (0, import_date19.dateI18n)(dateSettings.formats.datetime, revision.date);
    };
    const showPagination = totalPages > 1;
    if (isLoading && !showPagination) {
      return /* @__PURE__ */ (0, import_jsx_runtime506.jsx)(import_components250.Spinner, {});
    }
    if (!isLoading && !revisions?.length) {
      return /* @__PURE__ */ (0, import_jsx_runtime506.jsx)("span", { className: "editor-revisions-header__no-revisions", children: (0, import_i18n301.__)("No revisions found.") });
    }
    if (totalRevisions <= 1) {
      return /* @__PURE__ */ (0, import_jsx_runtime506.jsx)("span", { className: "editor-revisions-header__no-revisions", children: (0, import_i18n301.__)("Only one revision found.") });
    }
    const getPageRangeLabel = (page) => {
      const end = totalRevisions - (page - 1) * perPage;
      const start2 = Math.max(1, end - perPage + 1);
      return (0, import_i18n301.sprintf)(
        /* translators: 1: first revision number, 2: last revision number */
        (0, import_i18n301.__)("Revisions %1$s\u2013%2$s"),
        start2,
        end
      );
    };
    const sliderOrSpinner = isLoading || selectedIndex === -1 ? /* @__PURE__ */ (0, import_jsx_runtime506.jsx)(import_components250.Spinner, {}) : /* @__PURE__ */ (0, import_jsx_runtime506.jsx)(
      import_components250.RangeControl,
      {
        ref: focusOnMountRef,
        "aria-valuetext": renderTooltipContent(selectedIndex),
        className: "editor-revisions-header__slider",
        hideLabelFromVision: true,
        label: (0, import_i18n301.__)("Revision"),
        max: revisions?.length - 1,
        min: 0,
        marks: true,
        onChange: handleSliderChange,
        renderTooltipContent,
        value: selectedIndex,
        withInputField: false
      }
    );
    if (!showPagination) {
      return sliderOrSpinner;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime506.jsxs)(Stack, { direction: "row", gap: "sm", align: "center", style: { flex: 1 }, children: [
      /* @__PURE__ */ (0, import_jsx_runtime506.jsx)(
        import_components250.Button,
        {
          icon: chevron_left_default,
          label: revisionPage2 < totalPages ? getPageRangeLabel(revisionPage2 + 1) : (0, import_i18n301.__)("No older revisions"),
          onClick: () => setRevisionPage2(revisionPage2 + 1),
          disabled: isLoading || revisionPage2 >= totalPages,
          size: "compact",
          accessibleWhenDisabled: true
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime506.jsx)(
        "div",
        {
          style: {
            flex: 1,
            minWidth: 0,
            display: "flex",
            justifyContent: "center"
          },
          children: sliderOrSpinner
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime506.jsx)(
        import_components250.Button,
        {
          icon: chevron_right_default,
          label: revisionPage2 > 1 ? getPageRangeLabel(revisionPage2 - 1) : (0, import_i18n301.__)("No newer revisions"),
          onClick: () => setRevisionPage2(revisionPage2 - 1),
          disabled: isLoading || revisionPage2 <= 1,
          size: "compact",
          accessibleWhenDisabled: true
        }
      )
    ] });
  }
  var revisions_slider_default = RevisionsSlider;

  // packages/editor/build-module/components/post-revisions-preview/revisions-header.mjs
  var import_jsx_runtime507 = __toESM(require_jsx_runtime(), 1);
  function RevisionsHeader({ showDiff, onToggleDiff }) {
    const { currentRevisionId, sidebarIsOpened } = (0, import_data213.useSelect)((select9) => {
      return {
        currentRevisionId: unlock(
          select9(store)
        ).getCurrentRevisionId(),
        sidebarIsOpened: !!select9(store3).getActiveComplementaryArea(
          "core"
        )
      };
    }, []);
    const { setCurrentRevisionId: setCurrentRevisionId2, restoreRevision: restoreRevision2 } = unlock(
      (0, import_data213.useDispatch)(store)
    );
    const { enableComplementaryArea: enableComplementaryArea2, disableComplementaryArea: disableComplementaryArea2 } = (0, import_data213.useDispatch)(store3);
    const canRestore = !!currentRevisionId;
    const handleRestore = () => {
      if (currentRevisionId) {
        restoreRevision2(currentRevisionId);
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(
      HeaderSkeleton,
      {
        className: "editor-revisions-header",
        toolbar: /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(
          import_components251.Button,
          {
            __next40pxDefaultSize: true,
            size: "compact",
            icon: seen_default,
            label: (0, import_i18n302._x)("Show changes", "revisions"),
            isPressed: showDiff,
            onClick: onToggleDiff
          }
        ),
        center: /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(revisions_slider_default, {}),
        settings: /* @__PURE__ */ (0, import_jsx_runtime507.jsxs)(import_jsx_runtime507.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(PostPreviewButton, { className: "editor-header__post-preview-button" }),
          /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(
            import_components251.Button,
            {
              __next40pxDefaultSize: true,
              icon: (0, import_i18n302.isRTL)() ? drawer_left_default : drawer_right_default,
              label: (0, import_i18n302._x)("Settings", "panel button label"),
              isPressed: sidebarIsOpened,
              "aria-expanded": sidebarIsOpened,
              onClick: () => {
                if (sidebarIsOpened) {
                  disableComplementaryArea2("core");
                } else {
                  enableComplementaryArea2(
                    "core",
                    sidebars.document
                  );
                }
              },
              size: "compact"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(
            import_components251.Button,
            {
              __next40pxDefaultSize: true,
              variant: "secondary",
              size: "compact",
              onClick: () => setCurrentRevisionId2(null),
              children: (0, import_i18n302.__)("Exit")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(
            import_components251.Button,
            {
              __next40pxDefaultSize: true,
              accessibleWhenDisabled: true,
              variant: "primary",
              size: "compact",
              className: "editor-revisions-header__restore-button",
              disabled: !canRestore,
              onClick: handleRestore,
              children: (0, import_i18n302.__)("Restore")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime507.jsx)(MoreMenu, { disabled: true })
        ] })
      }
    );
  }
  var revisions_header_default = RevisionsHeader;

  // packages/editor/build-module/components/post-revisions-preview/revisions-canvas.mjs
  var import_components254 = __toESM(require_components(), 1);
  var import_block_editor84 = __toESM(require_block_editor(), 1);
  var import_data222 = __toESM(require_data(), 1);
  var import_element307 = __toESM(require_element(), 1);
  var import_hooks61 = __toESM(require_hooks(), 1);
  var import_blocks34 = __toESM(require_blocks(), 1);
  var import_i18n306 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/components/visual-editor/index.mjs
  var import_block_editor82 = __toESM(require_block_editor(), 1);
  var import_element305 = __toESM(require_element(), 1);
  var import_data220 = __toESM(require_data(), 1);
  var import_blocks33 = __toESM(require_blocks(), 1);
  var import_core_data119 = __toESM(require_core_data(), 1);
  var import_compose77 = __toESM(require_compose(), 1);

  // packages/editor/build-module/components/visual-editor/edit-template-blocks-notification.mjs
  var import_data214 = __toESM(require_data(), 1);
  var import_core_data117 = __toESM(require_core_data(), 1);
  var import_element302 = __toESM(require_element(), 1);
  var import_i18n303 = __toESM(require_i18n(), 1);
  var import_components252 = __toESM(require_components(), 1);
  var import_jsx_runtime508 = __toESM(require_jsx_runtime(), 1);
  function EditTemplateBlocksNotification({ contentRef }) {
    const { onNavigateToEntityRecord, templateId: templateId2 } = (0, import_data214.useSelect)((select9) => {
      const { getEditorSettings: getEditorSettings2, getCurrentTemplateId: getCurrentTemplateId2 } = select9(store);
      return {
        onNavigateToEntityRecord: getEditorSettings2().onNavigateToEntityRecord,
        templateId: getCurrentTemplateId2()
      };
    }, []);
    const canEditTemplate = (0, import_data214.useSelect)(
      (select9) => !!select9(import_core_data117.store).canUser("create", {
        kind: "postType",
        name: "wp_template"
      }),
      []
    );
    const [isDialogOpen, setIsDialogOpen] = (0, import_element302.useState)(false);
    (0, import_element302.useEffect)(() => {
      const handleDblClick = (event) => {
        if (!canEditTemplate) {
          return;
        }
        if (!event.target.classList.contains("is-root-container") || event.target.dataset?.type === "core/template-part") {
          return;
        }
        if (!event.defaultPrevented) {
          event.preventDefault();
          setIsDialogOpen(true);
        }
      };
      const canvas = contentRef.current;
      canvas?.addEventListener("dblclick", handleDblClick);
      return () => {
        canvas?.removeEventListener("dblclick", handleDblClick);
      };
    }, [contentRef, canEditTemplate]);
    if (!canEditTemplate) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime508.jsx)(
      import_components252.__experimentalConfirmDialog,
      {
        isOpen: isDialogOpen,
        confirmButtonText: (0, import_i18n303.__)("Edit template"),
        onConfirm: () => {
          setIsDialogOpen(false);
          onNavigateToEntityRecord({
            postId: templateId2,
            postType: "wp_template"
          });
        },
        onCancel: () => setIsDialogOpen(false),
        size: "medium",
        children: (0, import_i18n303.__)(
          "You\u2019ve tried to select a block that is part of a template that may be used elsewhere on your site. Would you like to edit the template?"
        )
      }
    );
  }

  // packages/editor/build-module/components/visual-editor/use-select-nearest-editable-block.mjs
  var import_compose72 = __toESM(require_compose(), 1);
  var import_data215 = __toESM(require_data(), 1);
  var import_block_editor77 = __toESM(require_block_editor(), 1);
  var DISTANCE_THRESHOLD = 500;
  function clamp2(value, min3, max3) {
    return Math.min(Math.max(value, min3), max3);
  }
  function distanceFromRect(x2, y3, rect) {
    const dx = x2 - clamp2(x2, rect.left, rect.right);
    const dy = y3 - clamp2(y3, rect.top, rect.bottom);
    return Math.sqrt(dx * dx + dy * dy);
  }
  function useSelectNearestEditableBlock({
    isEnabled = true
  } = {}) {
    const { getEnabledClientIdsTree, getBlockName: getBlockName2, getBlockOrder: getBlockOrder2 } = unlock(
      (0, import_data215.useSelect)(import_block_editor77.store)
    );
    const { selectBlock: selectBlock2 } = (0, import_data215.useDispatch)(import_block_editor77.store);
    return (0, import_compose72.useRefEffect)(
      (element) => {
        if (!isEnabled) {
          return;
        }
        const selectNearestEditableBlock = (x2, y3) => {
          const editableBlockClientIds = getEnabledClientIdsTree().flatMap(({ clientId }) => {
            const blockName = getBlockName2(clientId);
            if (blockName === "core/template-part") {
              return [];
            }
            if (blockName === "core/post-content") {
              const innerBlocks = getBlockOrder2(clientId);
              if (innerBlocks.length) {
                return innerBlocks;
              }
            }
            return [clientId];
          });
          let nearestDistance = Infinity, nearestClientId = null;
          for (const clientId of editableBlockClientIds) {
            const block = element.querySelector(
              `[data-block="${clientId}"]`
            );
            if (!block) {
              continue;
            }
            const rect = block.getBoundingClientRect();
            const distance2 = distanceFromRect(x2, y3, rect);
            if (distance2 < nearestDistance && distance2 < DISTANCE_THRESHOLD) {
              nearestDistance = distance2;
              nearestClientId = clientId;
            }
          }
          if (nearestClientId) {
            selectBlock2(nearestClientId);
          }
        };
        const handleClick = (event) => {
          const shouldSelect = event.target === element || event.target.classList.contains("is-root-container");
          if (shouldSelect) {
            selectNearestEditableBlock(event.clientX, event.clientY);
          }
        };
        element.addEventListener("click", handleClick);
        return () => element.removeEventListener("click", handleClick);
      },
      [isEnabled]
    );
  }

  // packages/editor/build-module/components/visual-editor/use-zoom-out-mode-exit.mjs
  var import_data216 = __toESM(require_data(), 1);
  var import_compose73 = __toESM(require_compose(), 1);
  var import_block_editor78 = __toESM(require_block_editor(), 1);
  function useZoomOutModeExit() {
    const { getSettings: getSettings10, isZoomOut } = unlock((0, import_data216.useSelect)(import_block_editor78.store));
    const { resetZoomLevel } = unlock((0, import_data216.useDispatch)(import_block_editor78.store));
    return (0, import_compose73.useRefEffect)(
      (node) => {
        function onDoubleClick(event) {
          if (!isZoomOut()) {
            return;
          }
          if (!event.defaultPrevented) {
            event.preventDefault();
            const { __experimentalSetIsInserterOpened } = getSettings10();
            if (typeof __experimentalSetIsInserterOpened === "function") {
              __experimentalSetIsInserterOpened(false);
            }
            resetZoomLevel();
          }
        }
        node.addEventListener("dblclick", onDoubleClick);
        return () => {
          node.removeEventListener("dblclick", onDoubleClick);
        };
      },
      [getSettings10, isZoomOut, resetZoomLevel]
    );
  }

  // packages/editor/build-module/components/visual-editor/use-padding-appender.mjs
  var import_data217 = __toESM(require_data(), 1);
  var import_compose74 = __toESM(require_compose(), 1);
  var import_block_editor79 = __toESM(require_block_editor(), 1);
  var import_blocks31 = __toESM(require_blocks(), 1);
  var CSS2 = ':root :where(.editor-styles-wrapper)::after {content: ""; display: block; height: 40vh;}';
  function usePaddingAppender(enabled) {
    const registry = (0, import_data217.useRegistry)();
    const effect = (0, import_compose74.useRefEffect)(
      (node) => {
        function onMouseDown(event) {
          if (event.target !== node && // Tests for the parent element because in the iframed editor if the click is
          // below the padding the target will be the parent element (html) and should
          // still be treated as intent to append.
          event.target !== node.parentElement) {
            return;
          }
          const lastChild = node.lastElementChild;
          if (!lastChild) {
            return;
          }
          const lastChildRect = lastChild.getBoundingClientRect();
          if (event.clientY < lastChildRect.bottom) {
            return;
          }
          event.preventDefault();
          const blockOrder = registry.select(import_block_editor79.store).getBlockOrder("");
          const lastBlockClientId = blockOrder[blockOrder.length - 1];
          const lastBlock = registry.select(import_block_editor79.store).getBlock(lastBlockClientId);
          const { selectBlock: selectBlock2, insertDefaultBlock: insertDefaultBlock2 } = registry.dispatch(import_block_editor79.store);
          if (lastBlock && (0, import_blocks31.isUnmodifiedDefaultBlock)(lastBlock)) {
            selectBlock2(lastBlockClientId);
          } else {
            insertDefaultBlock2();
          }
        }
        const { ownerDocument: ownerDocument2 } = node;
        ownerDocument2.addEventListener("pointerdown", onMouseDown);
        return () => {
          ownerDocument2.removeEventListener("pointerdown", onMouseDown);
        };
      },
      [registry]
    );
    return enabled ? [effect, CSS2] : [];
  }

  // packages/editor/build-module/components/visual-editor/use-edit-content-only-section-exit.mjs
  var import_data218 = __toESM(require_data(), 1);
  var import_compose75 = __toESM(require_compose(), 1);
  var import_block_editor80 = __toESM(require_block_editor(), 1);
  function useEditContentOnlySectionExit() {
    const { getEditedContentOnlySection } = unlock(
      (0, import_data218.useSelect)(import_block_editor80.store)
    );
    const { stopEditingContentOnlySection } = unlock(
      (0, import_data218.useDispatch)(import_block_editor80.store)
    );
    return (0, import_compose75.useRefEffect)(
      (node) => {
        function onClick(event) {
          const editedContentOnlySection = getEditedContentOnlySection();
          if (!editedContentOnlySection) {
            return;
          }
          const isClickOutside = !event.target.closest(
            `[data-block="${editedContentOnlySection}"]`
          );
          if (isClickOutside && !event.defaultPrevented) {
            event.preventDefault();
            stopEditingContentOnlySection();
          }
        }
        node.addEventListener("click", onClick);
        return () => {
          node.removeEventListener("click", onClick);
        };
      },
      [getEditedContentOnlySection, stopEditingContentOnlySection]
    );
  }

  // packages/editor/build-module/components/sync-connection-error-modal/index.mjs
  var import_data219 = __toESM(require_data(), 1);
  var import_compose76 = __toESM(require_compose(), 1);
  var import_blocks32 = __toESM(require_blocks(), 1);
  var import_core_data118 = __toESM(require_core_data(), 1);
  var import_block_editor81 = __toESM(require_block_editor(), 1);
  var import_components253 = __toESM(require_components(), 1);
  var import_hooks60 = __toESM(require_hooks(), 1);
  var import_element304 = __toESM(require_element(), 1);
  var import_i18n304 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/components/sync-connection-error-modal/use-retry-countdown.mjs
  var import_element303 = __toESM(require_element(), 1);
  function useRetryCountdown(connectionStatus) {
    const [secondsRemaining, setSecondsRemaining] = (0, import_element303.useState)();
    const hasRetriedRef = (0, import_element303.useRef)(false);
    (0, import_element303.useEffect)(() => {
      if (!connectionStatus) {
        return;
      }
      if ("connected" === connectionStatus.status) {
        setSecondsRemaining(void 0);
        hasRetriedRef.current = false;
        return;
      }
      if ("disconnected" !== connectionStatus.status || !connectionStatus.willAutoRetryInMs) {
        return;
      }
      const { willAutoRetryInMs: retryInMs } = connectionStatus;
      const retryAt = Date.now() + retryInMs;
      const hasRetried = hasRetriedRef.current;
      hasRetriedRef.current = true;
      if (hasRetried) {
        setSecondsRemaining(0);
      }
      let countdownIntervalId = null;
      const startCountdown = () => {
        setSecondsRemaining(Math.ceil((retryAt - Date.now()) / 1e3));
        countdownIntervalId = setInterval(() => {
          const remaining = Math.ceil((retryAt - Date.now()) / 1e3);
          setSecondsRemaining(Math.max(0, remaining));
          if (remaining <= 0 && countdownIntervalId) {
            clearInterval(countdownIntervalId);
          }
        }, 1e3);
      };
      const retryingDelayId = hasRetried ? setTimeout(startCountdown, 500) : null;
      if (!retryingDelayId) {
        startCountdown();
      }
      return () => {
        if (retryingDelayId) {
          clearTimeout(retryingDelayId);
        }
        if (countdownIntervalId) {
          clearInterval(countdownIntervalId);
        }
      };
    }, [connectionStatus]);
    return {
      onManualRetry: () => {
        setSecondsRemaining(0);
      },
      secondsRemaining
    };
  }

  // packages/editor/build-module/components/sync-connection-error-modal/index.mjs
  var import_jsx_runtime509 = __toESM(require_jsx_runtime(), 1);
  var { BlockCanvasCover: BlockCanvasCover2 } = unlock(import_block_editor81.privateApis);
  var { retrySyncConnection } = unlock(import_core_data118.privateApis);
  var INITIAL_DISCONNECTED_DEBOUNCE_MS = 2e4;
  function SyncConnectionErrorModal() {
    const [hasInitialized, setHasInitialized] = (0, import_element304.useState)(false);
    const [showModal, setShowModal] = (0, import_element304.useState)(false);
    const [isManualRetryAvailable, setIsManualRetryAvailable] = (0, import_element304.useState)(false);
    const { connectionStatus, isCollaborationEnabled, postType: postType2 } = (0, import_data219.useSelect)(
      (selectFn) => {
        const { getSyncConnectionStatus, getPostType } = unlock(
          selectFn(import_core_data118.store)
        );
        const { getCurrentPostType: getCurrentPostType2, isCollaborationEnabledForCurrentPost: isCollaborationEnabledForCurrentPost2 } = unlock(selectFn(store));
        const currentPostType = getCurrentPostType2();
        return {
          connectionStatus: getSyncConnectionStatus() || null,
          isCollaborationEnabled: isCollaborationEnabledForCurrentPost2(),
          postType: currentPostType ? getPostType(currentPostType) : null
        };
      },
      []
    );
    const { onManualRetry, secondsRemaining } = useRetryCountdown(connectionStatus);
    const copyButtonRef = (0, import_compose76.useCopyToClipboard)(() => {
      const blocks = (0, import_data219.select)(import_block_editor81.store).getBlocks();
      return (0, import_blocks32.serialize)(blocks);
    });
    (0, import_element304.useEffect)(() => {
      const timeout = setTimeout(() => {
        setHasInitialized(true);
      }, INITIAL_DISCONNECTED_DEBOUNCE_MS);
      return () => clearTimeout(timeout);
    }, []);
    (0, import_element304.useEffect)(() => {
      if ("connecting" === connectionStatus?.status) {
        return;
      }
      setIsManualRetryAvailable(
        connectionStatus !== null && "canManuallyRetry" in connectionStatus && connectionStatus.canManuallyRetry === true
      );
    }, [connectionStatus]);
    const canRetry = connectionStatus && "disconnected" === connectionStatus.status && (connectionStatus.canManuallyRetry || connectionStatus.willAutoRetryInMs);
    (0, import_element304.useEffect)(() => {
      if ("connected" === connectionStatus?.status) {
        setShowModal(false);
        return;
      }
      if (connectionStatus?.status && "connecting" !== connectionStatus.status && (!canRetry || connectionStatus.backgroundRetriesFailed)) {
        setShowModal(true);
      }
    }, [connectionStatus, canRetry]);
    const isProtocolMismatch = connectionStatus?.status === "disconnected" && "error" in connectionStatus && connectionStatus.error?.code === PROTOCOL_MISMATCH;
    if (!isCollaborationEnabled || !hasInitialized && !isProtocolMismatch || !showModal) {
      return null;
    }
    const error2 = connectionStatus && "error" in connectionStatus ? connectionStatus?.error : void 0;
    if (!canRetry && (0, import_hooks60.applyFilters)(
      "editor.isSyncConnectionErrorHandled",
      false,
      error2?.code
    ) !== false) {
      return null;
    }
    const manualRetry = isManualRetryAvailable ? () => {
      onManualRetry();
      retrySyncConnection();
    } : void 0;
    const messages = getSyncErrorMessages(error2);
    let retryCountdownText = "";
    let isRetrying = false;
    if (secondsRemaining && secondsRemaining > 0) {
      retryCountdownText = (0, import_i18n304.sprintf)(
        /* translators: %d: number of seconds until retry */
        (0, import_i18n304._n)(
          "Retrying connection in %d second\u2026",
          "Retrying connection in %d seconds\u2026",
          secondsRemaining
        ),
        secondsRemaining
      );
    } else if (0 === secondsRemaining) {
      isRetrying = true;
      retryCountdownText = (0, import_i18n304.__)("Retrying\u2026");
    }
    let editPostHref = "edit.php";
    if (postType2?.slug) {
      editPostHref = `edit.php?post_type=${postType2.slug}`;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime509.jsx)(BlockCanvasCover2.Fill, { children: /* @__PURE__ */ (0, import_jsx_runtime509.jsx)(
      import_components253.Modal,
      {
        overlayClassName: "editor-sync-connection-error-modal",
        isDismissible: false,
        onRequestClose: () => {
        },
        shouldCloseOnClickOutside: false,
        shouldCloseOnEsc: false,
        size: "medium",
        title: messages.title,
        children: /* @__PURE__ */ (0, import_jsx_runtime509.jsxs)(import_components253.__experimentalVStack, { spacing: 6, children: [
          /* @__PURE__ */ (0, import_jsx_runtime509.jsx)("p", { children: messages.description }),
          retryCountdownText && /* @__PURE__ */ (0, import_jsx_runtime509.jsx)("p", { className: "editor-sync-connection-error-modal__retry-countdown", children: retryCountdownText }),
          /* @__PURE__ */ (0, import_jsx_runtime509.jsxs)(import_components253.__experimentalHStack, { justify: "right", children: [
            /* @__PURE__ */ (0, import_jsx_runtime509.jsx)(
              import_components253.Button,
              {
                __next40pxDefaultSize: true,
                href: editPostHref,
                isDestructive: true,
                variant: "tertiary",
                children: (0, import_i18n304.sprintf)(
                  /* translators: %s: Post type name (e.g., "Posts", "Pages"). */
                  (0, import_i18n304.__)("Back to %s"),
                  postType2?.labels?.name ?? (0, import_i18n304.__)("Posts")
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime509.jsx)(
              import_components253.Button,
              {
                __next40pxDefaultSize: true,
                ref: copyButtonRef,
                variant: manualRetry ? "secondary" : "primary",
                children: (0, import_i18n304.__)("Copy Post Content")
              }
            ),
            manualRetry && /* @__PURE__ */ (0, import_jsx_runtime509.jsx)(
              import_components253.Button,
              {
                __next40pxDefaultSize: true,
                accessibleWhenDisabled: true,
                "aria-disabled": isRetrying,
                disabled: isRetrying,
                isBusy: isRetrying,
                variant: "primary",
                onClick: manualRetry,
                children: (0, import_i18n304.__)("Retry")
              }
            )
          ] })
        ] })
      }
    ) });
  }

  // packages/editor/build-module/components/visual-editor/index.mjs
  var import_jsx_runtime510 = __toESM(require_jsx_runtime(), 1);
  var {
    LayoutStyle,
    useLayoutClasses,
    useLayoutStyles,
    ExperimentalBlockCanvas: BlockCanvas,
    useFlashEditableBlocks
  } = unlock(import_block_editor82.privateApis);
  function getPostContentAttributes(blocks) {
    for (let i3 = 0; i3 < blocks.length; i3++) {
      if (blocks[i3].name === "core/post-content") {
        return blocks[i3].attributes;
      }
      if (blocks[i3].innerBlocks.length) {
        const nestedPostContent = getPostContentAttributes(
          blocks[i3].innerBlocks
        );
        if (nestedPostContent) {
          return nestedPostContent;
        }
      }
    }
  }
  function checkForPostContentAtRootLevel(blocks) {
    for (let i3 = 0; i3 < blocks.length; i3++) {
      if (blocks[i3].name === "core/post-content") {
        return true;
      }
    }
    return false;
  }
  var CANVAS_MIN_WIDTH = 300;
  var CANVAS_TARGET_ASPECT_RATIO = 9 / 16;
  function getCanvasHeight(width, containerSize) {
    const lerp2 = (a3, b3, amount) => a3 + (b3 - a3) * amount;
    const lerpFactor = 1 - Math.max(
      0,
      Math.min(
        1,
        (width - CANVAS_MIN_WIDTH) / (containerSize.width - CANVAS_MIN_WIDTH)
      )
    );
    const aspectRatio = lerp2(
      containerSize.width / containerSize.height,
      CANVAS_TARGET_ASPECT_RATIO,
      lerpFactor
    );
    return Math.min(Math.round(width / aspectRatio), containerSize.height);
  }
  function VisualEditor({
    // Ideally as we unify post and site editors, we won't need these props.
    autoFocus,
    iframeProps,
    contentRef,
    className
  }) {
    const isMobileViewport = (0, import_compose77.useViewportMatch)("small", "<");
    const {
      renderingMode: renderingMode2,
      postContentAttributes,
      editedPostTemplate = {},
      wrapperBlockName,
      wrapperUniqueId,
      deviceType,
      isFocusedEntity,
      isDesignPostType,
      postType: postType2,
      isPreview,
      styles,
      hasCanvasWidth,
      canvasWidth: canvasWidth2
    } = (0, import_data220.useSelect)((select9) => {
      const {
        getCurrentPostId: getCurrentPostId2,
        getCurrentPostType: getCurrentPostType2,
        getCurrentTemplateId: getCurrentTemplateId2,
        getEditorSettings: getEditorSettings2,
        getRenderingMode: getRenderingMode2,
        getDeviceType: getDeviceType2,
        getCanvasWidth: getCanvasWidth2
      } = unlock(select9(store));
      const { getPostType, getEditedEntityRecord } = select9(import_core_data119.store);
      const postTypeSlug = getCurrentPostType2();
      const _renderingMode = getRenderingMode2();
      let _wrapperBlockName;
      if (postTypeSlug === PATTERN_POST_TYPE) {
        _wrapperBlockName = "core/block";
      } else if (_renderingMode === "post-only") {
        _wrapperBlockName = "core/post-content";
      }
      const editorSettings2 = getEditorSettings2();
      const supportsTemplateMode = editorSettings2.supportsTemplateMode;
      const postTypeObject = getPostType(postTypeSlug);
      const currentTemplateId = getCurrentTemplateId2();
      const _canvasWidth = getCanvasWidth2();
      const template2 = currentTemplateId ? getEditedEntityRecord(
        "postType",
        TEMPLATE_POST_TYPE,
        currentTemplateId
      ) : void 0;
      return {
        renderingMode: _renderingMode,
        postContentAttributes: editorSettings2.postContentAttributes,
        isDesignPostType: DESIGN_POST_TYPES.includes(postTypeSlug),
        // Post template fetch returns a 404 on classic themes, which
        // messes with e2e tests, so check it's a block theme first.
        editedPostTemplate: postTypeObject?.viewable && supportsTemplateMode ? template2 : void 0,
        wrapperBlockName: _wrapperBlockName,
        wrapperUniqueId: getCurrentPostId2(),
        deviceType: getDeviceType2(),
        isFocusedEntity: !!editorSettings2.onNavigateToPreviousEntityRecord,
        postType: postTypeSlug,
        isPreview: editorSettings2.isPreviewMode,
        styles: editorSettings2.styles,
        hasCanvasWidth: _canvasWidth !== void 0,
        canvasWidth: _canvasWidth
      };
    }, []);
    const { isCleanNewPost: isCleanNewPost2 } = (0, import_data220.useSelect)(store);
    const {
      hasRootPaddingAwareAlignments,
      themeHasDisabledLayoutStyles,
      themeSupportsLayout,
      isZoomedOut
    } = (0, import_data220.useSelect)((select9) => {
      const { getSettings: getSettings10, isZoomOut: _isZoomOut } = unlock(
        select9(import_block_editor82.store)
      );
      const _settings = getSettings10();
      return {
        themeHasDisabledLayoutStyles: _settings.disableLayoutStyles,
        themeSupportsLayout: _settings.supportsLayout,
        hasRootPaddingAwareAlignments: _settings.__experimentalFeatures?.useRootPaddingAwareAlignments,
        isZoomedOut: _isZoomOut()
      };
    }, []);
    const localRef = (0, import_element305.useRef)();
    const [globalLayoutSettings] = (0, import_block_editor82.useSettings)("layout");
    const [containerSize, setContainerSize] = (0, import_element305.useState)();
    const containerRef = (0, import_compose77.useResizeObserver)((entries) => {
      const { width, height } = entries[0].contentRect;
      setContainerSize(
        (size4) => size4?.width === width && size4?.height === height ? size4 : { width, height }
      );
    });
    const fallbackLayout = (0, import_element305.useMemo)(() => {
      if (renderingMode2 !== "post-only" || isDesignPostType) {
        return { type: "default" };
      }
      if (themeSupportsLayout) {
        return { ...globalLayoutSettings, type: "constrained" };
      }
      return { type: "default" };
    }, [
      renderingMode2,
      themeSupportsLayout,
      globalLayoutSettings,
      isDesignPostType
    ]);
    const newestPostContentAttributes = (0, import_element305.useMemo)(() => {
      if (!editedPostTemplate?.content && !editedPostTemplate?.blocks && postContentAttributes) {
        return postContentAttributes;
      }
      if (editedPostTemplate?.blocks) {
        return getPostContentAttributes(editedPostTemplate?.blocks);
      }
      const parseableContent = typeof editedPostTemplate?.content === "string" ? editedPostTemplate?.content : "";
      return getPostContentAttributes((0, import_blocks33.parse)(parseableContent)) || {};
    }, [
      editedPostTemplate?.content,
      editedPostTemplate?.blocks,
      postContentAttributes
    ]);
    const hasPostContentAtRootLevel = (0, import_element305.useMemo)(() => {
      if (!editedPostTemplate?.content && !editedPostTemplate?.blocks) {
        return false;
      }
      if (editedPostTemplate?.blocks) {
        return checkForPostContentAtRootLevel(editedPostTemplate?.blocks);
      }
      const parseableContent = typeof editedPostTemplate?.content === "string" ? editedPostTemplate?.content : "";
      return checkForPostContentAtRootLevel((0, import_blocks33.parse)(parseableContent)) || false;
    }, [editedPostTemplate?.content, editedPostTemplate?.blocks]);
    const { layout = {}, align = "" } = newestPostContentAttributes || {};
    const postContentLayoutClasses = useLayoutClasses(
      newestPostContentAttributes,
      "core/post-content"
    );
    const blockListLayoutClass = clsx_default(
      {
        "is-layout-flow": !themeSupportsLayout
      },
      themeSupportsLayout && postContentLayoutClasses,
      align && `align${align}`
    );
    const postContentLayoutStyles = useLayoutStyles(
      newestPostContentAttributes,
      "core/post-content",
      ".block-editor-block-list__layout.is-root-container"
    );
    const postContentLayout = (0, import_element305.useMemo)(() => {
      return layout && (layout?.type === "constrained" || layout?.inherit || layout?.contentSize || layout?.wideSize) ? { ...globalLayoutSettings, ...layout, type: "constrained" } : { ...globalLayoutSettings, ...layout, type: "default" };
    }, [
      layout?.type,
      layout?.inherit,
      layout?.contentSize,
      layout?.wideSize,
      globalLayoutSettings
    ]);
    const blockListLayout = postContentAttributes ? postContentLayout : fallbackLayout;
    const postEditorLayout = blockListLayout?.type === "default" && !hasPostContentAtRootLevel ? fallbackLayout : blockListLayout;
    const titleRef = (0, import_element305.useRef)();
    (0, import_element305.useEffect)(() => {
      if (!autoFocus || !isCleanNewPost2()) {
        return;
      }
      titleRef?.current?.focus();
    }, [autoFocus, isCleanNewPost2]);
    const alignCSS = `.is-root-container.alignwide { max-width: var(--wp--style--global--wide-size); margin-left: auto; margin-right: auto;}
		.is-root-container.alignwide:where(.is-layout-flow) > :not(.alignleft):not(.alignright) { max-width: var(--wp--style--global--wide-size);}
		.is-root-container.alignfull { max-width: none; margin-left: auto; margin-right: auto;}
		.is-root-container.alignfull:where(.is-layout-flow) > :not(.alignleft):not(.alignright) { max-width: none;}`;
    const isResizablePostType = [
      NAVIGATION_POST_TYPE,
      TEMPLATE_PART_POST_TYPE,
      PATTERN_POST_TYPE
    ].includes(postType2);
    const enableResizing = isResizablePostType && // Disable in previews / view mode.
    !isPreview && // Disable resizing in mobile viewport.
    !isMobileViewport && // Disable resizing in zoomed-out mode.
    !isZoomedOut || // When the canvas has an explicit width, always allow resizing.
    hasCanvasWidth;
    const isNavigationPreview = postType2 === NAVIGATION_POST_TYPE && isPreview;
    const [paddingAppenderRef, paddingStyle] = usePaddingAppender(
      !isPreview && renderingMode2 === "post-only" && !isDesignPostType
    );
    const shouldConstrainCanvasHeight = enableResizing && canvasWidth2 && containerSize?.height > 0 && containerSize?.width > CANVAS_MIN_WIDTH;
    const canvasHeight = shouldConstrainCanvasHeight ? getCanvasHeight(canvasWidth2, containerSize) : "100%";
    const centerContentCSS = `display:flex;align-items:center;justify-content:center;`;
    const iframeBodyMinHeightCSS = hasCanvasWidth && !isResizablePostType ? "min-height:100vh;" : "";
    const iframeStyles = (0, import_element305.useMemo)(() => {
      return [
        ...styles ?? [],
        {
          // Ensures margins of children are contained so that the body background paints behind them.
          // Otherwise, the background of html (when zoomed out) would show there and appear broken. It's
          // important mostly for post-only views yet conceivably an issue in templated views too.
          css: `:where(.block-editor-iframe__body){display:flow-root;}.is-root-container{display:flow-root;${// Some themes will have `min-height: 100vh` for the root container,
          // which isn't a requirement in auto resize mode.
          enableResizing || isNavigationPreview ? "min-height:0!important;" : ""}}
				${paddingStyle ? paddingStyle : ""}
				${enableResizing ? `.block-editor-iframe__html{background:var(--wp-editor-canvas-background);min-height:100vh;${centerContentCSS}}.block-editor-iframe__body{width:100%;${iframeBodyMinHeightCSS}}` : ""}${isNavigationPreview ? `.block-editor-iframe__body{${centerContentCSS}padding:var(--wp--style--block-gap,2em);}` : ""}`
          // The CSS for enableResizing centers the body content vertically when resizing is enabled and applies a background
          // color to the iframe HTML element to match the background color of the editor canvas.
          // The CSS for isNavigationPreview centers the body content vertically and horizontally when the navigation is in preview mode.
        }
      ];
    }, [
      styles,
      enableResizing,
      centerContentCSS,
      iframeBodyMinHeightCSS,
      isNavigationPreview,
      paddingStyle
    ]);
    const typewriterRef = (0, import_block_editor82.__unstableUseTypewriter)();
    contentRef = (0, import_compose77.useMergeRefs)([
      localRef,
      contentRef,
      renderingMode2 === "post-only" ? typewriterRef : null,
      useFlashEditableBlocks({
        isEnabled: renderingMode2 === "template-locked"
      }),
      useSelectNearestEditableBlock({
        isEnabled: renderingMode2 === "template-locked"
      }),
      useZoomOutModeExit(),
      paddingAppenderRef,
      useEditContentOnlySectionExit()
    ]);
    return /* @__PURE__ */ (0, import_jsx_runtime510.jsxs)(
      "div",
      {
        ref: containerRef,
        className: clsx_default(
          "editor-visual-editor",
          // this class is here for backward compatibility reasons.
          "edit-post-visual-editor",
          className,
          {
            // Vertical padding frames a width-constrained canvas
            // (device preview or after a resize) as a centered preview.
            "has-vertical-padding": isFocusedEntity || hasCanvasWidth,
            // Horizontal padding leaves room for the resize handles
            // that appear on the left/right of a resizable canvas.
            "has-horizontal-padding": isFocusedEntity || enableResizing
          }
        ),
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(SyncConnectionErrorModal, {}),
          /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(
            resizable_editor_default,
            {
              enableResizing,
              width: enableResizing && canvasWidth2 ? canvasWidth2 + "px" : "100%",
              height: canvasHeight,
              children: /* @__PURE__ */ (0, import_jsx_runtime510.jsxs)(
                BlockCanvas,
                {
                  shouldIframe: true,
                  contentRef,
                  styles: iframeStyles,
                  height: "100%",
                  iframeProps: {
                    ...iframeProps,
                    style: iframeProps?.style
                  },
                  children: [
                    themeSupportsLayout && !themeHasDisabledLayoutStyles && renderingMode2 === "post-only" && !isDesignPostType && /* @__PURE__ */ (0, import_jsx_runtime510.jsxs)(import_jsx_runtime510.Fragment, { children: [
                      /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(
                        LayoutStyle,
                        {
                          selector: ".editor-visual-editor__post-title-wrapper",
                          layout: fallbackLayout
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(
                        LayoutStyle,
                        {
                          selector: ".block-editor-block-list__layout.is-root-container",
                          layout: postEditorLayout
                        }
                      ),
                      align && /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(LayoutStyle, { css: alignCSS }),
                      postContentLayoutStyles && /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(
                        LayoutStyle,
                        {
                          layout: postContentLayout,
                          css: postContentLayoutStyles
                        }
                      )
                    ] }),
                    renderingMode2 === "post-only" && !isDesignPostType && /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(
                      "div",
                      {
                        className: clsx_default(
                          "editor-visual-editor__post-title-wrapper",
                          // The following class is only here for backward compatibility
                          // some themes might be using it to style the post title.
                          "edit-post-visual-editor__post-title-wrapper",
                          {
                            "has-global-padding": hasRootPaddingAwareAlignments
                          }
                        ),
                        contentEditable: false,
                        style: {
                          // This is using inline styles so it's applied
                          // within the editor iframe.
                          marginTop: "4rem"
                        },
                        children: /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(post_title_default, { ref: titleRef })
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime510.jsxs)(
                      import_block_editor82.RecursionProvider,
                      {
                        blockName: wrapperBlockName,
                        uniqueId: wrapperUniqueId,
                        children: [
                          /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(
                            import_block_editor82.BlockList,
                            {
                              className: clsx_default(
                                "is-" + deviceType.toLowerCase() + "-preview",
                                renderingMode2 !== "post-only" || isDesignPostType ? "wp-site-blocks" : `${blockListLayoutClass} wp-block-post-content`,
                                // Ensure root level blocks receive default/flow blockGap styling rules.
                                {
                                  "has-global-padding": renderingMode2 === "post-only" && !isDesignPostType && hasRootPaddingAwareAlignments
                                }
                              ),
                              layout: blockListLayout,
                              dropZoneElement: (
                                // Pass in the html element of the iframe to
                                // ensure the drop zone extends to the edges of
                                // the iframe.
                                localRef.current?.parentNode
                              ),
                              __unstableDisableDropZone: (
                                // In template preview mode, disable drop zones at the root of the template.
                                renderingMode2 === "template-locked" ? true : false
                              )
                            }
                          ),
                          renderingMode2 === "template-locked" && /* @__PURE__ */ (0, import_jsx_runtime510.jsx)(
                            EditTemplateBlocksNotification,
                            {
                              contentRef: localRef
                            }
                          )
                        ]
                      }
                    )
                  ]
                }
              )
            }
          )
        ]
      }
    );
  }
  var visual_editor_default = VisualEditor;

  // packages/editor/build-module/components/post-revisions-preview/diff-markers.mjs
  var import_element306 = __toESM(require_element(), 1);
  var import_compose78 = __toESM(require_compose(), 1);
  var import_data221 = __toESM(require_data(), 1);
  var import_block_editor83 = __toESM(require_block_editor(), 1);
  var import_i18n305 = __toESM(require_i18n(), 1);
  var import_jsx_runtime511 = __toESM(require_jsx_runtime(), 1);
  var { useBlockElementRef } = unlock(import_block_editor83.privateApis);
  function collectDiffBlocks(blocks) {
    const result = [];
    for (const block of blocks) {
      if (block.__revisionDiffStatus?.status) {
        result.push({
          clientId: block.clientId,
          status: block.__revisionDiffStatus.status
        });
      }
      if (block.innerBlocks?.length) {
        result.push(...collectDiffBlocks(block.innerBlocks));
      }
    }
    return result;
  }
  var STATUS_LABELS = {
    added: (0, import_i18n305.__)("Go to added block"),
    removed: (0, import_i18n305.__)("Go to removed block"),
    modified: (0, import_i18n305.__)("Go to modified block")
  };
  function calculatePosition(el) {
    if (!el) {
      return null;
    }
    const doc = el.ownerDocument;
    const scrollHeight = doc.documentElement.scrollHeight;
    const rect = el.getBoundingClientRect();
    const scrollTop = doc.documentElement.scrollTop;
    const top = rect.top + scrollTop;
    return {
      top: top / scrollHeight * 100,
      height: rect.height / scrollHeight * 100
    };
  }
  function DiffMarkerButton({ clientId, status, subscribe: subscribe5 }) {
    const blockRef = (0, import_element306.useRef)();
    useBlockElementRef(clientId, blockRef);
    const [position, setPosition] = (0, import_element306.useState)(
      () => calculatePosition(blockRef.current)
    );
    (0, import_element306.useEffect)(() => {
      return subscribe5(() => {
        setPosition(calculatePosition(blockRef.current));
      });
    }, [subscribe5]);
    (0, import_element306.useEffect)(() => {
      setPosition(calculatePosition(blockRef.current));
    }, [status]);
    if (!position) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime511.jsxs)(tooltip_exports.Root, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime511.jsx)(
        tooltip_exports.Trigger,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime511.jsx)(
            "button",
            {
              className: `revision-diff-marker is-${status}`,
              style: {
                top: `${position.top}%`,
                height: `${Math.max(position.height, 0.5)}%`
              },
              onClick: () => blockRef.current?.focus(),
              "aria-label": STATUS_LABELS[status]
            }
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime511.jsx)(tooltip_exports.Popup, { children: STATUS_LABELS[status] })
    ] });
  }
  function useDiffMarkers() {
    const [isMounted, setIsMounted] = (0, import_element306.useState)(false);
    const subscribersRef = (0, import_element306.useRef)(/* @__PURE__ */ new Set());
    const blocks = (0, import_data221.useSelect)(
      (select9) => select9(import_block_editor83.store).getBlocks(),
      []
    );
    const diffBlocks = (0, import_element306.useMemo)(() => collectDiffBlocks(blocks), [blocks]);
    const subscribe5 = (0, import_element306.useCallback)((callback) => {
      subscribersRef.current.add(callback);
      return () => subscribersRef.current.delete(callback);
    }, []);
    const contentRef = (0, import_compose78.useRefEffect)((element) => {
      const { ownerDocument: ownerDocument2 } = element;
      const { defaultView } = ownerDocument2;
      const resizeObserver = new defaultView.ResizeObserver(() => {
        subscribersRef.current.forEach((cb) => cb());
      });
      resizeObserver.observe(ownerDocument2.body);
      return () => {
        resizeObserver.disconnect();
      };
    }, []);
    return [
      (0, import_compose78.useMergeRefs)([contentRef, setIsMounted]),
      /* @__PURE__ */ (0, import_jsx_runtime511.jsx)(
        "div",
        {
          className: "revision-diff-markers",
          role: "navigation",
          "aria-label": (0, import_i18n305.__)("Document changes"),
          children: isMounted && diffBlocks.map(({ clientId, status }) => /* @__PURE__ */ (0, import_jsx_runtime511.jsx)(
            DiffMarkerButton,
            {
              clientId,
              status,
              subscribe: subscribe5
            },
            clientId
          ))
        },
        "diff-markers"
      )
    ];
  }

  // packages/editor/build-module/components/post-revisions-preview/revisions-canvas.mjs
  var import_jsx_runtime512 = __toESM(require_jsx_runtime(), 1);
  var { usePrivateStyleOverride, PrivateBlockContext } = unlock(
    import_block_editor84.privateApis
  );
  var REVISION_REMOVED_FILTER_SVG = `
<svg
	xmlns="http://www.w3.org/2000/svg"
	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="revision-removed-filter" x="0" y="0" width="100%" height="100%">
			<!-- Desaturate and add red tint -->
			<feColorMatrix type="matrix"
				values="0.5 0.3 0.2 0 0.15
				        0.2 0.2 0.1 0 0
				        0.2 0.2 0.1 0 0
				        0   0   0   0.8 0"/>
		</filter>
	</defs>
</svg>
`;
  var REVISION_DIFF_STYLES = `
	.is-revision-added {
		box-shadow: inset 0 0 0 9999px color-mix(in srgb, currentColor 5%, #00a32a 15%), 0 0 0 4px color-mix(in srgb, currentColor 5%, #00a32a 15%);
		outline: 3px solid #00a32a;
		outline-offset: 2px;
	}
	.is-revision-removed,
	.revision-diff-removed {
		text-decoration: line-through;
		filter: url(#revision-removed-filter);
	}
	.is-revision-removed {
		outline: 3px dashed #d63638;
		outline-offset: 2px;
	}
	.is-revision-modified {
		outline: 3px dotted #9a7000 !important;
		outline-offset: 2px;
	}
	.revision-diff-added {
		background-color: color-mix(in srgb, currentColor 5%, #00a32a 15%);
		text-decoration: none;
	}
	/* Reset UA <mark> styles so format markers keep the same look as before. */
	mark.revision-diff-format-added,
	mark.revision-diff-format-removed,
	mark.revision-diff-format-changed {
		background: transparent;
		color: inherit;
		padding: 0;
	}
	.revision-diff-format-added {
		text-decoration: underline wavy color-mix(in srgb, currentColor 30%, #00a32a 70%);
		text-decoration-thickness: 2px;
	}
	.revision-diff-format-removed {
		text-decoration: underline wavy color-mix(in srgb, currentColor 20%, #d63638 80%);
		text-decoration-thickness: 2px;
	}
	.revision-diff-format-changed {
		text-decoration: underline wavy color-mix(in srgb, currentColor 30%, #dba617 70%);
		text-decoration-thickness: 2px;
	}
`;
  function getDiffStatusLabel(status, blockTitle) {
    switch (status) {
      case "added":
        return (0, import_i18n306.sprintf)((0, import_i18n306.__)("Added block: %s"), blockTitle);
      case "removed":
        return (0, import_i18n306.sprintf)((0, import_i18n306.__)("Removed block: %s"), blockTitle);
      case "modified":
        return (0, import_i18n306.sprintf)((0, import_i18n306.__)("Modified block: %s"), blockTitle);
    }
  }
  function BlockDiffLabelProvider({ status, name: name2, attributes, children }) {
    const context = (0, import_element307.useContext)(PrivateBlockContext);
    const blockTitle = (0, import_data222.useSelect)(
      (select9) => {
        const { getActiveBlockVariation, getBlockType: getBlockType7 } = select9(import_blocks34.store);
        return getActiveBlockVariation(name2, attributes)?.title ?? getBlockType7(name2)?.title;
      },
      [name2, attributes]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(
      PrivateBlockContext.Provider,
      {
        value: {
          ...context,
          ariaLabel: blockTitle ? getDiffStatusLabel(status, blockTitle) : void 0
        },
        children
      }
    );
  }
  function withRevisionDiffClasses(BlockListBlock) {
    return function WithRevisionDiffClasses(props) {
      const { block, className, name: name2, attributes } = props;
      const diffStatus = block?.__revisionDiffStatus?.status;
      const enhancedClassName = clsx_default(className, {
        "is-revision-added": diffStatus === "added",
        "is-revision-removed": diffStatus === "removed",
        "is-revision-modified": diffStatus === "modified"
      });
      if (!diffStatus) {
        return /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(BlockListBlock, { ...props, className: enhancedClassName });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(
        BlockDiffLabelProvider,
        {
          status: diffStatus,
          name: name2,
          attributes,
          children: /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(BlockListBlock, { ...props, className: enhancedClassName })
        }
      );
    };
  }
  var FILTER_NAME = "editor/revisions-canvas/withRevisionDiffClasses";
  (0, import_hooks61.addFilter)("editor.BlockListBlock", FILTER_NAME, withRevisionDiffClasses);
  function DiffStyleOverrides({ showDiff }) {
    usePrivateStyleOverride({
      css: showDiff ? REVISION_DIFF_STYLES : ""
    });
    usePrivateStyleOverride({
      assets: showDiff ? REVISION_REMOVED_FILTER_SVG : "",
      __unstableType: "svgs"
    });
    return null;
  }
  function DiffDescriptions() {
    return /* @__PURE__ */ (0, import_jsx_runtime512.jsxs)(VisuallyHidden, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime512.jsx)("span", { id: DIFF_DESCRIPTION_IDS.removed, children: (0, import_i18n306.__)("Removed") }),
      /* @__PURE__ */ (0, import_jsx_runtime512.jsx)("span", { id: DIFF_DESCRIPTION_IDS.added, children: (0, import_i18n306.__)("Added") }),
      /* @__PURE__ */ (0, import_jsx_runtime512.jsx)("span", { id: DIFF_DESCRIPTION_IDS.formatAdded, children: (0, import_i18n306.__)("Format added") }),
      /* @__PURE__ */ (0, import_jsx_runtime512.jsx)("span", { id: DIFF_DESCRIPTION_IDS.formatRemoved, children: (0, import_i18n306.__)("Format removed") }),
      /* @__PURE__ */ (0, import_jsx_runtime512.jsx)("span", { id: DIFF_DESCRIPTION_IDS.formatChanged, children: (0, import_i18n306.__)("Format changed") })
    ] });
  }
  function CanvasContent({ showDiff }) {
    const [contentRef, diffMarkers] = useDiffMarkers();
    return /* @__PURE__ */ (0, import_jsx_runtime512.jsxs)(import_jsx_runtime512.Fragment, { children: [
      showDiff && /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(DiffDescriptions, {}),
      /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(visual_editor_default, { contentRef }),
      showDiff && diffMarkers
    ] });
  }
  function RevisionsCanvas() {
    (0, import_element307.useEffect)(() => {
      registerDiffFormatTypes();
      return () => {
        unregisterDiffFormatTypes();
      };
    }, []);
    const { revision, showDiff } = (0, import_data222.useSelect)((select9) => {
      const { getCurrentRevision: getCurrentRevision2, isShowingRevisionDiff: isShowingRevisionDiff2 } = unlock(
        select9(store)
      );
      return {
        revision: getCurrentRevision2(),
        showDiff: isShowingRevisionDiff2()
      };
    }, []);
    return revision ? /* @__PURE__ */ (0, import_jsx_runtime512.jsxs)(import_jsx_runtime512.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(DiffStyleOverrides, { showDiff }),
      /* @__PURE__ */ (0, import_jsx_runtime512.jsx)("div", { className: "editor-revisions-canvas__content", children: /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(CanvasContent, { showDiff }) })
    ] }) : /* @__PURE__ */ (0, import_jsx_runtime512.jsx)("div", { className: "editor-revisions-canvas__loading", children: /* @__PURE__ */ (0, import_jsx_runtime512.jsx)(import_components254.Spinner, {}) });
  }

  // packages/editor/build-module/components/collaborators-presence/use-collaborator-notifications.mjs
  var import_data223 = __toESM(require_data(), 1);
  var import_element308 = __toESM(require_element(), 1);
  var import_i18n307 = __toESM(require_i18n(), 1);
  var import_notices31 = __toESM(require_notices(), 1);
  var import_core_data120 = __toESM(require_core_data(), 1);
  var import_preferences23 = __toESM(require_preferences(), 1);
  var { useOnCollaboratorJoin, useOnCollaboratorLeave, useOnPostSave } = unlock(import_core_data120.privateApis);
  var NOTIFICATION_TYPE = {
    COLLAB_POST_UPDATED: "collab-post-updated",
    COLLAB_USER_ENTERED: "collab-user-entered",
    COLLAB_USER_EXITED: "collab-user-exited"
  };
  var PUBLISHED_STATUSES = ["publish", "private", "future"];
  function getPostUpdatedMessage(name2, status, isFirstPublish) {
    if (isFirstPublish) {
      return (0, import_i18n307.sprintf)((0, import_i18n307.__)("Post published by %s."), name2);
    }
    if (PUBLISHED_STATUSES.includes(status)) {
      return (0, import_i18n307.sprintf)((0, import_i18n307.__)("Post updated by %s."), name2);
    }
    return (0, import_i18n307.sprintf)((0, import_i18n307.__)("Draft saved by %s."), name2);
  }
  function useCollaboratorNotifications(postId2, postType2) {
    const {
      postStatus,
      isCollaborationEnabled,
      showJoinNotifications,
      showLeaveNotifications,
      showPostSaveNotifications
    } = (0, import_data223.useSelect)((select9) => {
      const {
        getCurrentPostAttribute: getCurrentPostAttribute2,
        isCollaborationEnabledForCurrentPost: isCollaborationEnabledForCurrentPost2
      } = unlock(select9(store));
      const getNotificationPreference = (name2) => select9(import_preferences23.store).get("core", name2) ?? true;
      return {
        postStatus: getCurrentPostAttribute2("status"),
        isCollaborationEnabled: isCollaborationEnabledForCurrentPost2(),
        showJoinNotifications: getNotificationPreference(
          "showCollaborationJoinNotifications"
        ),
        showLeaveNotifications: getNotificationPreference(
          "showCollaborationLeaveNotifications"
        ),
        showPostSaveNotifications: getNotificationPreference(
          "showCollaborationPostSaveNotifications"
        )
      };
    }, []);
    const { createNotice } = (0, import_data223.useDispatch)(import_notices31.store);
    const shouldShowJoinNotifications = isCollaborationEnabled && showJoinNotifications;
    const shouldShowLeaveNotifications = isCollaborationEnabled && showLeaveNotifications;
    const shouldShowPostSaveNotifications = isCollaborationEnabled && showPostSaveNotifications;
    const effectiveTarget = (shouldShow) => shouldShow ? [postId2, postType2] : [null, null];
    const [joinPostId, joinPostType] = effectiveTarget(
      shouldShowJoinNotifications
    );
    const [leavePostId, leavePostType] = effectiveTarget(
      shouldShowLeaveNotifications
    );
    const [postSavePostId, postSavePostType] = effectiveTarget(
      shouldShowPostSaveNotifications
    );
    useOnCollaboratorJoin(
      joinPostId,
      joinPostType,
      (0, import_element308.useCallback)(
        (collaborator, me) => {
          if (!shouldShowJoinNotifications) {
            return;
          }
          if (me && collaborator.collaboratorInfo.enteredAt < me.collaboratorInfo.enteredAt) {
            return;
          }
          void createNotice(
            "info",
            (0, import_i18n307.sprintf)(
              /* translators: %s: collaborator display name */
              (0, import_i18n307.__)("%s has joined the post."),
              collaborator.collaboratorInfo.name
            ),
            {
              id: `${NOTIFICATION_TYPE.COLLAB_USER_ENTERED}-${collaborator.collaboratorInfo.id}`,
              type: "snackbar",
              isDismissible: false
            }
          );
        },
        [createNotice, shouldShowJoinNotifications]
      )
    );
    useOnCollaboratorLeave(
      leavePostId,
      leavePostType,
      (0, import_element308.useCallback)(
        (collaborator) => {
          if (!shouldShowLeaveNotifications) {
            return;
          }
          void createNotice(
            "info",
            (0, import_i18n307.sprintf)(
              /* translators: %s: collaborator display name */
              (0, import_i18n307.__)("%s has left the post."),
              collaborator.collaboratorInfo.name
            ),
            {
              id: `${NOTIFICATION_TYPE.COLLAB_USER_EXITED}-${collaborator.collaboratorInfo.id}`,
              type: "snackbar",
              isDismissible: false
            }
          );
        },
        [createNotice, shouldShowLeaveNotifications]
      )
    );
    useOnPostSave(
      postSavePostId,
      postSavePostType,
      (0, import_element308.useCallback)(
        (saveEvent, saver, prevEvent) => {
          if (!shouldShowPostSaveNotifications || !postStatus) {
            return;
          }
          const effectiveStatus = saveEvent.postStatus ?? postStatus ?? "draft";
          const prevStatus = prevEvent?.postStatus ?? postStatus;
          const isFirstPublish = !(prevStatus && PUBLISHED_STATUSES.includes(prevStatus)) && PUBLISHED_STATUSES.includes(effectiveStatus);
          const message2 = getPostUpdatedMessage(
            saver.collaboratorInfo.name,
            effectiveStatus,
            isFirstPublish
          );
          void createNotice("info", message2, {
            id: `${NOTIFICATION_TYPE.COLLAB_POST_UPDATED}-${saver.collaboratorInfo.id}`,
            type: "snackbar",
            isDismissible: false
          });
        },
        [createNotice, postStatus, shouldShowPostSaveNotifications]
      )
    );
  }

  // packages/editor/build-module/components/save-publish-panels/index.mjs
  var import_data224 = __toESM(require_data(), 1);
  var import_components255 = __toESM(require_components(), 1);
  var import_i18n308 = __toESM(require_i18n(), 1);
  var import_element309 = __toESM(require_element(), 1);
  var import_jsx_runtime513 = __toESM(require_jsx_runtime(), 1);
  var { Fill: Fill11, Slot: Slot13 } = (0, import_components255.createSlotFill)("ActionsPanel");
  function SavePublishPanels({
    setEntitiesSavedStatesCallback,
    closeEntitiesSavedStates,
    isEntitiesSavedStatesOpen,
    forceIsDirtyPublishPanel
  }) {
    const { closePublishSidebar: closePublishSidebar2, togglePublishSidebar: togglePublishSidebar2 } = (0, import_data224.useDispatch)(store);
    const {
      publishSidebarOpened,
      isPublishable,
      isDirty,
      hasOtherEntitiesChanges
    } = (0, import_data224.useSelect)((select9) => {
      const {
        isPublishSidebarOpened: isPublishSidebarOpened2,
        isEditedPostPublishable: isEditedPostPublishable2,
        isCurrentPostPublished: isCurrentPostPublished2,
        isEditedPostDirty: isEditedPostDirty2,
        hasNonPostEntityChanges: hasNonPostEntityChanges2
      } = select9(store);
      const _hasOtherEntitiesChanges = hasNonPostEntityChanges2();
      return {
        publishSidebarOpened: isPublishSidebarOpened2(),
        isPublishable: !isCurrentPostPublished2() && isEditedPostPublishable2(),
        isDirty: _hasOtherEntitiesChanges || isEditedPostDirty2(),
        hasOtherEntitiesChanges: _hasOtherEntitiesChanges
      };
    }, []);
    const openEntitiesSavedStates = (0, import_element309.useCallback)(
      () => setEntitiesSavedStatesCallback(true),
      []
    );
    let unmountableContent;
    if (publishSidebarOpened) {
      unmountableContent = /* @__PURE__ */ (0, import_jsx_runtime513.jsx)(
        PostPublishPanel,
        {
          onClose: closePublishSidebar2,
          forceIsDirty: forceIsDirtyPublishPanel,
          PrePublishExtension: plugin_pre_publish_panel_default.Slot,
          PostPublishExtension: plugin_post_publish_panel_default.Slot
        }
      );
    } else if (isPublishable && !hasOtherEntitiesChanges) {
      unmountableContent = /* @__PURE__ */ (0, import_jsx_runtime513.jsx)("div", { className: "editor-layout__toggle-publish-panel", children: /* @__PURE__ */ (0, import_jsx_runtime513.jsx)(
        import_components255.Button,
        {
          __next40pxDefaultSize: true,
          variant: "secondary",
          onClick: togglePublishSidebar2,
          "aria-expanded": false,
          children: (0, import_i18n308.__)("Open publish panel")
        }
      ) });
    } else {
      unmountableContent = /* @__PURE__ */ (0, import_jsx_runtime513.jsx)("div", { className: "editor-layout__toggle-entities-saved-states-panel", children: /* @__PURE__ */ (0, import_jsx_runtime513.jsx)(
        import_components255.Button,
        {
          __next40pxDefaultSize: true,
          variant: "secondary",
          onClick: openEntitiesSavedStates,
          "aria-expanded": false,
          "aria-haspopup": "dialog",
          disabled: !isDirty,
          accessibleWhenDisabled: true,
          children: (0, import_i18n308.__)("Open save panel")
        }
      ) });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime513.jsxs)(import_jsx_runtime513.Fragment, { children: [
      isEntitiesSavedStatesOpen && /* @__PURE__ */ (0, import_jsx_runtime513.jsx)(
        EntitiesSavedStates,
        {
          close: closeEntitiesSavedStates,
          renderDialog: true
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime513.jsx)(Slot13, { bubblesVirtually: true }),
      !isEntitiesSavedStatesOpen && unmountableContent
    ] });
  }

  // packages/editor/build-module/components/text-editor/index.mjs
  var import_components256 = __toESM(require_components(), 1);
  var import_data225 = __toESM(require_data(), 1);
  var import_i18n309 = __toESM(require_i18n(), 1);
  var import_keyboard_shortcuts10 = __toESM(require_keyboard_shortcuts(), 1);
  var import_element310 = __toESM(require_element(), 1);
  var import_jsx_runtime514 = __toESM(require_jsx_runtime(), 1);
  function TextEditor({ autoFocus = false }) {
    const { switchEditorMode: switchEditorMode2 } = (0, import_data225.useDispatch)(store);
    const { shortcut, isRichEditingEnabled } = (0, import_data225.useSelect)((select9) => {
      const { getEditorSettings: getEditorSettings2 } = select9(store);
      const { getShortcutRepresentation } = select9(import_keyboard_shortcuts10.store);
      return {
        shortcut: getShortcutRepresentation("core/editor/toggle-mode"),
        isRichEditingEnabled: getEditorSettings2().richEditingEnabled
      };
    }, []);
    const titleRef = (0, import_element310.useRef)();
    (0, import_element310.useEffect)(() => {
      if (autoFocus) {
        return;
      }
      titleRef?.current?.focus();
    }, [autoFocus]);
    return /* @__PURE__ */ (0, import_jsx_runtime514.jsxs)("div", { className: "editor-text-editor", children: [
      isRichEditingEnabled && /* @__PURE__ */ (0, import_jsx_runtime514.jsxs)("div", { className: "editor-text-editor__toolbar", children: [
        /* @__PURE__ */ (0, import_jsx_runtime514.jsx)("h2", { children: (0, import_i18n309.__)("Editing code") }),
        /* @__PURE__ */ (0, import_jsx_runtime514.jsx)(
          import_components256.Button,
          {
            __next40pxDefaultSize: true,
            variant: "tertiary",
            onClick: () => switchEditorMode2("visual"),
            shortcut,
            children: (0, import_i18n309.__)("Exit code editor")
          }
        )
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime514.jsxs)("div", { className: "editor-text-editor__body", children: [
        /* @__PURE__ */ (0, import_jsx_runtime514.jsx)(post_title_raw_default, { ref: titleRef }),
        /* @__PURE__ */ (0, import_jsx_runtime514.jsx)(PostTextEditor, {})
      ] })
    ] });
  }

  // packages/editor/build-module/components/editor-interface/index.mjs
  var import_jsx_runtime515 = __toESM(require_jsx_runtime(), 1);
  var interfaceLabels = {
    /* translators: accessibility text for the editor top bar landmark region. */
    header: (0, import_i18n310.__)("Editor top bar"),
    /* translators: accessibility text for the editor content landmark region. */
    body: (0, import_i18n310.__)("Editor content"),
    /* translators: accessibility text for the editor settings landmark region. */
    sidebar: (0, import_i18n310.__)("Editor settings"),
    /* translators: accessibility text for the editor publish landmark region. */
    actions: (0, import_i18n310.__)("Editor publish"),
    /* translators: accessibility text for the editor footer landmark region. */
    footer: (0, import_i18n310.__)("Editor footer")
  };
  function Notices() {
    const isValidTemplate2 = (0, import_data226.useSelect)((select9) => {
      return select9(import_block_editor85.store).isValidTemplate();
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(import_theme.ThemeProvider, { cornerRadius: "none", children: /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
      import_notices32.InlineNotices,
      {
        className: "editor-notices",
        pinnedNoticesClassName: "editor-notices__pinned",
        dismissibleNoticesClassName: "editor-notices__dismissible",
        children: !isValidTemplate2 && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(TemplateValidationNotice, {})
      }
    ) });
  }
  function EditorInterface({
    className,
    children,
    forceIsDirty,
    contentRef,
    autoFocus,
    customSaveButton,
    customSavePanel,
    forceDisableBlockTools,
    iframeProps
  }) {
    const {
      mode,
      postId: postId2,
      postType: postType2,
      isInserterOpened: isInserterOpened2,
      isListViewOpened: isListViewOpened2,
      isDistractionFree,
      isPreviewMode,
      showBlockBreadcrumbs,
      postTypeLabel,
      stylesPath: stylesPath2,
      showStylebook: showStylebook2,
      isRevisionsMode: isRevisionsMode2,
      showDiff
    } = (0, import_data226.useSelect)((select9) => {
      const { get } = select9(import_preferences24.store);
      const {
        getEditorSettings: getEditorSettings2,
        getPostTypeLabel: getPostTypeLabel2,
        getCurrentPostType: getCurrentPostType2,
        getCurrentPostId: getCurrentPostId2
      } = select9(store);
      const {
        getStylesPath: getStylesPath2,
        getShowStylebook: getShowStylebook2,
        isRevisionsMode: _isRevisionsMode,
        isShowingRevisionDiff: isShowingRevisionDiff2
      } = unlock(select9(store));
      const editorSettings2 = getEditorSettings2();
      let _mode = select9(store).getEditorMode();
      if (!editorSettings2.richEditingEnabled && _mode === "visual") {
        _mode = "text";
      }
      if (!editorSettings2.codeEditingEnabled && _mode === "text") {
        _mode = "visual";
      }
      return {
        mode: _mode,
        postId: getCurrentPostId2(),
        postType: getCurrentPostType2(),
        isInserterOpened: select9(store).isInserterOpened(),
        isListViewOpened: select9(store).isListViewOpened(),
        isDistractionFree: get("core", "distractionFree"),
        isPreviewMode: editorSettings2.isPreviewMode,
        showBlockBreadcrumbs: get("core", "showBlockBreadcrumbs"),
        postTypeLabel: getPostTypeLabel2(),
        stylesPath: getStylesPath2(),
        showStylebook: getShowStylebook2(),
        isRevisionsMode: _isRevisionsMode(),
        showDiff: isShowingRevisionDiff2()
      };
    }, []);
    const { setShowRevisionDiff: setShowRevisionDiff2 } = unlock((0, import_data226.useDispatch)(store));
    useCollaboratorNotifications(postId2, postType2);
    const isLargeViewport = (0, import_compose79.useViewportMatch)("medium");
    const secondarySidebarLabel = isListViewOpened2 ? (0, import_i18n310.__)("Document Overview") : (0, import_i18n310.__)("Block Library");
    const shouldShowStylesCanvas = showStylebook2 || stylesPath2?.startsWith("/revisions");
    const shouldShowBlockEditor = !shouldShowStylesCanvas;
    const [entitiesSavedStatesCallback, setEntitiesSavedStatesCallback] = (0, import_element311.useState)(false);
    const closeEntitiesSavedStates = (0, import_element311.useCallback)(
      (arg) => {
        if (typeof entitiesSavedStatesCallback === "function") {
          entitiesSavedStatesCallback(arg);
        }
        setEntitiesSavedStatesCallback(false);
      },
      [entitiesSavedStatesCallback]
    );
    if (isRevisionsMode2) {
      return /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
        interface_skeleton_default,
        {
          className: clsx_default("editor-editor-interface", className),
          labels: interfaceLabels,
          header: /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
            revisions_header_default,
            {
              showDiff,
              onToggleDiff: () => setShowRevisionDiff2(!showDiff)
            }
          ),
          content: /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(RevisionsCanvas, {}),
          sidebar: /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(complementary_area_default.Slot, { scope: "core" })
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
      interface_skeleton_default,
      {
        isDistractionFree,
        className: clsx_default("editor-editor-interface", className, {
          "is-entity-save-view-open": !!entitiesSavedStatesCallback,
          "is-distraction-free": isDistractionFree && !isPreviewMode
        }),
        labels: {
          ...interfaceLabels,
          secondarySidebar: secondarySidebarLabel
        },
        header: !isPreviewMode && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
          header_default2,
          {
            forceIsDirty,
            setEntitiesSavedStatesCallback,
            customSaveButton,
            forceDisableBlockTools
          }
        ),
        editorNotices: /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(Notices, {}),
        secondarySidebar: !isPreviewMode && mode === "visual" && (isInserterOpened2 && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(InserterSidebar, {}) || isListViewOpened2 && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(ListViewSidebar, {})),
        sidebar: !isPreviewMode && !isDistractionFree && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(complementary_area_default.Slot, { scope: "core" }),
        content: /* @__PURE__ */ (0, import_jsx_runtime515.jsxs)(import_jsx_runtime515.Fragment, { children: [
          !isDistractionFree && !isPreviewMode && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(Notices, {}),
          shouldShowStylesCanvas && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(StylesCanvas, {}),
          shouldShowBlockEditor && /* @__PURE__ */ (0, import_jsx_runtime515.jsxs)(import_jsx_runtime515.Fragment, { children: [
            !isPreviewMode && mode === "text" && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
              TextEditor,
              {
                autoFocus
              }
            ),
            !isPreviewMode && !isLargeViewport && mode === "visual" && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(import_block_editor85.BlockToolbar, { hideDragHandle: true }),
            (isPreviewMode || mode === "visual") && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
              visual_editor_default,
              {
                contentRef,
                autoFocus,
                iframeProps
              }
            ),
            children,
            /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
              CollaboratorsOverlay,
              {
                postId: postId2,
                postType: postType2
              }
            )
          ] })
        ] }),
        footer: !isPreviewMode && !isDistractionFree && isLargeViewport && showBlockBreadcrumbs && mode === "visual" && /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
          import_block_editor85.BlockBreadcrumb,
          {
            rootLabelText: postTypeLabel ? (0, import_html_entities31.decodeEntities)(postTypeLabel) : void 0
          }
        ),
        actions: !isPreviewMode ? customSavePanel || /* @__PURE__ */ (0, import_jsx_runtime515.jsx)(
          SavePublishPanels,
          {
            closeEntitiesSavedStates,
            isEntitiesSavedStatesOpen: entitiesSavedStatesCallback,
            setEntitiesSavedStatesCallback,
            forceIsDirtyPublishPanel: forceIsDirty
          }
        ) : void 0
      }
    );
  }

  // packages/editor/build-module/components/sidebar/index.mjs
  var import_block_editor97 = __toESM(require_block_editor(), 1);
  var import_data257 = __toESM(require_data(), 1);
  var import_element332 = __toESM(require_element(), 1);
  var import_i18n334 = __toESM(require_i18n(), 1);
  var import_keyboard_shortcuts11 = __toESM(require_keyboard_shortcuts(), 1);
  var import_components277 = __toESM(require_components(), 1);

  // packages/editor/build-module/components/pattern-overrides-panel/index.mjs
  var import_data227 = __toESM(require_data(), 1);
  var import_patterns10 = __toESM(require_patterns(), 1);
  var import_jsx_runtime516 = __toESM(require_jsx_runtime(), 1);
  var { OverridesPanel } = unlock(import_patterns10.privateApis);
  function PatternOverridesPanel() {
    const supportsPatternOverridesPanel = (0, import_data227.useSelect)(
      (select9) => select9(store).getCurrentPostType() === "wp_block",
      []
    );
    if (!supportsPatternOverridesPanel) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime516.jsx)(OverridesPanel, {});
  }

  // packages/editor/build-module/components/sidebar/post-summary.mjs
  var import_data239 = __toESM(require_data(), 1);

  // packages/editor/build-module/components/post-card-panel/index.mjs
  var import_components260 = __toESM(require_components(), 1);
  var import_core_data125 = __toESM(require_core_data(), 1);
  var import_data232 = __toESM(require_data(), 1);
  var import_element316 = __toESM(require_element(), 1);
  var import_i18n314 = __toESM(require_i18n(), 1);
  var import_dom27 = __toESM(require_dom(), 1);

  // packages/editor/build-module/components/post-actions/index.mjs
  var import_data231 = __toESM(require_data(), 1);
  var import_element315 = __toESM(require_element(), 1);
  var import_i18n313 = __toESM(require_i18n(), 1);
  var import_components259 = __toESM(require_components(), 1);
  var import_core_data124 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/post-actions/actions.mjs
  var import_data230 = __toESM(require_data(), 1);
  var import_element314 = __toESM(require_element(), 1);
  var import_core_data123 = __toESM(require_core_data(), 1);

  // packages/editor/build-module/components/post-actions/set-as-homepage.mjs
  var import_i18n311 = __toESM(require_i18n(), 1);
  var import_element312 = __toESM(require_element(), 1);
  var import_components257 = __toESM(require_components(), 1);
  var import_data228 = __toESM(require_data(), 1);
  var import_core_data121 = __toESM(require_core_data(), 1);
  var import_notices33 = __toESM(require_notices(), 1);

  // packages/editor/build-module/utils/get-item-title.mjs
  var import_html_entities32 = __toESM(require_html_entities(), 1);
  function getItemTitle2(item) {
    if (typeof item.title === "string") {
      return (0, import_html_entities32.decodeEntities)(item.title);
    }
    if (item.title && "rendered" in item.title) {
      return (0, import_html_entities32.decodeEntities)(item.title.rendered);
    }
    if (item.title && "raw" in item.title) {
      return (0, import_html_entities32.decodeEntities)(item.title.raw);
    }
    return "";
  }

  // packages/editor/build-module/components/post-actions/set-as-homepage.mjs
  var import_jsx_runtime517 = __toESM(require_jsx_runtime(), 1);
  var SetAsHomepageModal = ({ items, closeModal: closeModal2 }) => {
    const [item] = items;
    const pageTitle = getItemTitle2(item);
    const { showOnFront, currentHomePage, isSaving } = (0, import_data228.useSelect)(
      (select9) => {
        const { getEntityRecord, isSavingEntityRecord } = select9(import_core_data121.store);
        const siteSettings = getEntityRecord("root", "site");
        const currentHomePageItem = getEntityRecord(
          "postType",
          "page",
          siteSettings?.page_on_front
        );
        return {
          showOnFront: siteSettings?.show_on_front,
          currentHomePage: currentHomePageItem,
          isSaving: isSavingEntityRecord("root", "site")
        };
      }
    );
    const { saveEntityRecord } = (0, import_data228.useDispatch)(import_core_data121.store);
    const { createSuccessNotice, createErrorNotice } = (0, import_data228.useDispatch)(import_notices33.store);
    async function onSetPageAsHomepage(event) {
      event.preventDefault();
      try {
        await saveEntityRecord("root", "site", {
          page_on_front: item.id,
          show_on_front: "page"
        });
        createSuccessNotice((0, import_i18n311.__)("Homepage updated."), {
          type: "snackbar"
        });
      } catch (error2) {
        const errorMessage = error2.message && error2.code !== "unknown_error" ? error2.message : (0, import_i18n311.__)("An error occurred while setting the homepage.");
        createErrorNotice(errorMessage, { type: "snackbar" });
      } finally {
        closeModal2?.();
      }
    }
    let modalWarning = "";
    if ("posts" === showOnFront) {
      modalWarning = (0, import_i18n311.__)(
        "This will replace the current homepage which is set to display latest posts."
      );
    } else if (currentHomePage) {
      modalWarning = (0, import_i18n311.sprintf)(
        // translators: %s: title of the current home page.
        (0, import_i18n311.__)('This will replace the current homepage: "%s"'),
        getItemTitle2(currentHomePage)
      );
    }
    const modalText = (0, import_i18n311.sprintf)(
      // translators: %1$s: title of the page to be set as the homepage, %2$s: homepage replacement warning message.
      (0, import_i18n311.__)('Set "%1$s" as the site homepage? %2$s'),
      pageTitle,
      modalWarning
    ).trim();
    const modalButtonLabel = (0, import_i18n311.__)("Set homepage");
    return /* @__PURE__ */ (0, import_jsx_runtime517.jsx)("form", { onSubmit: onSetPageAsHomepage, children: /* @__PURE__ */ (0, import_jsx_runtime517.jsxs)(import_components257.__experimentalVStack, { spacing: "5", children: [
      /* @__PURE__ */ (0, import_jsx_runtime517.jsx)(import_components257.__experimentalText, { children: modalText }),
      /* @__PURE__ */ (0, import_jsx_runtime517.jsxs)(import_components257.__experimentalHStack, { justify: "right", children: [
        /* @__PURE__ */ (0, import_jsx_runtime517.jsx)(
          import_components257.Button,
          {
            __next40pxDefaultSize: true,
            variant: "tertiary",
            onClick: () => {
              closeModal2?.();
            },
            disabled: isSaving,
            accessibleWhenDisabled: true,
            children: (0, import_i18n311.__)("Cancel")
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime517.jsx)(
          import_components257.Button,
          {
            __next40pxDefaultSize: true,
            variant: "primary",
            type: "submit",
            disabled: isSaving,
            accessibleWhenDisabled: true,
            children: modalButtonLabel
          }
        )
      ] })
    ] }) });
  };
  var useSetAsHomepageAction = () => {
    const { pageOnFront, pageForPosts } = (0, import_data228.useSelect)((select9) => {
      const { getEntityRecord, canUser } = select9(import_core_data121.store);
      const siteSettings = canUser("read", {
        kind: "root",
        name: "site"
      }) ? getEntityRecord("root", "site") : void 0;
      return {
        pageOnFront: siteSettings?.page_on_front,
        pageForPosts: siteSettings?.page_for_posts
      };
    });
    return (0, import_element312.useMemo)(
      () => ({
        id: "set-as-homepage",
        label: (0, import_i18n311.__)("Set as homepage"),
        isEligible(post2) {
          if (post2.status !== "publish") {
            return false;
          }
          if (post2.type !== "page") {
            return false;
          }
          if (pageOnFront === post2.id) {
            return false;
          }
          if (pageForPosts === post2.id) {
            return false;
          }
          return true;
        },
        modalFocusOnMount: "firstContentElement",
        RenderModal: SetAsHomepageModal
      }),
      [pageForPosts, pageOnFront]
    );
  };

  // packages/editor/build-module/components/post-actions/set-as-posts-page.mjs
  var import_i18n312 = __toESM(require_i18n(), 1);
  var import_element313 = __toESM(require_element(), 1);
  var import_components258 = __toESM(require_components(), 1);
  var import_data229 = __toESM(require_data(), 1);
  var import_core_data122 = __toESM(require_core_data(), 1);
  var import_notices34 = __toESM(require_notices(), 1);
  var import_jsx_runtime518 = __toESM(require_jsx_runtime(), 1);
  var SetAsPostsPageModal = ({ items, closeModal: closeModal2 }) => {
    const [item] = items;
    const pageTitle = getItemTitle2(item);
    const { currentPostsPage, isPageForPostsSet, isSaving } = (0, import_data229.useSelect)(
      (select9) => {
        const { getEntityRecord, isSavingEntityRecord } = select9(import_core_data122.store);
        const siteSettings = getEntityRecord("root", "site");
        const currentPostsPageItem = getEntityRecord(
          "postType",
          "page",
          siteSettings?.page_for_posts
        );
        return {
          currentPostsPage: currentPostsPageItem,
          isPageForPostsSet: siteSettings?.page_for_posts !== 0,
          isSaving: isSavingEntityRecord("root", "site")
        };
      }
    );
    const { saveEntityRecord } = (0, import_data229.useDispatch)(import_core_data122.store);
    const { createSuccessNotice, createErrorNotice } = (0, import_data229.useDispatch)(import_notices34.store);
    async function onSetPageAsPostsPage(event) {
      event.preventDefault();
      try {
        await saveEntityRecord("root", "site", {
          page_for_posts: item.id,
          show_on_front: "page"
        });
        createSuccessNotice((0, import_i18n312.__)("Posts page updated."), {
          type: "snackbar"
        });
      } catch (error2) {
        const errorMessage = error2.message && error2.code !== "unknown_error" ? error2.message : (0, import_i18n312.__)("An error occurred while setting the posts page.");
        createErrorNotice(errorMessage, { type: "snackbar" });
      } finally {
        closeModal2?.();
      }
    }
    const modalWarning = isPageForPostsSet && currentPostsPage ? (0, import_i18n312.sprintf)(
      // translators: %s: title of the current posts page.
      (0, import_i18n312.__)('This will replace the current posts page: "%s"'),
      getItemTitle2(currentPostsPage)
    ) : (0, import_i18n312.__)("This page will show the latest posts.");
    const modalText = (0, import_i18n312.sprintf)(
      // translators: %1$s: title of the page to be set as the posts page, %2$s: posts page replacement warning message.
      (0, import_i18n312.__)('Set "%1$s" as the posts page? %2$s'),
      pageTitle,
      modalWarning
    );
    const modalButtonLabel = (0, import_i18n312.__)("Set posts page");
    return /* @__PURE__ */ (0, import_jsx_runtime518.jsx)("form", { onSubmit: onSetPageAsPostsPage, children: /* @__PURE__ */ (0, import_jsx_runtime518.jsxs)(import_components258.__experimentalVStack, { spacing: "5", children: [
      /* @__PURE__ */ (0, import_jsx_runtime518.jsx)(import_components258.__experimentalText, { children: modalText }),
      /* @__PURE__ */ (0, import_jsx_runtime518.jsxs)(import_components258.__experimentalHStack, { justify: "right", children: [
        /* @__PURE__ */ (0, import_jsx_runtime518.jsx)(
          import_components258.Button,
          {
            __next40pxDefaultSize: true,
            variant: "tertiary",
            onClick: () => {
              closeModal2?.();
            },
            disabled: isSaving,
            accessibleWhenDisabled: true,
            children: (0, import_i18n312.__)("Cancel")
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime518.jsx)(
          import_components258.Button,
          {
            __next40pxDefaultSize: true,
            variant: "primary",
            type: "submit",
            disabled: isSaving,
            accessibleWhenDisabled: true,
            children: modalButtonLabel
          }
        )
      ] })
    ] }) });
  };
  var useSetAsPostsPageAction = () => {
    const { pageOnFront, pageForPosts } = (0, import_data229.useSelect)((select9) => {
      const { getEntityRecord, canUser } = select9(import_core_data122.store);
      const siteSettings = canUser("read", {
        kind: "root",
        name: "site"
      }) ? getEntityRecord("root", "site") : void 0;
      return {
        pageOnFront: siteSettings?.page_on_front,
        pageForPosts: siteSettings?.page_for_posts
      };
    });
    return (0, import_element313.useMemo)(
      () => ({
        id: "set-as-posts-page",
        label: (0, import_i18n312.__)("Set as posts page"),
        isEligible(post2) {
          if (post2.status !== "publish") {
            return false;
          }
          if (post2.type !== "page") {
            return false;
          }
          if (pageOnFront === post2.id) {
            return false;
          }
          if (pageForPosts === post2.id) {
            return false;
          }
          return true;
        },
        modalFocusOnMount: "firstContentElement",
        RenderModal: SetAsPostsPageModal
      }),
      [pageForPosts, pageOnFront]
    );
  };

  // packages/editor/build-module/components/post-actions/actions.mjs
  var import_jsx_runtime519 = __toESM(require_jsx_runtime(), 1);
  function usePostActions({ postType: postType2, onActionPerformed, context }) {
    const { defaultActions } = (0, import_data230.useSelect)(
      (select9) => {
        const { getEntityActions: getEntityActions3 } = unlock(select9(store));
        return {
          defaultActions: getEntityActions3("postType", postType2)
        };
      },
      [postType2]
    );
    const shouldShowHomepageActions = (0, import_data230.useSelect)(
      (select9) => {
        if (postType2 !== "page") {
          return false;
        }
        const { getDefaultTemplateId, getEntityRecord, canUser } = select9(import_core_data123.store);
        const canUpdateSettings = canUser("update", {
          kind: "root",
          name: "site"
        });
        if (!canUpdateSettings) {
          return false;
        }
        const frontPageTemplateId = getDefaultTemplateId({
          slug: "front-page"
        });
        if (!frontPageTemplateId) {
          return true;
        }
        const frontPageTemplate = getEntityRecord(
          "postType",
          "wp_template",
          frontPageTemplateId
        );
        if (!frontPageTemplate) {
          return true;
        }
        return frontPageTemplate.slug !== "front-page";
      },
      [postType2]
    );
    const setAsHomepageAction = useSetAsHomepageAction();
    const setAsPostsPageAction = useSetAsPostsPageAction();
    const { registerPostTypeSchema: registerPostTypeSchema2 } = unlock((0, import_data230.useDispatch)(store));
    (0, import_element314.useEffect)(() => {
      registerPostTypeSchema2(postType2);
    }, [registerPostTypeSchema2, postType2]);
    return (0, import_element314.useMemo)(() => {
      let actions2 = [...defaultActions];
      if (shouldShowHomepageActions) {
        actions2.push(setAsHomepageAction, setAsPostsPageAction);
      }
      actions2 = actions2.sort(
        (a3, b3) => b3.id === "move-to-trash" ? -1 : 0
      );
      actions2 = actions2.filter((action) => {
        if (!action.context) {
          return true;
        }
        return action.context === context;
      });
      if (onActionPerformed) {
        for (let i3 = 0; i3 < actions2.length; ++i3) {
          if (actions2[i3].callback) {
            const existingCallback = actions2[i3].callback;
            actions2[i3] = {
              ...actions2[i3],
              callback: (items, argsObject) => {
                existingCallback(items, {
                  ...argsObject,
                  onActionPerformed: (_items) => {
                    if (argsObject?.onActionPerformed) {
                      argsObject.onActionPerformed(_items);
                    }
                    onActionPerformed(
                      actions2[i3].id,
                      _items
                    );
                  }
                });
              }
            };
          }
          if (actions2[i3].RenderModal) {
            const ExistingRenderModal = actions2[i3].RenderModal;
            actions2[i3] = {
              ...actions2[i3],
              RenderModal: (props) => {
                return /* @__PURE__ */ (0, import_jsx_runtime519.jsx)(
                  ExistingRenderModal,
                  {
                    ...props,
                    onActionPerformed: (_items) => {
                      if (props.onActionPerformed) {
                        props.onActionPerformed(_items);
                      }
                      onActionPerformed(
                        actions2[i3].id,
                        _items
                      );
                    }
                  }
                );
              }
            };
          }
        }
      }
      return actions2;
    }, [
      context,
      defaultActions,
      onActionPerformed,
      setAsHomepageAction,
      setAsPostsPageAction,
      shouldShowHomepageActions
    ]);
  }

  // packages/editor/build-module/components/post-actions/index.mjs
  var import_jsx_runtime520 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu10, kebabCase: kebabCase5 } = unlock(import_components259.privateApis);
  function PostActions({ postType: postType2, postId: postId2, onActionPerformed }) {
    const [activeModalAction, setActiveModalAction] = (0, import_element315.useState)(null);
    const { item, permissions } = (0, import_data231.useSelect)(
      (select9) => {
        const { getEditedEntityRecord, getEntityRecordPermissions } = unlock(select9(import_core_data124.store));
        return {
          item: getEditedEntityRecord("postType", postType2, postId2),
          permissions: getEntityRecordPermissions(
            "postType",
            postType2,
            postId2
          )
        };
      },
      [postId2, postType2]
    );
    const itemWithPermissions = (0, import_element315.useMemo)(() => {
      return {
        ...item,
        permissions
      };
    }, [item, permissions]);
    const allActions = usePostActions({ postType: postType2, onActionPerformed });
    const actions2 = (0, import_element315.useMemo)(() => {
      return allActions.filter((action) => {
        return !action.isEligible || action.isEligible(itemWithPermissions);
      });
    }, [allActions, itemWithPermissions]);
    return /* @__PURE__ */ (0, import_jsx_runtime520.jsxs)(import_jsx_runtime520.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime520.jsxs)(Menu10, { placement: "bottom-end", children: [
        /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(
          Menu10.TriggerButton,
          {
            render: /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(
              import_components259.Button,
              {
                size: "small",
                icon: more_vertical_default,
                label: (0, import_i18n313.__)("Actions"),
                disabled: !actions2.length,
                accessibleWhenDisabled: true,
                className: "editor-all-actions-button"
              }
            )
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(Menu10.Popover, { children: /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(
          ActionsDropdownMenuGroup,
          {
            actions: actions2,
            items: [itemWithPermissions],
            setActiveModalAction
          }
        ) })
      ] }),
      !!activeModalAction && /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(
        ActionModal2,
        {
          action: activeModalAction,
          items: [itemWithPermissions],
          closeModal: () => setActiveModalAction(null)
        }
      )
    ] });
  }
  function DropdownMenuItemTrigger({ action, onClick, items }) {
    const label = typeof action.label === "string" ? action.label : action.label(items);
    return /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(Menu10.Item, { onClick, children: /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(Menu10.ItemLabel, { children: label }) });
  }
  function ActionModal2({ action, items, closeModal: closeModal2 }) {
    const label = typeof action.label === "string" ? action.label : action.label(items);
    return /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(
      import_components259.Modal,
      {
        title: action.modalHeader || label,
        __experimentalHideHeader: !!action.hideModalHeader,
        onRequestClose: closeModal2 ?? (() => {
        }),
        focusOnMount: "firstContentElement",
        size: "medium",
        overlayClassName: `editor-action-modal editor-action-modal__${kebabCase5(
          action.id
        )}`,
        children: /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(action.RenderModal, { items, closeModal: closeModal2 })
      }
    );
  }
  function ActionsDropdownMenuGroup({ actions: actions2, items, setActiveModalAction }) {
    const registry = (0, import_data231.useRegistry)();
    return /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(Menu10.Group, { children: actions2.map((action) => {
      return /* @__PURE__ */ (0, import_jsx_runtime520.jsx)(
        DropdownMenuItemTrigger,
        {
          action,
          onClick: () => {
            if ("RenderModal" in action) {
              setActiveModalAction(action);
              return;
            }
            action.callback(items, { registry });
          },
          items
        },
        action.id
      );
    }) });
  }

  // packages/editor/build-module/components/post-card-panel/index.mjs
  var import_jsx_runtime521 = __toESM(require_jsx_runtime(), 1);
  var { Badge: WCBadge5 } = unlock(import_components260.privateApis);
  function PostCardPanel({
    postType: postType2,
    postId: postId2,
    hideActions = false,
    onActionPerformed,
    onClose
  }) {
    const postIds = (0, import_element316.useMemo)(
      () => Array.isArray(postId2) ? postId2 : [postId2],
      [postId2]
    );
    const { postTitle, icon, labels } = (0, import_data232.useSelect)(
      (select9) => {
        const { getEditedEntityRecord, getCurrentTheme, getPostType } = select9(import_core_data125.store);
        const {
          getPostIcon: getPostIcon2,
          getCurrentPostType: getCurrentPostType2,
          isRevisionsMode: isRevisionsMode2,
          getCurrentRevision: getCurrentRevision2
        } = unlock(select9(store));
        let _title = "";
        if (isRevisionsMode2()) {
          const parentPostType = getCurrentPostType2();
          const _record2 = getCurrentRevision2();
          _title = _record2?.title?.rendered || _record2?.title?.raw || "";
          return {
            postTitle: _title,
            icon: getPostIcon2(parentPostType, {
              area: _record2?.area
            }),
            labels: getPostType(parentPostType)?.labels
          };
        }
        const _record = getEditedEntityRecord(
          "postType",
          postType2,
          postIds[0]
        );
        if (postIds.length === 1) {
          const { default_template_types: templateTypes = [] } = getCurrentTheme() ?? {};
          const _templateInfo = [
            TEMPLATE_POST_TYPE,
            TEMPLATE_PART_POST_TYPE
          ].includes(postType2) ? getTemplateInfo({
            template: _record,
            templateTypes
          }) : {};
          _title = _templateInfo?.title || _record?.title;
        }
        return {
          postTitle: _title,
          icon: getPostIcon2(postType2, {
            area: _record?.area
          }),
          labels: getPostType(postType2)?.labels
        };
      },
      [postIds, postType2]
    );
    const pageTypeBadge = usePageTypeBadge(postId2);
    let title = (0, import_i18n314.__)("No title");
    if (labels?.name && postIds.length > 1) {
      title = (0, import_i18n314.sprintf)(
        // translators: %1$d number of selected items %2$s: Name of the plural post type e.g: "Posts".
        (0, import_i18n314.__)("%1$d %2$s"),
        postIds.length,
        labels?.name
      );
    } else if (postTitle) {
      title = (0, import_dom27.__unstableStripHTML)(postTitle);
    }
    return /* @__PURE__ */ (0, import_jsx_runtime521.jsxs)(import_components260.__experimentalVStack, { spacing: 1, className: "editor-post-card-panel", children: [
      /* @__PURE__ */ (0, import_jsx_runtime521.jsxs)(
        import_components260.__experimentalHStack,
        {
          spacing: 2,
          className: "editor-post-card-panel__header",
          alignment: "flex-start",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
              import_components260.Icon,
              {
                className: "editor-post-card-panel__icon",
                icon
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime521.jsxs)(
              import_components260.__experimentalText,
              {
                numberOfLines: 2,
                truncate: true,
                className: "editor-post-card-panel__title",
                as: "h2",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime521.jsx)("span", { className: "editor-post-card-panel__title-name", children: title }),
                  pageTypeBadge && postIds.length === 1 && /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(WCBadge5, { children: pageTypeBadge })
                ]
              }
            ),
            !hideActions && postIds.length === 1 && /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
              PostActions,
              {
                postType: postType2,
                postId: postIds[0],
                onActionPerformed
              }
            ),
            onClose && /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(
              import_components260.Button,
              {
                size: "small",
                icon: close_default,
                label: (0, import_i18n314.__)("Close"),
                onClick: onClose
              }
            )
          ]
        }
      ),
      postIds.length > 1 && /* @__PURE__ */ (0, import_jsx_runtime521.jsx)(import_components260.__experimentalText, { className: "editor-post-card-panel__description", children: (0, import_i18n314.sprintf)(
        // translators: %s: Name of the plural post type e.g: "Posts".
        (0, import_i18n314.__)("Changes will be applied to all selected %s."),
        labels?.name?.toLowerCase()
      ) })
    ] });
  }

  // packages/editor/build-module/components/post-content-information/index.mjs
  var import_components261 = __toESM(require_components(), 1);
  var import_data233 = __toESM(require_data(), 1);
  var import_i18n315 = __toESM(require_i18n(), 1);
  var import_wordcount5 = __toESM(require_wordcount(), 1);
  var import_element317 = __toESM(require_element(), 1);
  var import_core_data126 = __toESM(require_core_data(), 1);
  var import_jsx_runtime522 = __toESM(require_jsx_runtime(), 1);
  var AVERAGE_READING_RATE3 = 189;
  function PostContentInformation() {
    const postContent = (0, import_data233.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2, getCurrentPostType: getCurrentPostType2, getCurrentPostId: getCurrentPostId2 } = select9(store);
      const { canUser } = select9(import_core_data126.store);
      const { getEntityRecord } = select9(import_core_data126.store);
      const siteSettings = canUser("read", {
        kind: "root",
        name: "site"
      }) ? getEntityRecord("root", "site") : void 0;
      const postType2 = getCurrentPostType2();
      const _id = getCurrentPostId2();
      const isPostsPage = +_id === siteSettings?.page_for_posts;
      const showPostContentInfo = !isPostsPage && ![TEMPLATE_POST_TYPE, TEMPLATE_PART_POST_TYPE].includes(
        postType2
      );
      return showPostContentInfo && getEditedPostAttribute2("content");
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(PostContentInformationUI, { postContent });
  }
  function PostContentInformationUI({ postContent }) {
    const wordCountType = (0, import_i18n315._x)("words", "Word count type. Do not translate!");
    const wordsCounted = (0, import_element317.useMemo)(
      () => postContent ? (0, import_wordcount5.count)(postContent, wordCountType) : 0,
      [postContent, wordCountType]
    );
    if (!wordsCounted) {
      return null;
    }
    const readingTime = Math.round(wordsCounted / AVERAGE_READING_RATE3);
    const wordsCountText = (0, import_i18n315.sprintf)(
      // translators: %s: the number of words in the post.
      (0, import_i18n315._n)("%s word", "%s words", wordsCounted),
      wordsCounted.toLocaleString()
    );
    const minutesText = readingTime <= 1 ? (0, import_i18n315.__)("1 minute") : (0, import_i18n315.sprintf)(
      /* translators: %s: the number of minutes to read the post. */
      (0, import_i18n315._n)("%s minute", "%s minutes", readingTime),
      readingTime.toLocaleString()
    );
    return /* @__PURE__ */ (0, import_jsx_runtime522.jsx)("div", { className: "editor-post-content-information", children: /* @__PURE__ */ (0, import_jsx_runtime522.jsx)(import_components261.__experimentalText, { children: (0, import_i18n315.sprintf)(
      /* translators: 1: How many words a post has. 2: the number of minutes to read the post (e.g. 130 words, 2 minutes read time.) */
      (0, import_i18n315.__)("%1$s, %2$s read time."),
      wordsCountText,
      minutesText
    ) }) });
  }

  // packages/editor/build-module/components/post-format/panel.mjs
  var import_components262 = __toESM(require_components(), 1);
  var import_i18n316 = __toESM(require_i18n(), 1);
  var import_data234 = __toESM(require_data(), 1);
  var import_element318 = __toESM(require_element(), 1);
  var import_block_editor86 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime523 = __toESM(require_jsx_runtime(), 1);
  function PostFormat2() {
    const { postFormat } = (0, import_data234.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2 } = select9(store);
      const _postFormat = getEditedPostAttribute2("format");
      return {
        postFormat: _postFormat ?? "standard"
      };
    }, []);
    const activeFormat = POST_FORMATS2.find(
      (format6) => format6.id === postFormat
    );
    const [popoverAnchor, setPopoverAnchor] = (0, import_element318.useState)(null);
    const popoverProps = (0, import_element318.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]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime523.jsx)(PostFormatCheck, { children: /* @__PURE__ */ (0, import_jsx_runtime523.jsx)(post_panel_row_default, { label: (0, import_i18n316.__)("Format"), ref: setPopoverAnchor, children: /* @__PURE__ */ (0, import_jsx_runtime523.jsx)(
      import_components262.Dropdown,
      {
        popoverProps,
        contentClassName: "editor-post-format__dialog",
        focusOnMount: true,
        renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime523.jsx)(
          import_components262.Button,
          {
            size: "compact",
            variant: "tertiary",
            "aria-expanded": isOpen2,
            "aria-label": (0, import_i18n316.sprintf)(
              // translators: %s: Current post format.
              (0, import_i18n316.__)("Change format: %s"),
              activeFormat?.caption
            ),
            onClick: onToggle,
            children: activeFormat?.caption
          }
        ),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime523.jsxs)("div", { className: "editor-post-format__dialog-content", children: [
          /* @__PURE__ */ (0, import_jsx_runtime523.jsx)(
            import_block_editor86.__experimentalInspectorPopoverHeader,
            {
              title: (0, import_i18n316.__)("Format"),
              onClose
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime523.jsx)(PostFormat, {})
        ] })
      }
    ) }) });
  }
  var panel_default4 = PostFormat2;

  // packages/editor/build-module/components/post-last-edited-panel/index.mjs
  var import_components263 = __toESM(require_components(), 1);
  var import_data235 = __toESM(require_data(), 1);
  var import_i18n317 = __toESM(require_i18n(), 1);
  var import_date20 = __toESM(require_date(), 1);
  var import_jsx_runtime524 = __toESM(require_jsx_runtime(), 1);
  function PostLastEditedPanel() {
    const modified = (0, import_data235.useSelect)(
      (select9) => select9(store).getEditedPostAttribute("modified"),
      []
    );
    if (!modified) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime524.jsx)("div", { className: "editor-post-last-edited-panel", children: /* @__PURE__ */ (0, import_jsx_runtime524.jsx)(import_components263.__experimentalText, { children: (0, import_i18n317.sprintf)(
      // translators: %s: Human-readable time difference, e.g. "2 days ago".
      (0, import_i18n317.__)("Last edited %s."),
      (0, import_date20.humanTimeDiff)(modified)
    ) }) });
  }

  // packages/editor/build-module/components/post-panel-section/index.mjs
  var import_components264 = __toESM(require_components(), 1);
  var import_jsx_runtime525 = __toESM(require_jsx_runtime(), 1);
  function PostPanelSection({ className, children }) {
    return /* @__PURE__ */ (0, import_jsx_runtime525.jsx)(import_components264.__experimentalVStack, { className: clsx_default("editor-post-panel__section", className), children });
  }
  var post_panel_section_default = PostPanelSection;

  // packages/editor/build-module/components/blog-title/index.mjs
  var import_i18n318 = __toESM(require_i18n(), 1);
  var import_compose80 = __toESM(require_compose(), 1);
  var import_data236 = __toESM(require_data(), 1);
  var import_core_data127 = __toESM(require_core_data(), 1);
  var import_html_entities33 = __toESM(require_html_entities(), 1);
  var import_components265 = __toESM(require_components(), 1);
  var import_element319 = __toESM(require_element(), 1);
  var import_block_editor87 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime526 = __toESM(require_jsx_runtime(), 1);
  var EMPTY_OBJECT5 = {};
  function BlogTitle() {
    const { editEntityRecord } = (0, import_data236.useDispatch)(import_core_data127.store);
    const { postsPageTitle, postsPageId, isTemplate: isTemplate2, postSlug } = (0, import_data236.useSelect)(
      (select9) => {
        const { getEntityRecord, getEditedEntityRecord, canUser } = select9(import_core_data127.store);
        const siteSettings = canUser("read", {
          kind: "root",
          name: "site"
        }) ? getEntityRecord("root", "site") : void 0;
        const _postsPageRecord = siteSettings?.page_for_posts ? getEditedEntityRecord(
          "postType",
          "page",
          siteSettings?.page_for_posts
        ) : EMPTY_OBJECT5;
        const { getEditedPostAttribute: getEditedPostAttribute2, getCurrentPostType: getCurrentPostType2 } = select9(store);
        return {
          postsPageId: _postsPageRecord?.id,
          postsPageTitle: _postsPageRecord?.title,
          isTemplate: getCurrentPostType2() === TEMPLATE_POST_TYPE,
          postSlug: getEditedPostAttribute2("slug")
        };
      },
      []
    );
    const [popoverAnchor, setPopoverAnchor] = (0, import_element319.useState)(null);
    const popoverProps = (0, import_element319.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]
    );
    if (!isTemplate2 || !["home", "index"].includes(postSlug) || !postsPageId) {
      return null;
    }
    const setPostsPageTitle = (newValue) => {
      editEntityRecord("postType", "page", postsPageId, {
        title: newValue
      });
    };
    const decodedTitle = (0, import_html_entities33.decodeEntities)(postsPageTitle);
    return /* @__PURE__ */ (0, import_jsx_runtime526.jsx)(post_panel_row_default, { label: (0, import_i18n318.__)("Blog title"), ref: setPopoverAnchor, children: /* @__PURE__ */ (0, import_jsx_runtime526.jsx)(
      import_components265.Dropdown,
      {
        popoverProps,
        contentClassName: "editor-blog-title-dropdown__content",
        focusOnMount: true,
        renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime526.jsx)(
          import_components265.Button,
          {
            size: "compact",
            variant: "tertiary",
            "aria-expanded": isOpen2,
            "aria-label": (0, import_i18n318.sprintf)(
              // translators: %s: Current post link.
              (0, import_i18n318.__)("Change blog title: %s"),
              decodedTitle
            ),
            onClick: onToggle,
            children: decodedTitle
          }
        ),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime526.jsxs)(import_jsx_runtime526.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime526.jsx)(
            import_block_editor87.__experimentalInspectorPopoverHeader,
            {
              title: (0, import_i18n318.__)("Blog title"),
              onClose
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime526.jsx)(
            import_components265.__experimentalInputControl,
            {
              placeholder: (0, import_i18n318.__)("No title"),
              value: postsPageTitle,
              onChange: (0, import_compose80.debounce)(setPostsPageTitle, 300),
              label: (0, import_i18n318.__)("Blog title"),
              help: (0, import_i18n318.__)(
                "Set the Posts Page title. Appears in search results, and when the page is shared on social media."
              ),
              hideLabelFromVision: true
            }
          )
        ] })
      }
    ) });
  }

  // packages/editor/build-module/components/posts-per-page/index.mjs
  var import_i18n319 = __toESM(require_i18n(), 1);
  var import_data237 = __toESM(require_data(), 1);
  var import_core_data128 = __toESM(require_core_data(), 1);
  var import_components266 = __toESM(require_components(), 1);
  var import_element320 = __toESM(require_element(), 1);
  var import_block_editor88 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime527 = __toESM(require_jsx_runtime(), 1);
  function PostsPerPage() {
    const { editEntityRecord } = (0, import_data237.useDispatch)(import_core_data128.store);
    const { postsPerPage, isTemplate: isTemplate2, postSlug } = (0, import_data237.useSelect)((select9) => {
      const { getEditedPostAttribute: getEditedPostAttribute2, getCurrentPostType: getCurrentPostType2 } = select9(store);
      const { getEditedEntityRecord, canUser } = select9(import_core_data128.store);
      const siteSettings = canUser("read", {
        kind: "root",
        name: "site"
      }) ? getEditedEntityRecord("root", "site") : void 0;
      return {
        isTemplate: getCurrentPostType2() === TEMPLATE_POST_TYPE,
        postSlug: getEditedPostAttribute2("slug"),
        postsPerPage: siteSettings?.posts_per_page || 1
      };
    }, []);
    const [popoverAnchor, setPopoverAnchor] = (0, import_element320.useState)(null);
    const popoverProps = (0, import_element320.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]
    );
    if (!isTemplate2 || !["home", "index"].includes(postSlug)) {
      return null;
    }
    const setPostsPerPage = (newValue) => {
      editEntityRecord("root", "site", void 0, {
        posts_per_page: newValue
      });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime527.jsx)(post_panel_row_default, { label: (0, import_i18n319.__)("Posts per page"), ref: setPopoverAnchor, children: /* @__PURE__ */ (0, import_jsx_runtime527.jsx)(
      import_components266.Dropdown,
      {
        popoverProps,
        contentClassName: "editor-posts-per-page-dropdown__content",
        focusOnMount: true,
        renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime527.jsx)(
          import_components266.Button,
          {
            size: "compact",
            variant: "tertiary",
            "aria-expanded": isOpen2,
            "aria-label": (0, import_i18n319.__)("Change posts per page"),
            onClick: onToggle,
            children: postsPerPage
          }
        ),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime527.jsxs)(import_jsx_runtime527.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime527.jsx)(
            import_block_editor88.__experimentalInspectorPopoverHeader,
            {
              title: (0, import_i18n319.__)("Posts per page"),
              onClose
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime527.jsx)(
            import_components266.__experimentalNumberControl,
            {
              placeholder: 0,
              value: postsPerPage,
              spinControls: "custom",
              step: "1",
              min: "1",
              onChange: setPostsPerPage,
              label: (0, import_i18n319.__)("Posts per page"),
              help: (0, import_i18n319.__)(
                "Set the default number of posts to display on blog pages, including categories and tags. Some templates may override this setting."
              ),
              hideLabelFromVision: true
            }
          )
        ] })
      }
    ) });
  }

  // packages/editor/build-module/components/site-discussion/index.mjs
  var import_i18n320 = __toESM(require_i18n(), 1);
  var import_data238 = __toESM(require_data(), 1);
  var import_core_data129 = __toESM(require_core_data(), 1);
  var import_components267 = __toESM(require_components(), 1);
  var import_element321 = __toESM(require_element(), 1);
  var import_block_editor89 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime528 = __toESM(require_jsx_runtime(), 1);
  var COMMENT_OPTIONS2 = [
    {
      label: (0, import_i18n320._x)("Open", 'Adjective: e.g. "Comments are open"'),
      value: "open",
      description: (0, import_i18n320.__)("Visitors can add new comments and replies.")
    },
    {
      label: (0, import_i18n320.__)("Closed"),
      value: "",
      description: [
        (0, import_i18n320.__)("Visitors cannot add new comments or replies."),
        (0, import_i18n320.__)("Existing comments remain visible.")
      ].join(" ")
    }
  ];
  function SiteDiscussion() {
    const { editEntityRecord } = (0, import_data238.useDispatch)(import_core_data129.store);
    const { allowCommentsOnNewPosts, isTemplate: isTemplate2, postSlug } = (0, import_data238.useSelect)(
      (select9) => {
        const { getEditedPostAttribute: getEditedPostAttribute2, getCurrentPostType: getCurrentPostType2 } = select9(store);
        const { getEditedEntityRecord, canUser } = select9(import_core_data129.store);
        const siteSettings = canUser("read", {
          kind: "root",
          name: "site"
        }) ? getEditedEntityRecord("root", "site") : void 0;
        return {
          isTemplate: getCurrentPostType2() === TEMPLATE_POST_TYPE,
          postSlug: getEditedPostAttribute2("slug"),
          allowCommentsOnNewPosts: siteSettings?.default_comment_status || ""
        };
      },
      []
    );
    const [popoverAnchor, setPopoverAnchor] = (0, import_element321.useState)(null);
    const popoverProps = (0, import_element321.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]
    );
    if (!isTemplate2 || !["home", "index"].includes(postSlug)) {
      return null;
    }
    const setAllowCommentsOnNewPosts = (newValue) => {
      editEntityRecord("root", "site", void 0, {
        default_comment_status: newValue ? "open" : null
      });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime528.jsx)(post_panel_row_default, { label: (0, import_i18n320.__)("Discussion"), ref: setPopoverAnchor, children: /* @__PURE__ */ (0, import_jsx_runtime528.jsx)(
      import_components267.Dropdown,
      {
        popoverProps,
        contentClassName: "editor-site-discussion-dropdown__content",
        focusOnMount: true,
        renderToggle: ({ isOpen: isOpen2, onToggle }) => /* @__PURE__ */ (0, import_jsx_runtime528.jsx)(
          import_components267.Button,
          {
            size: "compact",
            variant: "tertiary",
            "aria-expanded": isOpen2,
            "aria-label": (0, import_i18n320.__)("Change discussion settings"),
            onClick: onToggle,
            children: allowCommentsOnNewPosts ? (0, import_i18n320.__)("Comments open") : (0, import_i18n320.__)("Comments closed")
          }
        ),
        renderContent: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime528.jsxs)(import_jsx_runtime528.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime528.jsx)(
            import_block_editor89.__experimentalInspectorPopoverHeader,
            {
              title: (0, import_i18n320.__)("Discussion"),
              onClose
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime528.jsxs)(import_components267.__experimentalVStack, { spacing: 3, children: [
            /* @__PURE__ */ (0, import_jsx_runtime528.jsx)(import_components267.__experimentalText, { children: (0, import_i18n320.__)(
              "Changes will apply to new posts only. Individual posts may override these settings."
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime528.jsx)(
              import_components267.RadioControl,
              {
                className: "editor-site-discussion__options",
                hideLabelFromVision: true,
                label: (0, import_i18n320.__)("Comment status"),
                options: COMMENT_OPTIONS2,
                onChange: setAllowCommentsOnNewPosts,
                selected: allowCommentsOnNewPosts
              }
            )
          ] })
        ] })
      }
    ) });
  }

  // packages/editor/build-module/components/sidebar/post-summary.mjs
  var import_jsx_runtime529 = __toESM(require_jsx_runtime(), 1);
  var PANEL_NAME5 = "post-status";
  function PostSummary({ onActionPerformed }) {
    const { isRemovedPostStatusPanel, postType: postType2, postId: postId2 } = (0, import_data239.useSelect)(
      (select9) => {
        const {
          isEditorPanelRemoved: isEditorPanelRemoved2,
          getCurrentPostType: getCurrentPostType2,
          getCurrentPostId: getCurrentPostId2
        } = select9(store);
        return {
          isRemovedPostStatusPanel: isEditorPanelRemoved2(PANEL_NAME5),
          postType: getCurrentPostType2(),
          postId: getCurrentPostId2()
        };
      },
      []
    );
    return /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(post_panel_section_default, { className: "editor-post-summary", children: /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(plugin_post_status_info_default.Slot, { children: (fills) => /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(import_jsx_runtime529.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime529.jsxs)(Stack, { direction: "column", gap: "lg", children: [
      /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(
        PostCardPanel,
        {
          postType: postType2,
          postId: postId2,
          onActionPerformed
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PostFeaturedImagePanel, { withPanelBody: false }),
      /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PrivatePostExcerptPanel, {}),
      /* @__PURE__ */ (0, import_jsx_runtime529.jsxs)(Stack, { direction: "column", gap: "xs", children: [
        /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PostContentInformation, {}),
        /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PostLastEditedPanel, {})
      ] }),
      !isRemovedPostStatusPanel && /* @__PURE__ */ (0, import_jsx_runtime529.jsxs)(Stack, { direction: "column", gap: "lg", children: [
        /* @__PURE__ */ (0, import_jsx_runtime529.jsxs)(Stack, { direction: "column", gap: "xs", children: [
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PostStatus, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PostSchedulePanel, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PostURLPanel, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(panel_default, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PostTemplatePanel, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PostDiscussionPanel, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PrivatePostLastRevision, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PageAttributesPanel, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PostSyncStatus, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(BlogTitle, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(PostsPerPage, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(SiteDiscussion, {}),
          /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(panel_default4, {}),
          fills
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime529.jsx)(
          PostTrash,
          {
            onActionPerformed
          }
        )
      ] })
    ] }) }) }) });
  }

  // packages/editor/build-module/components/sidebar/dataform-post-summary.mjs
  var import_i18n323 = __toESM(require_i18n(), 1);
  var import_data244 = __toESM(require_data(), 1);
  var import_core_data131 = __toESM(require_core_data(), 1);
  var import_element323 = __toESM(require_element(), 1);

  // packages/views/build-module/use-view.mjs
  var import_element322 = __toESM(require_element(), 1);
  var import_data240 = __toESM(require_data(), 1);
  var import_preferences25 = __toESM(require_preferences(), 1);

  // packages/views/build-module/load-view.mjs
  var import_data241 = __toESM(require_data(), 1);
  var import_preferences26 = __toESM(require_preferences(), 1);

  // packages/views/build-module/use-view-config.mjs
  var import_data242 = __toESM(require_data(), 1);
  var import_core_data130 = __toESM(require_core_data(), 1);

  // packages/views/build-module/lock-unlock.mjs
  var import_private_apis11 = __toESM(require_private_apis(), 1);
  var { lock: lock8, unlock: unlock8 } = (0, import_private_apis11.__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_data242.useSelect)(
      (select9) => {
        return unlock8(select9(import_core_data130.store)).getViewConfig(kind, name2, {
          fields: fieldsKey
        });
      },
      [kind, name2, fieldsKey]
    );
  }

  // packages/editor/build-module/dataviews/fields/revisions/index.mjs
  var import_i18n322 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/dataviews/fields/revisions/revisions-view.mjs
  var import_components268 = __toESM(require_components(), 1);
  var import_data243 = __toESM(require_data(), 1);
  var import_i18n321 = __toESM(require_i18n(), 1);
  var import_url24 = __toESM(require_url(), 1);
  var import_jsx_runtime530 = __toESM(require_jsx_runtime(), 1);
  function RevisionsView() {
    const { lastRevisionId, revisionsCount, disableVisualRevisions } = (0, import_data243.useSelect)((select9) => {
      const {
        getCurrentPostLastRevisionId: getCurrentPostLastRevisionId2,
        getCurrentPostRevisionsCount: getCurrentPostRevisionsCount2,
        getEditorSettings: getEditorSettings2
        // @ts-ignore
      } = select9(store);
      return {
        lastRevisionId: getCurrentPostLastRevisionId2(),
        revisionsCount: getCurrentPostRevisionsCount2(),
        disableVisualRevisions: (
          // @ts-ignore
          !!getEditorSettings2().disableVisualRevisions
        )
      };
    }, []);
    const { setCurrentRevisionId: setCurrentRevisionId2 } = unlock((0, import_data243.useDispatch)(store));
    const buttonProps = disableVisualRevisions ? {
      href: (0, import_url24.addQueryArgs)("revision.php", {
        revision: lastRevisionId
      })
    } : { onClick: () => setCurrentRevisionId2(lastRevisionId) };
    return /* @__PURE__ */ (0, import_jsx_runtime530.jsx)(
      import_components268.Button,
      {
        ...buttonProps,
        variant: "link",
        text: String(revisionsCount),
        "aria-label": (0, import_i18n321.sprintf)(
          /* translators: %d: number of revisions. */
          (0, import_i18n321._n)(
            "Open revisions screen: %d revision",
            "Open revisions screen: %d revisions",
            revisionsCount
          ),
          revisionsCount
        )
      }
    );
  }

  // packages/editor/build-module/dataviews/fields/revisions/index.mjs
  var revisionsField = {
    id: "revisions",
    label: (0, import_i18n322.__)("Revisions"),
    readOnly: true,
    enableSorting: false,
    render: RevisionsView,
    isVisible: (item) => {
      const revisionsCount = item._links?.["version-history"]?.[0]?.count ?? 0;
      const lastRevisionId = item._links?.["predecessor-version"]?.[0]?.id ?? null;
      return !!lastRevisionId && revisionsCount >= 2;
    }
  };
  var revisions_default2 = revisionsField;

  // packages/editor/build-module/components/sidebar/dataform-post-summary.mjs
  var import_jsx_runtime531 = __toESM(require_jsx_runtime(), 1);
  var EMPTY_FORM = { layout: { type: "panel" }, fields: [] };
  var VIEW_CONFIG_FIELDS = ["form"];
  function useInspectorPanelVisibility(form) {
    const {
      isPostStatusRemoved,
      featuredImageEnabled,
      excerptEnabled,
      discussionEnabled,
      pageAttributesEnabled
    } = (0, import_data244.useSelect)((select9) => {
      const { isEditorPanelRemoved: isEditorPanelRemoved2, isEditorPanelEnabled: isEditorPanelEnabled2 } = select9(store);
      return {
        isPostStatusRemoved: isEditorPanelRemoved2("post-status"),
        featuredImageEnabled: isEditorPanelEnabled2("featured-image"),
        excerptEnabled: isEditorPanelEnabled2("post-excerpt"),
        discussionEnabled: isEditorPanelEnabled2("discussion-panel"),
        pageAttributesEnabled: isEditorPanelEnabled2("page-attributes")
      };
    }, []);
    const visibleForm = (0, import_element323.useMemo)(() => {
      if (!form.fields?.length) {
        return form;
      }
      const visibilityById = {
        featured_media: featuredImageEnabled,
        excerpt: excerptEnabled,
        "post-content-info": true,
        discussion: discussionEnabled && !isPostStatusRemoved,
        parent: pageAttributesEnabled && !isPostStatusRemoved
      };
      const isFieldVisible = (id) => id in visibilityById ? visibilityById[id] : !isPostStatusRemoved;
      const filterFields = (fields2) => fields2.reduce((acc, field) => {
        const id = typeof field === "string" ? field : field.id;
        if (!isFieldVisible(id)) {
          return acc;
        }
        if (typeof field !== "string" && Array.isArray(field.children)) {
          const children = filterFields(field.children);
          if (!children.length) {
            return acc;
          }
          acc.push({ ...field, children });
          return acc;
        }
        acc.push(field);
        return acc;
      }, []);
      return { ...form, fields: filterFields(form.fields) };
    }, [
      form,
      isPostStatusRemoved,
      featuredImageEnabled,
      excerptEnabled,
      discussionEnabled,
      pageAttributesEnabled
    ]);
    return visibleForm;
  }
  var ENTITIES = {
    wp_template: {
      root_site: {
        kind: "root",
        name: "site",
        fields: ["posts_per_page", "default_comment_status"],
        isVisible: (item) => ["home", "index"].includes(item.slug ?? "")
      },
      posttype_page: {
        kind: "postType",
        name: "page",
        getId: (select9) => select9(import_core_data131.store).getEditedEntityRecord("root", "site")?.page_for_posts,
        fields: ["posts_page_title"],
        isVisible: (item) => ["home", "index"].includes(item.slug ?? "")
      }
    }
  };
  function bindFieldToNamespace(field, namespace, isVisible2 = () => true) {
    const subItem = (item) => item?.[namespace] ?? {};
    return {
      ...field,
      getValue: ({ item }) => field.getValue ? field.getValue({ item: subItem(item) }) : subItem(item)[field.id],
      setValue: ({ item, value }) => ({
        [namespace]: field.setValue({ item: subItem(item), value })
      }),
      render: field.render ? (props) => field.render({ ...props, item: subItem(props.item) }) : void 0,
      isVisible: (item) => isVisible2(item) && !!item[namespace]
    };
  }
  function DataFormPostSummary({ onActionPerformed }) {
    const { postType: postType2, postId: postId2, isPostStatusRemoved, availableTemplates } = (0, import_data244.useSelect)((select9) => {
      const {
        getCurrentPostType: getCurrentPostType2,
        getCurrentPostId: getCurrentPostId2,
        isEditorPanelRemoved: isEditorPanelRemoved2,
        getEditorSettings: getEditorSettings2
      } = select9(store);
      const _availableTemplates = select9(
        import_core_data131.store
      ).getCurrentTheme()?.is_block_theme ? null : getEditorSettings2().availableTemplates ?? null;
      return {
        postType: getCurrentPostType2(),
        postId: getCurrentPostId2(),
        isPostStatusRemoved: isEditorPanelRemoved2("post-status"),
        availableTemplates: _availableTemplates
      };
    }, []);
    const { form: formConfig } = useViewConfig({
      kind: "postType",
      name: postType2,
      fields: VIEW_CONFIG_FIELDS
    });
    const form = useInspectorPanelVisibility(formConfig ?? EMPTY_FORM);
    const record = (0, import_data244.useSelect)(
      (select9) => {
        if (!postType2 || !postId2) {
          return null;
        }
        return select9(import_core_data131.store).getEditedEntityRecord(
          "postType",
          postType2,
          postId2
        );
      },
      [postType2, postId2]
    );
    const templatePanelMode = usePostTemplatePanelMode();
    const entityRecords = (0, import_data244.useSelect)(
      (select9) => {
        const { getEditedEntityRecord, canUser } = select9(import_core_data131.store);
        const records = {};
        for (const [namespace, entity] of Object.entries(
          ENTITIES[postType2] ?? {}
        )) {
          if (!canUser("read", {
            kind: entity.kind,
            name: entity.name
          })) {
            continue;
          }
          const id = entity.getId ? entity.getId(select9) : void 0;
          if (entity.getId && !id) {
            continue;
          }
          records[namespace] = getEditedEntityRecord(
            entity.kind,
            entity.name,
            id
          );
        }
        return records;
      },
      [postType2]
    );
    const data = (0, import_element323.useMemo)(() => {
      if (!record) {
        return record;
      }
      const extra = { ...entityRecords };
      if (availableTemplates && Object.keys(availableTemplates).length) {
        extra.available_templates = availableTemplates;
      }
      return { ...record, ...extra };
    }, [record, entityRecords, availableTemplates]);
    const { editEntityRecord } = (0, import_data244.useDispatch)(import_core_data131.store);
    const registry = (0, import_data244.useRegistry)();
    const fieldNamespaces = (0, import_element323.useMemo)(() => {
      const map = {};
      for (const [namespace, entity] of Object.entries(
        ENTITIES[postType2] ?? {}
      )) {
        for (const id of entity.fields ?? []) {
          map[id] = namespace;
        }
      }
      return map;
    }, [postType2]);
    const _fields = post_fields_default({ postType: postType2 });
    const fields2 = (0, import_element323.useMemo)(
      () => _fields?.map((field) => {
        const namespace = fieldNamespaces[field.id];
        if (namespace) {
          return bindFieldToNamespace(
            field,
            namespace,
            ENTITIES[postType2]?.[namespace]?.isVisible
          );
        }
        if (field.id === "status") {
          return {
            ...field,
            elements: field.elements.filter(
              (element) => element.value !== "trash"
            )
          };
        }
        if (field.id === "template") {
          if (!templatePanelMode) {
            return null;
          }
          if (templatePanelMode === "classic" && Object.keys(availableTemplates ?? {}).length === 0) {
            return {
              ...field,
              readOnly: true,
              render: () => (0, import_i18n323.__)("Default template")
            };
          }
          return field;
        }
        return field;
      }).filter(Boolean).concat(revisions_default2),
      [
        _fields,
        templatePanelMode,
        availableTemplates,
        fieldNamespaces,
        postType2
      ]
    );
    const onChange = (edits) => {
      const entities = ENTITIES[postType2] ?? {};
      const baseEdits = {};
      for (const [key, value] of Object.entries(edits)) {
        const entity = entities[key];
        if (entity) {
          const id = entity.getId ? entity.getId(registry.select) : void 0;
          editEntityRecord(entity.kind, entity.name, id, value);
        } else {
          baseEdits[key] = value;
        }
      }
      if (!Object.keys(baseEdits).length) {
        return;
      }
      if (baseEdits.status && baseEdits.status !== "future" && record?.status === "future" && new Date(record.date) > /* @__PURE__ */ new Date()) {
        baseEdits.date = null;
      }
      if (baseEdits.status && baseEdits.status === "private" && record?.password) {
        baseEdits.password = "";
      }
      editEntityRecord("postType", postType2, postId2, baseEdits);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime531.jsx)(post_panel_section_default, { className: "editor-post-summary", children: /* @__PURE__ */ (0, import_jsx_runtime531.jsxs)(Stack, { direction: "column", gap: "lg", children: [
      /* @__PURE__ */ (0, import_jsx_runtime531.jsx)(
        PostCardPanel,
        {
          postType: postType2,
          postId: postId2,
          onActionPerformed
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime531.jsx)(
        DataForm,
        {
          data,
          fields: fields2,
          form,
          onChange
        }
      ),
      !isPostStatusRemoved && /* @__PURE__ */ (0, import_jsx_runtime531.jsxs)(import_jsx_runtime531.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime531.jsx)(plugin_post_status_info_default.Slot, { children: (fills) => fills.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime531.jsx)(Stack, { direction: "column", gap: "xs", children: fills }) }),
        /* @__PURE__ */ (0, import_jsx_runtime531.jsx)(PostTrash, { onActionPerformed })
      ] })
    ] }) });
  }

  // packages/editor/build-module/components/sidebar/post-revision-summary.mjs
  var import_data247 = __toESM(require_data(), 1);
  var import_components270 = __toESM(require_components(), 1);
  var import_i18n326 = __toESM(require_i18n(), 1);
  var import_url25 = __toESM(require_url(), 1);

  // packages/editor/build-module/components/post-revisions-timeline/index.mjs
  var import_data245 = __toESM(require_data(), 1);
  var import_core_data132 = __toESM(require_core_data(), 1);
  var import_date21 = __toESM(require_date(), 1);
  var import_element324 = __toESM(require_element(), 1);
  var import_i18n324 = __toESM(require_i18n(), 1);
  var import_jsx_runtime532 = __toESM(require_jsx_runtime(), 1);
  var PAGE_SIZE2 = 10;
  var EMPTY_ARRAY16 = [];
  var defaultLayouts = { pickerActivity: true };
  var baseView = {
    type: "pickerActivity",
    titleField: "date",
    descriptionField: "details",
    fields: ["author"],
    layout: { density: "compact" },
    page: 1,
    perPage: PAGE_SIZE2
  };
  var DAY_IN_MILLISECONDS2 = 864e5;
  function getDisplayDate(value) {
    const dateNowInMs = (0, import_date21.getDate)(null).getTime();
    const date = (0, import_date21.getDate)(value ?? null);
    return dateNowInMs - date.getTime() > DAY_IN_MILLISECONDS2 ? (0, import_date21.dateI18n)((0, import_date21.getSettings)().formats.datetimeAbbreviated, date) : (0, import_date21.humanTimeDiff)(date);
  }
  function isAutosaveRevision(item) {
    return item.slug?.endsWith("-autosave-v1") ?? false;
  }
  function RevisionBadges({ item }) {
    if (!isAutosaveRevision(item)) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime532.jsx)(Badge, { intent: "none", children: (0, import_i18n324.__)("Autosave") });
  }
  function PostRevisionsTimeline() {
    const { setCurrentRevisionId: setCurrentRevisionId2 } = unlock((0, import_data245.useDispatch)(store));
    const [view, setView] = (0, import_element324.useState)(baseView);
    const { revisions, revisionKey, currentRevisionId } = (0, import_data245.useSelect)(
      (select9) => {
        const { getCurrentPostType: getCurrentPostType2 } = select9(store);
        const {
          getCurrentRevisionId: _getCurrentRevisionId,
          getRevisionPage: getRevisionPage2,
          getPageRevisions: getPageRevisions2
        } = unlock(select9(store));
        const { getEntityConfig } = select9(import_core_data132.store);
        const _postType = getCurrentPostType2();
        const entityConfig = getEntityConfig("postType", _postType);
        const _revisionKey = entityConfig?.revisionKey || "id";
        const _currentRevisionId = _getCurrentRevisionId();
        return {
          // Same desc-ordered window the header slider renders (warm cache).
          revisions: getPageRevisions2(getRevisionPage2()),
          revisionKey: _revisionKey,
          currentRevisionId: _currentRevisionId
        };
      },
      []
    );
    const isLoading = !revisions;
    const fields2 = (0, import_element324.useMemo)(
      () => [
        {
          id: "date",
          label: (0, import_i18n324.__)("Date"),
          // Return the humanized label the row renders so the picker
          // option's accessible name announces e.g. "5 minutes ago"
          // instead of the raw ISO timestamp.
          getValue: ({ item }) => {
            const displayDate = getDisplayDate(item.date);
            if (!isAutosaveRevision(item)) {
              return displayDate;
            }
            return (0, import_i18n324.sprintf)(
              /* translators: 1: revision date, 2: revision type. */
              (0, import_i18n324.__)("%1$s, %2$s"),
              displayDate,
              (0, import_i18n324.__)("Autosave")
            );
          },
          render: ({ item }) => /* @__PURE__ */ (0, import_jsx_runtime532.jsxs)(Stack, { direction: "row", align: "center", gap: "sm", children: [
            /* @__PURE__ */ (0, import_jsx_runtime532.jsx)(
              Text,
              {
                variant: "heading-sm",
                render: /* @__PURE__ */ (0, import_jsx_runtime532.jsx)("time", { dateTime: item.date }),
                children: getDisplayDate(item.date)
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime532.jsx)(RevisionBadges, { item })
          ] }),
          enableSorting: false,
          enableHiding: false
        },
        author_default,
        {
          id: "details",
          label: (0, import_i18n324.__)("Details"),
          render: ({ item }) => {
            if (String(item[revisionKey]) !== String(currentRevisionId)) {
              return null;
            }
            return /* @__PURE__ */ (0, import_jsx_runtime532.jsx)(
              PostContentInformationUI,
              {
                postContent: item.content?.raw
              }
            );
          },
          enableSorting: false,
          enableHiding: false
        }
      ],
      [revisionKey, currentRevisionId]
    );
    const { data: shownRevisions, paginationInfo } = (0, import_element324.useMemo)(
      () => filterSortAndPaginate(revisions || EMPTY_ARRAY16, view, fields2),
      [revisions, view, fields2]
    );
    (0, import_element324.useEffect)(() => {
      if (!currentRevisionId || !revisions) {
        return;
      }
      const index2 = revisions.findIndex(
        (r4) => String(r4[revisionKey]) === String(currentRevisionId)
      );
      if (index2 < 0) {
        return;
      }
      const page = Math.floor(index2 / view.perPage) + 1;
      setView((v3) => v3.page === page ? v3 : { ...v3, page });
    }, [currentRevisionId, revisions, revisionKey, view.perPage]);
    const selection = (0, import_element324.useMemo)(
      () => currentRevisionId ? [String(currentRevisionId)] : EMPTY_ARRAY16,
      [currentRevisionId]
    );
    const onChangeSelection = (0, import_element324.useCallback)(
      (newSelection) => {
        if (newSelection.length === 0) {
          return;
        }
        const selectedId = newSelection[newSelection.length - 1];
        setCurrentRevisionId2(Number(selectedId));
      },
      [setCurrentRevisionId2]
    );
    const getItemId2 = (0, import_element324.useCallback)(
      (item) => String(item[revisionKey]),
      [revisionKey]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime532.jsx)("div", { className: "editor-post-revisions-timeline", children: /* @__PURE__ */ (0, import_jsx_runtime532.jsxs)(
      dataviews_picker_default,
      {
        view,
        onChangeView: setView,
        fields: fields2,
        data: shownRevisions,
        isLoading,
        paginationInfo,
        defaultLayouts,
        getItemId: getItemId2,
        selection,
        onChangeSelection,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime532.jsx)(dataviews_picker_default.Layout, {}),
          /* @__PURE__ */ (0, import_jsx_runtime532.jsx)(dataviews_picker_default.Footer, {})
        ]
      }
    ) });
  }

  // packages/editor/build-module/components/revision-fields-diff/index.mjs
  var import_data246 = __toESM(require_data(), 1);
  var import_element325 = __toESM(require_element(), 1);
  var import_i18n325 = __toESM(require_i18n(), 1);

  // packages/editor/build-module/components/revision-diff-panel/index.mjs
  var import_components269 = __toESM(require_components(), 1);
  var import_jsx_runtime533 = __toESM(require_jsx_runtime(), 1);
  function RevisionDiffPanel({
    title,
    entries,
    initialOpen,
    className
  }) {
    if (!entries) {
      return null;
    }
    const fields2 = Object.entries(entries).map(([key, parts]) => /* @__PURE__ */ (0, import_jsx_runtime533.jsx)(post_panel_row_default, { label: key, children: /* @__PURE__ */ (0, import_jsx_runtime533.jsx)("span", { className: "editor-revision-fields-diff__value", children: parts.map((part, index2) => {
      if (part.added) {
        return /* @__PURE__ */ (0, import_jsx_runtime533.jsx)(
          "ins",
          {
            className: "editor-revision-fields-diff__added",
            children: part.value
          },
          index2
        );
      }
      if (part.removed) {
        return /* @__PURE__ */ (0, import_jsx_runtime533.jsx)(
          "del",
          {
            className: "editor-revision-fields-diff__removed",
            children: part.value
          },
          index2
        );
      }
      return /* @__PURE__ */ (0, import_jsx_runtime533.jsx)("span", { children: part.value }, index2);
    }) }) }, key));
    return /* @__PURE__ */ (0, import_jsx_runtime533.jsx)(import_components269.PanelBody, { title, initialOpen, children: /* @__PURE__ */ (0, import_jsx_runtime533.jsx)("div", { className, children: fields2 }) });
  }

  // packages/editor/build-module/components/revision-fields-diff/index.mjs
  var import_jsx_runtime534 = __toESM(require_jsx_runtime(), 1);
  function stringifyValue2(value) {
    if (value === null || value === void 0) {
      return "";
    }
    if (typeof value === "object") {
      return JSON.stringify(value, null, 2);
    }
    return String(value);
  }
  function isEmptyMeta(str3) {
    return !str3 || str3 === "[]" || str3 === "{}";
  }
  function RevisionFieldsDiffPanel() {
    const { revision, previousRevision } = (0, import_data246.useSelect)((select9) => {
      const { getCurrentRevision: getCurrentRevision2, getPreviousRevision: getPreviousRevision2 } = unlock(
        select9(store)
      );
      return {
        revision: getCurrentRevision2(),
        previousRevision: getPreviousRevision2()
      };
    }, []);
    const entries = (0, import_element325.useMemo)(() => {
      if (!revision) {
        return null;
      }
      const revisionMeta = revision.meta ?? {};
      const previousMeta = previousRevision?.meta ?? {};
      const allMetaKeys = /* @__PURE__ */ new Set([
        ...Object.keys(revisionMeta),
        ...Object.keys(previousMeta)
      ]);
      const result = {};
      for (const key of allMetaKeys) {
        const revStr = stringifyValue2(revisionMeta[key]);
        const prevStr = stringifyValue2(previousMeta[key]);
        if (isEmptyMeta(revStr) && isEmptyMeta(prevStr)) {
          continue;
        }
        result[key] = diffWordsWithSpace(prevStr, revStr);
      }
      if (Object.keys(result).length === 0) {
        return null;
      }
      return result;
    }, [revision, previousRevision]);
    return /* @__PURE__ */ (0, import_jsx_runtime534.jsx)(
      RevisionDiffPanel,
      {
        title: (0, import_i18n325.__)("Meta"),
        entries,
        initialOpen: false,
        className: "editor-revision-meta-diff__content"
      }
    );
  }

  // packages/editor/build-module/components/sidebar/post-revision-summary.mjs
  var import_jsx_runtime535 = __toESM(require_jsx_runtime(), 1);
  function PostRevisionSummary() {
    const { revisionId: revisionId2, postId: postId2 } = (0, import_data247.useSelect)((select9) => {
      const { getCurrentRevisionId: getCurrentRevisionId2, getCurrentPostId: getCurrentPostId2 } = unlock(
        select9(store)
      );
      return {
        revisionId: getCurrentRevisionId2(),
        postId: getCurrentPostId2()
      };
    }, []);
    if (!revisionId2) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime535.jsxs)(import_jsx_runtime535.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime535.jsx)(post_panel_section_default, { className: "editor-post-summary", children: /* @__PURE__ */ (0, import_jsx_runtime535.jsxs)(import_components270.__experimentalVStack, { spacing: 4, children: [
        /* @__PURE__ */ (0, import_jsx_runtime535.jsx)(PostCardPanel, { postId: postId2, hideActions: true }),
        /* @__PURE__ */ (0, import_jsx_runtime535.jsx)(
          import_components270.ExternalLink,
          {
            href: (0, import_url25.addQueryArgs)("revision.php", {
              revision: revisionId2
            }),
            children: (0, import_i18n326.__)("Open classic revisions screen")
          }
        )
      ] }) }),
      /* @__PURE__ */ (0, import_jsx_runtime535.jsx)(RevisionFieldsDiffPanel, {}),
      /* @__PURE__ */ (0, import_jsx_runtime535.jsx)(PostRevisionsTimeline, {})
    ] });
  }

  // packages/editor/build-module/components/post-transform-panel/index.mjs
  var import_data249 = __toESM(require_data(), 1);
  var import_core_data134 = __toESM(require_core_data(), 1);
  var import_components271 = __toESM(require_components(), 1);
  var import_i18n327 = __toESM(require_i18n(), 1);
  var import_block_editor90 = __toESM(require_block_editor(), 1);
  var import_blocks36 = __toESM(require_blocks(), 1);

  // packages/editor/build-module/components/post-transform-panel/hooks.mjs
  var import_data248 = __toESM(require_data(), 1);
  var import_element326 = __toESM(require_element(), 1);
  var import_core_data133 = __toESM(require_core_data(), 1);
  var import_blocks35 = __toESM(require_blocks(), 1);
  var import_patterns11 = __toESM(require_patterns(), 1);
  var { EXCLUDED_PATTERN_SOURCES, PATTERN_TYPES: PATTERN_TYPES6 } = unlock(import_patterns11.privateApis);
  function injectThemeAttributeInBlockTemplateContent(block, currentThemeStylesheet) {
    block.innerBlocks = block.innerBlocks.map((innerBlock) => {
      return injectThemeAttributeInBlockTemplateContent(
        innerBlock,
        currentThemeStylesheet
      );
    });
    if (block.name === "core/template-part" && block.attributes.theme === void 0) {
      block.attributes.theme = currentThemeStylesheet;
    }
    return block;
  }
  function filterPatterns(patterns2, template2) {
    const filterOutDuplicatesByName = (currentItem, index2, items) => index2 === items.findIndex((item) => currentItem.name === item.name);
    const filterOutExcludedPatternSources = (pattern) => {
      if (template2.area === "navigation-overlay" && pattern.blockTypes?.includes(
        "core/template-part/navigation-overlay"
      )) {
        return true;
      }
      return !EXCLUDED_PATTERN_SOURCES.includes(pattern.source);
    };
    const filterCompatiblePatterns = (pattern) => pattern.templateTypes?.includes(template2.slug) || pattern.blockTypes?.includes("core/template-part/" + template2.area);
    return patterns2.filter((pattern, index2, items) => {
      return filterOutDuplicatesByName(pattern, index2, items) && filterOutExcludedPatternSources(pattern) && filterCompatiblePatterns(pattern);
    });
  }
  function preparePatterns(patterns2, currentThemeStylesheet) {
    return patterns2.map((pattern) => ({
      ...pattern,
      keywords: pattern.keywords || [],
      type: PATTERN_TYPES6.theme,
      blocks: (0, import_blocks35.parse)(pattern.content, {
        __unstableSkipMigrationLogs: true
      }).map(
        (block) => injectThemeAttributeInBlockTemplateContent(
          block,
          currentThemeStylesheet
        )
      )
    }));
  }
  function useAvailablePatterns({ area, name: name2, slug }) {
    const { blockPatterns, restBlockPatterns, currentThemeStylesheet } = (0, import_data248.useSelect)((select9) => {
      const { getEditorSettings: getEditorSettings2 } = select9(store);
      const settings = getEditorSettings2();
      return {
        blockPatterns: settings.__experimentalAdditionalBlockPatterns ?? settings.__experimentalBlockPatterns,
        restBlockPatterns: select9(import_core_data133.store).getBlockPatterns(),
        currentThemeStylesheet: select9(import_core_data133.store).getCurrentTheme().stylesheet
      };
    }, []);
    return (0, import_element326.useMemo)(() => {
      const mergedPatterns = [
        ...blockPatterns || [],
        ...restBlockPatterns || []
      ];
      const filteredPatterns = filterPatterns(mergedPatterns, {
        area,
        name: name2,
        slug
      });
      return preparePatterns(filteredPatterns, currentThemeStylesheet);
    }, [
      area,
      name2,
      slug,
      blockPatterns,
      restBlockPatterns,
      currentThemeStylesheet
    ]);
  }

  // packages/editor/build-module/components/post-transform-panel/index.mjs
  var import_jsx_runtime536 = __toESM(require_jsx_runtime(), 1);
  function TemplatesList2({ availableTemplates, onSelect }) {
    if (!availableTemplates || availableTemplates?.length === 0) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime536.jsx)(
      import_block_editor90.__experimentalBlockPatternsList,
      {
        label: (0, import_i18n327.__)("Templates"),
        blockPatterns: availableTemplates,
        onClickPattern: onSelect,
        showTitlesAsTooltip: true
      }
    );
  }
  function PostTransform() {
    const { area, name: name2, slug, postType: postType2, postId: postId2 } = (0, import_data249.useSelect)((select9) => {
      const { getCurrentPostType: getCurrentPostType2, getCurrentPostId: getCurrentPostId2 } = select9(store);
      const { getEditedEntityRecord } = select9(import_core_data134.store);
      const type = getCurrentPostType2();
      const id = getCurrentPostId2();
      const record = getEditedEntityRecord("postType", type, id);
      return {
        area: record?.area,
        name: record?.name,
        slug: record?.slug,
        postType: type,
        postId: id
      };
    }, []);
    const { editEntityRecord } = (0, import_data249.useDispatch)(import_core_data134.store);
    const availablePatterns = useAvailablePatterns({ area, name: name2, slug });
    const onTemplateSelect = async (selectedTemplate) => {
      await editEntityRecord("postType", postType2, postId2, {
        blocks: selectedTemplate.blocks,
        content: (0, import_blocks36.serialize)(selectedTemplate.blocks)
      });
    };
    if (!availablePatterns?.length) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime536.jsx)(
      import_components271.PanelBody,
      {
        title: (0, import_i18n327.__)("Design"),
        initialOpen: postType2 === TEMPLATE_PART_POST_TYPE,
        children: /* @__PURE__ */ (0, import_jsx_runtime536.jsx)(
          TemplatesList2,
          {
            availableTemplates: availablePatterns,
            onSelect: onTemplateSelect
          }
        )
      }
    );
  }
  function PostTransformPanel() {
    const { postType: postType2 } = (0, import_data249.useSelect)((select9) => {
      const { getCurrentPostType: getCurrentPostType2 } = select9(store);
      return {
        postType: getCurrentPostType2()
      };
    }, []);
    if (![TEMPLATE_PART_POST_TYPE, TEMPLATE_POST_TYPE].includes(postType2)) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime536.jsx)(PostTransform, {});
  }

  // packages/editor/build-module/components/sidebar/header.mjs
  var import_components272 = __toESM(require_components(), 1);
  var import_i18n328 = __toESM(require_i18n(), 1);
  var import_data250 = __toESM(require_data(), 1);
  var import_element327 = __toESM(require_element(), 1);
  var import_html_entities34 = __toESM(require_html_entities(), 1);
  var import_jsx_runtime537 = __toESM(require_jsx_runtime(), 1);
  var { Tabs: Tabs2 } = unlock(import_components272.privateApis);
  var SidebarHeader = (_, ref) => {
    const { postTypeLabel, isRevisionsMode: isRevisionsMode2 } = (0, import_data250.useSelect)((select9) => {
      const { getPostTypeLabel: getPostTypeLabel2 } = select9(store);
      const { isRevisionsMode: _isRevisionsMode } = unlock(
        select9(store)
      );
      return {
        postTypeLabel: getPostTypeLabel2(),
        isRevisionsMode: _isRevisionsMode()
      };
    }, []);
    let documentLabel;
    if (isRevisionsMode2) {
      documentLabel = (0, import_i18n328.__)("Revision");
    } else if (postTypeLabel) {
      documentLabel = (0, import_html_entities34.decodeEntities)(postTypeLabel);
    } else {
      documentLabel = (0, import_i18n328._x)("Document", "noun, panel");
    }
    return /* @__PURE__ */ (0, import_jsx_runtime537.jsxs)(Tabs2.TabList, { ref, children: [
      /* @__PURE__ */ (0, import_jsx_runtime537.jsx)(
        Tabs2.Tab,
        {
          tabId: sidebars.document,
          "data-tab-id": sidebars.document,
          children: documentLabel
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime537.jsx)(
        Tabs2.Tab,
        {
          tabId: sidebars.block,
          "data-tab-id": sidebars.block,
          children: (0, import_i18n328.__)("Block")
        }
      )
    ] });
  };
  var header_default3 = (0, import_element327.forwardRef)(SidebarHeader);

  // packages/editor/build-module/components/template-actions-panel/block-theme-content.mjs
  var import_data251 = __toESM(require_data(), 1);
  var import_core_data135 = __toESM(require_core_data(), 1);
  var import_block_editor91 = __toESM(require_block_editor(), 1);
  var import_components273 = __toESM(require_components(), 1);
  var import_element328 = __toESM(require_element(), 1);
  var import_i18n329 = __toESM(require_i18n(), 1);
  var import_html_entities35 = __toESM(require_html_entities(), 1);
  var import_keycodes20 = __toESM(require_keycodes(), 1);
  var import_notices35 = __toESM(require_notices(), 1);
  var import_preferences27 = __toESM(require_preferences(), 1);
  var import_jsx_runtime538 = __toESM(require_jsx_runtime(), 1);
  function TemplateActionsPanelContent() {
    const templateId2 = (0, import_data251.useSelect)(
      (select9) => select9(store).getCurrentTemplateId(),
      []
    );
    const [isCreateModalOpen, setIsCreateModalOpen] = (0, import_element328.useState)(false);
    const [isSwapModalOpen, setIsSwapModalOpen] = (0, import_element328.useState)(false);
    const availableTemplates = useAvailableTemplates();
    const hasSwapTargets = !!availableTemplates?.length;
    const {
      onNavigateToEntityRecord,
      canCreateTemplate,
      hasGoBack,
      getEditorSettings: getEditorSettings2
    } = (0, import_data251.useSelect)((select9) => {
      const { getEditorSettings: _getEditorSettings } = select9(store);
      const editorSettings2 = _getEditorSettings();
      return {
        onNavigateToEntityRecord: editorSettings2.onNavigateToEntityRecord,
        canCreateTemplate: !!select9(import_core_data135.store).canUser("create", {
          kind: "postType",
          name: "wp_template"
        }),
        hasGoBack: editorSettings2.hasOwnProperty(
          "onNavigateToPreviousEntityRecord"
        ),
        getEditorSettings: _getEditorSettings
      };
    }, []);
    const { get: getPreference } = (0, import_data251.useSelect)(import_preferences27.store);
    const { createSuccessNotice } = (0, import_data251.useDispatch)(import_notices35.store);
    const { editedRecord: template2, hasResolved } = (0, import_core_data135.useEntityRecord)(
      "postType",
      "wp_template",
      templateId2
    );
    const [blocks] = (0, import_core_data135.useEntityBlockEditor)("postType", "wp_template", {
      id: templateId2
    });
    if (!hasResolved) {
      return null;
    }
    const notificationAction = hasGoBack ? [
      {
        label: (0, import_i18n329.__)("Go back"),
        onClick: () => getEditorSettings2().onNavigateToPreviousEntityRecord()
      }
    ] : void 0;
    const mayShowTemplateEditNotice = () => {
      if (!getPreference("core/edit-site", "welcomeGuideTemplate")) {
        createSuccessNotice(
          (0, import_i18n329.__)(
            "Editing template. Changes made here affect all posts and pages that use the template."
          ),
          { type: "snackbar", actions: notificationAction }
        );
      }
    };
    const templateName = (0, import_html_entities35.decodeEntities)(template2.title);
    const previewContent = !!blocks?.length && /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(import_block_editor91.BlockPreview.Async, { children: /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(import_block_editor91.BlockPreview, { blocks }) });
    const renderPreview = () => {
      if (!previewContent) {
        return null;
      }
      if (hasSwapTargets) {
        const tooltipText = (0, import_i18n329.__)("Change template");
        return /* @__PURE__ */ (0, import_jsx_runtime538.jsxs)(tooltip_exports.Root, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(
            tooltip_exports.Trigger,
            {
              render: /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(
                "div",
                {
                  className: "editor-template-actions-panel__preview",
                  role: "button",
                  tabIndex: 0,
                  "aria-label": tooltipText,
                  onClick: () => setIsSwapModalOpen(true),
                  onKeyDown: (event) => {
                    if (event.keyCode === import_keycodes20.ENTER || event.keyCode === import_keycodes20.SPACE) {
                      event.preventDefault();
                      setIsSwapModalOpen(true);
                    }
                  },
                  children: previewContent
                }
              )
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(tooltip_exports.Popup, { children: tooltipText })
        ] });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime538.jsx)("div", { className: "editor-template-actions-panel__preview", children: previewContent });
    };
    return /* @__PURE__ */ (0, import_jsx_runtime538.jsxs)(import_jsx_runtime538.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(
        import_components273.PanelBody,
        {
          title: (0, import_i18n329.sprintf)(
            /* translators: %s: template name */
            (0, import_i18n329.__)("Template: %s"),
            templateName
          ),
          initialOpen: false,
          children: /* @__PURE__ */ (0, import_jsx_runtime538.jsxs)(import_components273.__experimentalVStack, { children: [
            renderPreview(),
            /* @__PURE__ */ (0, import_jsx_runtime538.jsxs)(import_components273.__experimentalHStack, { children: [
              onNavigateToEntityRecord && /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(
                import_components273.Button,
                {
                  className: "editor-template-actions-panel__action",
                  __next40pxDefaultSize: true,
                  variant: "secondary",
                  onClick: () => {
                    onNavigateToEntityRecord({
                      postId: template2.id,
                      postType: "wp_template"
                    });
                    mayShowTemplateEditNotice();
                  },
                  children: (0, import_i18n329.__)("Edit")
                }
              ),
              canCreateTemplate && /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(
                import_components273.Button,
                {
                  className: "editor-template-actions-panel__action",
                  __next40pxDefaultSize: true,
                  variant: "secondary",
                  onClick: () => setIsCreateModalOpen(true),
                  children: (0, import_i18n329.__)("Create new")
                }
              )
            ] })
          ] })
        }
      ),
      isCreateModalOpen && /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(
        CreateNewTemplateModal,
        {
          onClose: () => setIsCreateModalOpen(false)
        }
      ),
      isSwapModalOpen && /* @__PURE__ */ (0, import_jsx_runtime538.jsx)(
        SwapTemplateModal,
        {
          onRequestClose: () => setIsSwapModalOpen(false)
        }
      )
    ] });
  }

  // packages/editor/build-module/components/template-actions-panel/classic-theme-content.mjs
  var import_data252 = __toESM(require_data(), 1);
  var import_core_data136 = __toESM(require_core_data(), 1);
  var import_block_editor92 = __toESM(require_block_editor(), 1);
  var import_components274 = __toESM(require_components(), 1);
  var import_element329 = __toESM(require_element(), 1);
  var import_i18n330 = __toESM(require_i18n(), 1);
  var import_html_entities36 = __toESM(require_html_entities(), 1);
  var import_notices36 = __toESM(require_notices(), 1);
  var import_preferences28 = __toESM(require_preferences(), 1);
  var import_jsx_runtime539 = __toESM(require_jsx_runtime(), 1);
  function ClassicThemeContent() {
    const templateId2 = (0, import_data252.useSelect)(
      (select9) => select9(store).getCurrentTemplateId(),
      []
    );
    const [isCreateModalOpen, setIsCreateModalOpen] = (0, import_element329.useState)(false);
    const {
      onNavigateToEntityRecord,
      canCreateTemplate,
      hasGoBack,
      getEditorSettings: getEditorSettings2
    } = (0, import_data252.useSelect)((select9) => {
      const { getEditorSettings: _getEditorSettings } = select9(store);
      const editorSettings2 = _getEditorSettings();
      return {
        onNavigateToEntityRecord: editorSettings2.onNavigateToEntityRecord,
        canCreateTemplate: !!select9(import_core_data136.store).canUser("create", {
          kind: "postType",
          name: "wp_template"
        }) && editorSettings2.supportsTemplateMode,
        hasGoBack: editorSettings2.hasOwnProperty(
          "onNavigateToPreviousEntityRecord"
        ),
        getEditorSettings: _getEditorSettings
      };
    }, []);
    const { get: getPreference } = (0, import_data252.useSelect)(import_preferences28.store);
    const { createSuccessNotice } = (0, import_data252.useDispatch)(import_notices36.store);
    const { editedRecord: template2 } = (0, import_core_data136.useEntityRecord)(
      "postType",
      "wp_template",
      templateId2
    );
    const [blocks] = (0, import_core_data136.useEntityBlockEditor)("postType", "wp_template", {
      id: templateId2
    });
    if (!templateId2 && !canCreateTemplate) {
      return null;
    }
    const notificationAction = hasGoBack ? [
      {
        label: (0, import_i18n330.__)("Go back"),
        onClick: () => getEditorSettings2().onNavigateToPreviousEntityRecord()
      }
    ] : void 0;
    const mayShowTemplateEditNotice = () => {
      if (!getPreference("core/edit-site", "welcomeGuideTemplate")) {
        createSuccessNotice(
          (0, import_i18n330.__)(
            "Editing template. Changes made here affect all posts and pages that use the template."
          ),
          { type: "snackbar", actions: notificationAction }
        );
      }
    };
    const templateName = template2 ? (0, import_html_entities36.decodeEntities)(template2.title) : void 0;
    const previewContent = !!blocks?.length && /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(import_block_editor92.BlockPreview.Async, { children: /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(import_block_editor92.BlockPreview, { blocks }) });
    return /* @__PURE__ */ (0, import_jsx_runtime539.jsxs)(import_jsx_runtime539.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(
        import_components274.PanelBody,
        {
          title: template2 ? (0, import_i18n330.sprintf)(
            /* translators: %s: template name */
            (0, import_i18n330.__)("Template: %s"),
            templateName
          ) : (0, import_i18n330.__)("Template"),
          initialOpen: false,
          children: /* @__PURE__ */ (0, import_jsx_runtime539.jsxs)(import_components274.__experimentalVStack, { children: [
            !templateId2 && /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(import_components274.__experimentalText, { children: (0, import_i18n330.__)(
              "This page uses a classic template. To edit this template with blocks, create a block template."
            ) }),
            template2 && previewContent && /* @__PURE__ */ (0, import_jsx_runtime539.jsx)("div", { className: "editor-template-actions-panel__preview", children: previewContent }),
            /* @__PURE__ */ (0, import_jsx_runtime539.jsxs)(import_components274.__experimentalHStack, { children: [
              template2 && onNavigateToEntityRecord && /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(
                import_components274.Button,
                {
                  className: "editor-template-actions-panel__action",
                  __next40pxDefaultSize: true,
                  variant: "secondary",
                  onClick: () => {
                    onNavigateToEntityRecord({
                      postId: template2.id,
                      postType: "wp_template"
                    });
                    mayShowTemplateEditNotice();
                  },
                  children: (0, import_i18n330.__)("Edit")
                }
              ),
              canCreateTemplate && /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(
                import_components274.Button,
                {
                  className: "editor-template-actions-panel__action",
                  __next40pxDefaultSize: true,
                  variant: "secondary",
                  onClick: () => setIsCreateModalOpen(true),
                  children: !templateId2 ? (0, import_i18n330.__)("Create block template") : (0, import_i18n330.__)("Create new")
                }
              )
            ] })
          ] })
        }
      ),
      isCreateModalOpen && /* @__PURE__ */ (0, import_jsx_runtime539.jsx)(
        CreateNewTemplateModal,
        {
          onClose: () => setIsCreateModalOpen(false)
        }
      )
    ] });
  }

  // packages/editor/build-module/components/template-actions-panel/index.mjs
  var import_jsx_runtime540 = __toESM(require_jsx_runtime(), 1);
  function TemplateActionsPanel() {
    const mode = usePostTemplatePanelMode();
    if (mode === "classic") {
      return /* @__PURE__ */ (0, import_jsx_runtime540.jsx)(ClassicThemeContent, {});
    }
    if (mode === "block-theme") {
      return /* @__PURE__ */ (0, import_jsx_runtime540.jsx)(TemplateActionsPanelContent, {});
    }
    return null;
  }

  // packages/editor/build-module/components/template-content-panel/index.mjs
  var import_data253 = __toESM(require_data(), 1);
  var import_block_editor93 = __toESM(require_block_editor(), 1);
  var import_components275 = __toESM(require_components(), 1);
  var import_i18n331 = __toESM(require_i18n(), 1);
  var import_jsx_runtime541 = __toESM(require_jsx_runtime(), 1);
  var { BlockQuickNavigation } = unlock(import_block_editor93.privateApis);
  var TEMPLATE_PART_BLOCK = "core/template-part";
  function TemplateContentPanelInner({ postType: postType2 }) {
    const postContentBlockTypes = usePostContentBlockTypes();
    const clientIds = (0, import_data253.useSelect)(
      (select9) => {
        const { getPostBlocksByName: getPostBlocksByName2 } = unlock(select9(store));
        return getPostBlocksByName2(
          TEMPLATE_POST_TYPE === postType2 ? TEMPLATE_PART_BLOCK : postContentBlockTypes
        );
      },
      [postType2, postContentBlockTypes]
    );
    const { enableComplementaryArea: enableComplementaryArea2 } = (0, import_data253.useDispatch)(store3);
    if (clientIds.length === 0) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime541.jsx)(import_components275.PanelBody, { title: (0, import_i18n331.__)("Content"), children: /* @__PURE__ */ (0, import_jsx_runtime541.jsx)(
      BlockQuickNavigation,
      {
        clientIds,
        onSelect: () => {
          enableComplementaryArea2("core", "edit-post/document");
        }
      }
    ) });
  }
  function TemplateContentPanel() {
    const { postType: postType2, renderingMode: renderingMode2 } = (0, import_data253.useSelect)((select9) => {
      const { getCurrentPostType: getCurrentPostType2, getRenderingMode: getRenderingMode2 } = unlock(
        select9(store)
      );
      return {
        postType: getCurrentPostType2(),
        renderingMode: getRenderingMode2()
      };
    }, []);
    if (renderingMode2 === "post-only" && postType2 !== TEMPLATE_POST_TYPE) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime541.jsx)(TemplateContentPanelInner, { postType: postType2 });
  }

  // packages/editor/build-module/components/template-part-content-panel/index.mjs
  var import_data254 = __toESM(require_data(), 1);
  var import_element330 = __toESM(require_element(), 1);
  var import_blocks37 = __toESM(require_blocks(), 1);
  var import_block_editor94 = __toESM(require_block_editor(), 1);
  var import_components276 = __toESM(require_components(), 1);
  var import_i18n332 = __toESM(require_i18n(), 1);
  var import_jsx_runtime542 = __toESM(require_jsx_runtime(), 1);
  var { BlockQuickNavigation: BlockQuickNavigation2 } = unlock(import_block_editor94.privateApis);
  function TemplatePartContentPanelInner() {
    const blockTypes = (0, import_data254.useSelect)((select9) => {
      const { getBlockTypes: getBlockTypes6 } = select9(import_blocks37.store);
      return getBlockTypes6();
    }, []);
    const themeBlockNames = (0, import_element330.useMemo)(() => {
      return blockTypes.filter((blockType) => {
        return blockType.category === "theme";
      }).map(({ name: name2 }) => name2);
    }, [blockTypes]);
    const themeBlocks = (0, import_data254.useSelect)(
      (select9) => {
        const { getBlocksByName } = select9(import_block_editor94.store);
        return getBlocksByName(themeBlockNames);
      },
      [themeBlockNames]
    );
    if (themeBlocks.length === 0) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime542.jsx)(import_components276.PanelBody, { title: (0, import_i18n332.__)("Content"), children: /* @__PURE__ */ (0, import_jsx_runtime542.jsx)(BlockQuickNavigation2, { clientIds: themeBlocks }) });
  }
  function TemplatePartContentPanel() {
    const postType2 = (0, import_data254.useSelect)((select9) => {
      const { getCurrentPostType: getCurrentPostType2 } = select9(store);
      return getCurrentPostType2();
    }, []);
    if (postType2 !== TEMPLATE_PART_POST_TYPE) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime542.jsx)(TemplatePartContentPanelInner, {});
  }

  // packages/editor/build-module/components/revision-block-diff/index.mjs
  var import_block_editor95 = __toESM(require_block_editor(), 1);
  var import_data255 = __toESM(require_data(), 1);
  var import_i18n333 = __toESM(require_i18n(), 1);
  var import_jsx_runtime543 = __toESM(require_jsx_runtime(), 1);
  function RevisionBlockDiffPanel() {
    const { block } = (0, import_data255.useSelect)((select9) => {
      const { getSelectedBlock: getSelectedBlock2 } = select9(import_block_editor95.store);
      return {
        block: getSelectedBlock2()
      };
    }, []);
    if (!block) {
      return null;
    }
    const changedAttributes = block.attributes?.__revisionDiffStatus?.changedAttributes;
    return /* @__PURE__ */ (0, import_jsx_runtime543.jsx)(
      RevisionDiffPanel,
      {
        title: (0, import_i18n333.__)("Changed attributes"),
        entries: changedAttributes,
        initialOpen: true
      }
    );
  }

  // packages/editor/build-module/components/provider/use-auto-switch-editor-sidebars.mjs
  var import_data256 = __toESM(require_data(), 1);
  var import_element331 = __toESM(require_element(), 1);
  var import_block_editor96 = __toESM(require_block_editor(), 1);
  var import_preferences29 = __toESM(require_preferences(), 1);
  function useAutoSwitchEditorSidebars() {
    const { hasBlockSelection } = (0, import_data256.useSelect)((select9) => {
      return {
        hasBlockSelection: !!select9(import_block_editor96.store).getBlockSelectionStart()
      };
    }, []);
    const { getActiveComplementaryArea: getActiveComplementaryArea2 } = (0, import_data256.useSelect)(store3);
    const { enableComplementaryArea: enableComplementaryArea2 } = (0, import_data256.useDispatch)(store3);
    const { get: getPreference } = (0, import_data256.useSelect)(import_preferences29.store);
    (0, import_element331.useEffect)(() => {
      const activeGeneralSidebar = getActiveComplementaryArea2("core");
      const isEditorSidebarOpened = [
        "edit-post/document",
        "edit-post/block"
      ].includes(activeGeneralSidebar);
      const isDistractionFree = getPreference("core", "distractionFree");
      if (!isEditorSidebarOpened || isDistractionFree) {
        return;
      }
      if (hasBlockSelection) {
        enableComplementaryArea2("core", "edit-post/block");
      } else {
        enableComplementaryArea2("core", "edit-post/document");
      }
    }, [
      hasBlockSelection,
      getActiveComplementaryArea2,
      enableComplementaryArea2,
      getPreference
    ]);
  }
  var use_auto_switch_editor_sidebars_default = useAutoSwitchEditorSidebars;

  // packages/editor/build-module/components/sidebar/index.mjs
  var import_jsx_runtime544 = __toESM(require_jsx_runtime(), 1);
  var { Tabs: Tabs3 } = unlock(import_components277.privateApis);
  var SIDEBAR_ACTIVE_BY_DEFAULT = true;
  var SidebarContent = ({
    tabName,
    keyboardShortcut,
    onActionPerformed,
    extraPanels
  }) => {
    const tabListRef = (0, import_element332.useRef)(null);
    const tabsContextValue = (0, import_element332.useContext)(Tabs3.Context);
    const isRevisionsMode2 = (0, import_data257.useSelect)((select9) => {
      return unlock(select9(store)).isRevisionsMode();
    });
    (0, import_element332.useEffect)(() => {
      const tabsElements = Array.from(
        tabListRef.current?.querySelectorAll('[role="tab"]') || []
      );
      const selectedTabElement = tabsElements.find(
        // We are purposefully using a custom `data-tab-id` attribute here
        // because we don't want rely on any assumptions about `Tabs`
        // component internals.
        (element) => element.getAttribute("data-tab-id") === tabName
      );
      const activeElement2 = selectedTabElement?.ownerDocument.activeElement;
      const tabsHasFocus = tabsElements.some((element) => {
        return activeElement2 && activeElement2.id === element.id;
      });
      if (tabsHasFocus && selectedTabElement && selectedTabElement.id !== activeElement2?.id) {
        selectedTabElement?.focus();
      }
    }, [tabName]);
    let tabContent;
    if (isRevisionsMode2) {
      tabContent = /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(PostRevisionSummary, {});
    } else {
      const isDataFormInspectorEnabled = window?.__experimentalDataFormInspector;
      tabContent = /* @__PURE__ */ (0, import_jsx_runtime544.jsxs)(import_jsx_runtime544.Fragment, { children: [
        isDataFormInspectorEnabled ? /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(
          DataFormPostSummary,
          {
            onActionPerformed
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(PostSummary, { onActionPerformed }),
        /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(plugin_document_setting_panel_default.Slot, {}),
        /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(TemplateContentPanel, {}),
        isDataFormInspectorEnabled && /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(TemplateActionsPanel, {}),
        /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(TemplatePartContentPanel, {}),
        /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(PostTransformPanel, {}),
        /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(PostTaxonomies2, {}),
        /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(PatternOverridesPanel, {}),
        extraPanels
      ] });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(
      PluginSidebar,
      {
        identifier: tabName,
        header: /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(Tabs3.Context.Provider, { value: tabsContextValue, children: /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(header_default3, { ref: tabListRef }) }),
        closeLabel: (0, import_i18n334.__)("Close Settings"),
        className: "editor-sidebar__panel",
        headerClassName: "editor-sidebar__panel-tabs",
        title: (
          /* translators: button label text should, if possible, be under 16 characters. */
          (0, import_i18n334._x)("Settings", "panel button label")
        ),
        toggleShortcut: keyboardShortcut,
        icon: (0, import_i18n334.isRTL)() ? drawer_left_default : drawer_right_default,
        isActiveByDefault: SIDEBAR_ACTIVE_BY_DEFAULT,
        children: /* @__PURE__ */ (0, import_jsx_runtime544.jsxs)(Tabs3.Context.Provider, { value: tabsContextValue, children: [
          /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(Tabs3.TabPanel, { tabId: sidebars.document, focusable: false, children: tabContent }),
          /* @__PURE__ */ (0, import_jsx_runtime544.jsxs)(Tabs3.TabPanel, { tabId: sidebars.block, focusable: false, children: [
            /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(import_block_editor97.BlockInspector, {}),
            isRevisionsMode2 && /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(RevisionBlockDiffPanel, {})
          ] })
        ] })
      }
    );
  };
  var Sidebar = ({ extraPanels, onActionPerformed }) => {
    use_auto_switch_editor_sidebars_default();
    const { tabName, keyboardShortcut } = (0, import_data257.useSelect)((select9) => {
      const shortcut = select9(
        import_keyboard_shortcuts11.store
      ).getShortcutRepresentation("core/editor/toggle-sidebar");
      const sidebar = select9(store3).getActiveComplementaryArea("core");
      const _isEditorSidebarOpened = [
        sidebars.block,
        sidebars.document
      ].includes(sidebar);
      let _tabName = sidebar;
      if (!_isEditorSidebarOpened) {
        _tabName = !!select9(import_block_editor97.store).getBlockSelectionStart() ? sidebars.block : sidebars.document;
      }
      return {
        tabName: _tabName,
        keyboardShortcut: shortcut
      };
    }, []);
    const { enableComplementaryArea: enableComplementaryArea2 } = (0, import_data257.useDispatch)(store3);
    const onTabSelect = (0, import_element332.useCallback)(
      (newSelectedTabId) => {
        if (!!newSelectedTabId) {
          enableComplementaryArea2("core", newSelectedTabId);
        }
      },
      [enableComplementaryArea2]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(
      Tabs3,
      {
        selectedTabId: tabName,
        onSelect: onTabSelect,
        selectOnMove: false,
        children: /* @__PURE__ */ (0, import_jsx_runtime544.jsx)(
          SidebarContent,
          {
            tabName,
            keyboardShortcut,
            onActionPerformed,
            extraPanels
          }
        )
      }
    );
  };
  var sidebar_default2 = Sidebar;

  // packages/editor/build-module/components/collab-sidebar/index.mjs
  var import_i18n344 = __toESM(require_i18n(), 1);
  var import_data266 = __toESM(require_data(), 1);
  var import_element342 = __toESM(require_element(), 1);
  var import_compose84 = __toESM(require_compose(), 1);
  var import_keyboard_shortcuts13 = __toESM(require_keyboard_shortcuts(), 1);
  var import_block_editor106 = __toESM(require_block_editor(), 1);
  var import_preferences30 = __toESM(require_preferences(), 1);

  // packages/editor/build-module/components/collab-sidebar/notes.mjs
  var import_element339 = __toESM(require_element(), 1);
  var import_i18n341 = __toESM(require_i18n(), 1);
  var import_data263 = __toESM(require_data(), 1);
  var import_block_editor102 = __toESM(require_block_editor(), 1);

  // packages/editor/build-module/components/collab-sidebar/note-thread.mjs
  var import_element337 = __toESM(require_element(), 1);
  var import_components281 = __toESM(require_components(), 1);
  var import_compose83 = __toESM(require_compose(), 1);
  var import_i18n339 = __toESM(require_i18n(), 1);
  var import_data261 = __toESM(require_data(), 1);
  var import_dom29 = __toESM(require_dom(), 1);
  var import_block_editor100 = __toESM(require_block_editor(), 1);

  // packages/editor/build-module/components/collab-sidebar/add-note.mjs
  var import_i18n337 = __toESM(require_i18n(), 1);
  var import_element335 = __toESM(require_element(), 1);
  var import_compose82 = __toESM(require_compose(), 1);
  var import_data260 = __toESM(require_data(), 1);
  var import_block_editor99 = __toESM(require_block_editor(), 1);

  // packages/editor/build-module/components/collab-sidebar/note-card.mjs
  var import_components278 = __toESM(require_components(), 1);

  // packages/editor/build-module/components/collab-sidebar/note-byline.mjs
  var import_i18n335 = __toESM(require_i18n(), 1);
  var import_date22 = __toESM(require_date(), 1);
  var import_core_data137 = __toESM(require_core_data(), 1);
  var import_data258 = __toESM(require_data(), 1);
  var import_block_editor98 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime545 = __toESM(require_jsx_runtime(), 1);
  function NoteByline({ avatar, name: name2, date, userId }) {
    const hasAvatar = !!avatar;
    const dateSettings = (0, import_date22.getSettings)();
    const {
      currentUserAvatar,
      currentUserName,
      currentUserId,
      dateFormat = dateSettings.formats.date
    } = (0, import_data258.useSelect)(
      (select9) => {
        const { canUser, getCurrentUser, getEntityRecord } = select9(import_core_data137.store);
        const siteSettings = canUser("read", {
          kind: "root",
          name: "site"
        }) ? getEntityRecord("root", "site") : void 0;
        if (hasAvatar) {
          return {
            dateFormat: siteSettings?.date_format
          };
        }
        const { getSettings: getSettings10 } = select9(import_block_editor98.store);
        const { __experimentalDiscussionSettings } = getSettings10();
        const defaultAvatar = __experimentalDiscussionSettings?.avatarURL;
        const userData = getCurrentUser();
        return {
          currentUserAvatar: userData?.avatar_urls?.[48] ?? defaultAvatar,
          currentUserName: userData?.name,
          currentUserId: userData?.id,
          dateFormat: siteSettings?.date_format
        };
      },
      [hasAvatar]
    );
    const commentDate = (0, import_date22.getDate)(date);
    const commentDateTime = (0, import_date22.dateI18n)("c", commentDate);
    const shouldShowHumanTimeDiff = Math.floor((/* @__PURE__ */ new Date() - commentDate) / (1e3 * 60 * 60 * 24)) < 30;
    const commentDateText = shouldShowHumanTimeDiff ? (0, import_date22.humanTimeDiff)(commentDate) : (0, import_date22.dateI18n)(dateFormat, commentDate);
    const tooltipText = (0, import_date22.dateI18n)(
      // translators: Use a non-breaking space between 'g:i' and 'a' if appropriate.
      (0, import_i18n335._x)("F j, Y g:i\xA0a", "Note date full date format"),
      date
    );
    return /* @__PURE__ */ (0, import_jsx_runtime545.jsxs)(import_jsx_runtime545.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime545.jsx)(
        "img",
        {
          src: avatar || currentUserAvatar,
          className: "editor-collab-sidebar-panel__user-avatar",
          alt: (0, import_i18n335.__)("User avatar"),
          width: 32,
          height: 32,
          style: {
            borderColor: getAvatarBorderColor(
              userId ?? currentUserId
            )
          }
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime545.jsxs)(Stack, { direction: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime545.jsx)("span", { className: "editor-collab-sidebar-panel__user-name", children: name2 ?? currentUserName }),
        date && /* @__PURE__ */ (0, import_jsx_runtime545.jsxs)(tooltip_exports.Root, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime545.jsx)(
            tooltip_exports.Trigger,
            {
              render: /* @__PURE__ */ (0, import_jsx_runtime545.jsx)(
                "time",
                {
                  dateTime: commentDateTime,
                  className: "editor-collab-sidebar-panel__user-time",
                  children: commentDateText
                }
              )
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime545.jsx)(tooltip_exports.Popup, { children: tooltipText })
        ] })
      ] })
    ] });
  }

  // packages/editor/build-module/components/collab-sidebar/note-card.mjs
  var import_jsx_runtime546 = __toESM(require_jsx_runtime(), 1);
  function NoteCard({ note, actions: actions2, className, children, ...props }) {
    return /* @__PURE__ */ (0, import_jsx_runtime546.jsxs)(Stack, { direction: "column", gap: "sm", className, ...props, children: [
      /* @__PURE__ */ (0, import_jsx_runtime546.jsxs)(Stack, { direction: "row", align: "center", justify: "flex-start", gap: "md", children: [
        /* @__PURE__ */ (0, import_jsx_runtime546.jsx)(
          NoteByline,
          {
            avatar: note?.author_avatar_urls?.[48],
            name: note?.author_name,
            date: note?.date,
            userId: note?.author
          }
        ),
        actions2 && /* @__PURE__ */ (0, import_jsx_runtime546.jsx)(
          import_components278.FlexItem,
          {
            className: "editor-collab-sidebar-panel__note-actions",
            onClick: (event) => event.stopPropagation(),
            children: /* @__PURE__ */ (0, import_jsx_runtime546.jsx)(Stack, { direction: "row", align: "center", children: actions2 })
          }
        )
      ] }),
      children
    ] });
  }

  // packages/editor/build-module/components/collab-sidebar/note-form.mjs
  var import_element334 = __toESM(require_element(), 1);
  var import_components279 = __toESM(require_components(), 1);
  var import_i18n336 = __toESM(require_i18n(), 1);
  var import_compose81 = __toESM(require_compose(), 1);
  var import_keycodes21 = __toESM(require_keycodes(), 1);
  var import_dom28 = __toESM(require_dom(), 1);

  // packages/editor/build-module/components/collab-sidebar/note-mention-completer.mjs
  var import_element333 = __toESM(require_element(), 1);
  var import_data259 = __toESM(require_data(), 1);
  var import_core_data138 = __toESM(require_core_data(), 1);
  var import_jsx_runtime547 = __toESM(require_jsx_runtime(), 1);
  var noteMentionCompleter = {
    name: "note-mentions",
    className: "editor-autocompleters__user editor-collab-sidebar-panel__mention-suggestion",
    triggerPrefix: "@",
    useItems(filterValue) {
      const users = (0, import_data259.useSelect)(
        (select9) => {
          const { getUsers } = select9(import_core_data138.store);
          return getUsers({
            context: "view",
            search: filterValue
          });
        },
        [filterValue]
      );
      const options = (0, import_element333.useMemo)(
        () => users ? users.map((user) => ({
          key: `note-mention-${user.slug}`,
          value: user,
          label: getUserLabel(user)
        })) : [],
        [users]
      );
      return [options];
    },
    getOptionCompletion(user) {
      return {
        action: "insert-at-caret",
        value: /* @__PURE__ */ (0, import_jsx_runtime547.jsx)("span", { className: `wp-note-mention user-${user.id}`, children: "@" + user.name })
      };
    }
  };
  var note_mention_completer_default = noteMentionCompleter;

  // packages/editor/build-module/components/collab-sidebar/note-form.mjs
  var import_jsx_runtime548 = __toESM(require_jsx_runtime(), 1);
  var { RichTextControl: RichTextControl2 } = unlock(privateApis13);
  var ALLOWED_NOTE_FORMATS = [
    "core/bold",
    "core/italic",
    "core/link",
    "core/code"
  ];
  var NOTE_COMPLETERS = [note_mention_completer_default];
  function NoteForm({ onSubmit, onCancel, note, labels }) {
    const [inputComment, setInputComment] = (0, import_element334.useState)(
      note?.content?.raw ?? ""
    );
    const [isSubmitting, setIsSubmitting] = (0, import_element334.useState)(false);
    const inputId = (0, import_compose81.useInstanceId)(NoteForm, "comment-input");
    const trimmedPlainText = sanitizeNoteContent((0, import_dom28.__unstableStripHTML)(inputComment));
    const isDisabled = isSubmitting || inputComment === note?.content?.raw || !trimmedPlainText.length;
    async function submit() {
      if (isDisabled) {
        return;
      }
      setIsSubmitting(true);
      const submitted = inputComment;
      const result = await onSubmit(submitted);
      if (result) {
        setInputComment(
          (current) => current === submitted ? "" : current
        );
      }
      setIsSubmitting(false);
    }
    return /* @__PURE__ */ (0, import_jsx_runtime548.jsxs)(
      Stack,
      {
        className: "editor-collab-sidebar-panel__note-form",
        direction: "column",
        gap: "lg",
        render: /* @__PURE__ */ (0, import_jsx_runtime548.jsx)("form", {}),
        onSubmit: (event) => {
          event.preventDefault();
          submit();
        },
        onKeyDown: (event) => {
          if (import_keycodes21.isKeyboardEvent.primary(event, "Enter")) {
            event.preventDefault();
            submit();
            return;
          }
          if (event.key === "Escape" && !event.defaultPrevented) {
            event.preventDefault();
            onCancel(event);
          }
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime548.jsx)(
            RichTextControl2,
            {
              id: inputId,
              label: labels?.input ?? (0, import_i18n336.__)("Note"),
              hideLabelFromVision: true,
              value: inputComment,
              onChange: setInputComment,
              placeholder: labels?.placeholder,
              allowedFormats: ALLOWED_NOTE_FORMATS,
              completers: NOTE_COMPLETERS
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime548.jsxs)(
            Stack,
            {
              direction: "row",
              align: "center",
              justify: "flex-end",
              gap: "sm",
              wrap: "wrap",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime548.jsx)(import_components279.Button, { size: "compact", variant: "tertiary", onClick: onCancel, children: /* @__PURE__ */ (0, import_jsx_runtime548.jsx)(import_components279.__experimentalTruncate, { children: (0, import_i18n336.__)("Cancel") }) }),
                /* @__PURE__ */ (0, import_jsx_runtime548.jsx)(
                  import_components279.Button,
                  {
                    size: "compact",
                    accessibleWhenDisabled: true,
                    variant: "primary",
                    type: "submit",
                    disabled: isDisabled,
                    children: /* @__PURE__ */ (0, import_jsx_runtime548.jsx)(import_components279.__experimentalTruncate, { children: labels?.submit ?? (0, import_i18n336.__)("Add note") })
                  }
                )
              ]
            }
          )
        ]
      }
    );
  }

  // packages/editor/build-module/components/collab-sidebar/floating-container.mjs
  var import_jsx_runtime549 = __toESM(require_jsx_runtime(), 1);
  function FloatingContainer({
    floating,
    className,
    style,
    children,
    ...props
  }) {
    const isFloating = !!floating;
    return /* @__PURE__ */ (0, import_jsx_runtime549.jsx)(
      Stack,
      {
        direction: "column",
        className: clsx_default(className, { "is-floating": isFloating }),
        ref: isFloating ? floating.ref : void 0,
        style: isFloating ? { top: floating.y, ...style } : style,
        ...props,
        children
      }
    );
  }

  // packages/editor/build-module/components/collab-sidebar/add-note.mjs
  var import_jsx_runtime550 = __toESM(require_jsx_runtime(), 1);
  var { useBlockElement } = unlock(import_block_editor99.privateApis);
  function AddNote({ onSubmit, sidebarRef, floating }) {
    const { clientId } = (0, import_data260.useSelect)((select9) => {
      const { getSelectedBlockClientId: getSelectedBlockClientId2 } = select9(import_block_editor99.store);
      return {
        clientId: getSelectedBlockClientId2()
      };
    }, []);
    const selectedNote2 = (0, import_data260.useSelect)(
      (select9) => unlock(select9(store)).getSelectedNote(),
      []
    );
    const blockElement = useBlockElement(clientId);
    const { toggleBlockSpotlight } = unlock((0, import_data260.useDispatch)(import_block_editor99.store));
    const { selectNote: selectNote2 } = unlock((0, import_data260.useDispatch)(store));
    const { getSelectedNote: getSelectedNote2 } = unlock((0, import_data260.useSelect)(store));
    const isSubmittingRef = (0, import_element335.useRef)(false);
    const focusOutside = (0, import_compose82.__experimentalUseFocusOutside)((event) => {
      if (event.relatedTarget?.closest(
        ".editor-collab-sidebar-panel__add-note"
      )) {
        return;
      }
      if (isSubmittingRef.current) {
        return;
      }
      if (getSelectedNote2() === "new") {
        toggleBlockSpotlight(clientId, false);
        selectNote2(void 0);
      }
    });
    const unselectNote = () => {
      selectNote2(void 0);
      blockElement?.focus();
      toggleBlockSpotlight(clientId, false);
    };
    if (selectedNote2 !== "new" || !clientId) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime550.jsx)(
      FloatingContainer,
      {
        floating,
        className: "editor-collab-sidebar-panel__add-note is-selected",
        gap: "md",
        tabIndex: 0,
        "aria-label": (0, import_i18n337.__)("New note"),
        role: "treeitem",
        style: floating ? { opacity: !floating.y ? 0 : void 0 } : void 0,
        ...focusOutside,
        children: /* @__PURE__ */ (0, import_jsx_runtime550.jsx)(NoteCard, { children: /* @__PURE__ */ (0, import_jsx_runtime550.jsx)(
          NoteForm,
          {
            onSubmit: async (inputComment) => {
              isSubmittingRef.current = true;
              try {
                const savedRecord = await onSubmit({
                  content: inputComment
                });
                if (savedRecord) {
                  selectNote2(savedRecord.id);
                  focusNoteThread(
                    savedRecord.id,
                    sidebarRef.current
                  );
                }
                return savedRecord;
              } finally {
                isSubmittingRef.current = false;
              }
            },
            onCancel: unselectNote,
            labels: {
              input: (0, import_i18n337.__)("New note"),
              placeholder: (0, import_i18n337.__)("Add a note or @ mention")
            }
          }
        ) })
      }
    );
  }

  // packages/editor/build-module/components/collab-sidebar/note.mjs
  var import_element336 = __toESM(require_element(), 1);
  var import_components280 = __toESM(require_components(), 1);
  var import_i18n338 = __toESM(require_i18n(), 1);
  var import_jsx_runtime551 = __toESM(require_jsx_runtime(), 1);
  var { Menu: Menu11 } = unlock(import_components280.privateApis);
  function NoteActionsMenu({ items, buttonRef }) {
    return /* @__PURE__ */ (0, import_jsx_runtime551.jsxs)(Menu11, { placement: "bottom-end", children: [
      /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(
        Menu11.TriggerButton,
        {
          render: /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(
            import_components280.Button,
            {
              ref: buttonRef,
              size: "small",
              icon: more_vertical_default,
              label: (0, import_i18n338.__)("Actions"),
              disabled: !items.length,
              accessibleWhenDisabled: true
            }
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(
        Menu11.Popover,
        {
          modal: false,
          children: items.map((item) => /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(Menu11.Item, { onClick: item.onClick, children: /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(Menu11.ItemLabel, { children: item.title }) }, item.id))
        }
      )
    ] });
  }
  function Note({
    note,
    parentNote,
    isSelected: isSelected2,
    onEditNote,
    onDeleteNote,
    onResolve
  }) {
    const [actionState, setActionState] = (0, import_element336.useState)(null);
    const actionButtonRef = (0, import_element336.useRef)(null);
    const commentRef = (0, import_element336.useRef)(null);
    const rawContent = note?.content?.raw;
    const [prevContent, setPrevContent] = (0, import_element336.useState)(rawContent);
    const [isExpanded, setIsExpanded] = (0, import_element336.useState)(false);
    const [isOverflowing, setIsOverflowing] = (0, import_element336.useState)(false);
    if (prevContent !== rawContent) {
      setPrevContent(rawContent);
      setIsExpanded(false);
    }
    (0, import_element336.useLayoutEffect)(() => {
      const commentElement = commentRef.current;
      if (commentElement) {
        setIsOverflowing(
          commentElement.scrollHeight > commentElement.clientHeight
        );
      }
    }, [rawContent]);
    const canResolve = note.parent === 0;
    const isResolutionNote = note.type === "note" && note.meta && (note.meta._wp_note_status === "resolved" || note.meta._wp_note_status === "reopen");
    const menuItems = [
      {
        id: "edit",
        title: (0, import_i18n338.__)("Edit"),
        isEligible: ({ status }) => status !== "approved",
        onClick: () => setActionState("edit")
      },
      {
        id: "reopen",
        title: (0, import_i18n338._x)("Reopen", "Reopen note"),
        isEligible: ({ status }) => status === "approved",
        onClick: () => onEditNote({ id: note.id, status: "hold" })
      },
      {
        id: "delete",
        title: (0, import_i18n338.__)("Delete"),
        isEligible: () => true,
        onClick: () => setActionState("delete")
      }
    ];
    const availableItems = parentNote?.status !== "approved" ? menuItems.filter((item) => item.isEligible(note)) : [];
    const deleteConfirmMessage = note.parent === 0 ? (0, import_i18n338.__)(
      "Are you sure you want to delete this note? This will also delete all of this note's replies."
    ) : (0, import_i18n338.__)("Are you sure you want to delete this reply?");
    const handleCancel = () => {
      setActionState(null);
      actionButtonRef.current?.focus();
    };
    let body;
    if (actionState === "edit") {
      body = /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(
        NoteForm,
        {
          onSubmit: async (value) => {
            const saved = await onEditNote({
              id: note.id,
              content: value
            });
            if (saved) {
              handleCancel();
            }
            return saved;
          },
          onCancel: handleCancel,
          note,
          labels: {
            submit: (0, import_i18n338._x)("Update", "verb"),
            input: (0, import_i18n338.sprintf)(
              // translators: %1$s: note identifier, %2$s: author name.
              (0, import_i18n338.__)("Edit note %1$s by %2$s"),
              note.id,
              note.author_name
            )
          }
        }
      );
    } else {
      let content;
      if (isResolutionNote) {
        const actionText = note.meta._wp_note_status === "resolved" ? (0, import_i18n338.__)("Marked as resolved") : (0, import_i18n338.__)("Reopened");
        const raw = note?.content?.raw;
        content = raw && typeof raw === "string" && raw.trim() !== "" ? (0, import_i18n338.sprintf)(
          // translators: %1$s: action label ("Marked as resolved" or "Reopened"); %2$s: note text.
          (0, import_i18n338.__)("%1$s: %2$s"),
          actionText,
          raw
        ) : actionText;
      } else {
        content = note?.content?.rendered;
      }
      body = /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(
        "div",
        {
          ref: commentRef,
          className: clsx_default("editor-collab-sidebar-panel__note-content", {
            "editor-collab-sidebar-panel__resolution-text": isResolutionNote,
            "is-collapsed": !isExpanded
          }),
          dangerouslySetInnerHTML: { __html: content ?? "" }
        }
      );
    }
    const actions2 = isSelected2 ? /* @__PURE__ */ (0, import_jsx_runtime551.jsxs)(import_jsx_runtime551.Fragment, { children: [
      canResolve && onResolve && /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(
        import_components280.Button,
        {
          label: (0, import_i18n338._x)("Resolve", "Mark note as resolved"),
          size: "small",
          icon: published_default,
          disabled: note.status === "approved",
          accessibleWhenDisabled: note.status === "approved",
          onClick: onResolve
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(
        NoteActionsMenu,
        {
          items: availableItems,
          buttonRef: actionButtonRef
        }
      )
    ] }) : null;
    return /* @__PURE__ */ (0, import_jsx_runtime551.jsxs)(
      NoteCard,
      {
        note,
        actions: actions2,
        role: note.parent !== 0 ? "treeitem" : void 0,
        children: [
          body,
          actionState === "delete" && /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(
            import_components280.__experimentalConfirmDialog,
            {
              isOpen: true,
              onConfirm: () => {
                onDeleteNote(note);
                setActionState(null);
              },
              onCancel: handleCancel,
              confirmButtonText: (0, import_i18n338.__)("Delete"),
              children: deleteConfirmMessage
            }
          ),
          isOverflowing && "edit" !== actionState && /* @__PURE__ */ (0, import_jsx_runtime551.jsx)(
            Button5,
            {
              className: "editor-collab-sidebar-panel__show-more-button",
              variant: "unstyled",
              size: "small",
              onClick: () => setIsExpanded(!isExpanded),
              children: !isExpanded ? (0, import_i18n338.__)("Show more") : (0, import_i18n338.__)("Show less")
            }
          )
        ]
      }
    );
  }

  // packages/editor/build-module/components/collab-sidebar/note-thread.mjs
  var import_jsx_runtime552 = __toESM(require_jsx_runtime(), 1);
  var { useBlockElement: useBlockElement2 } = unlock(import_block_editor100.privateApis);
  function NoteThread({
    note,
    onEditNote,
    onAddReply,
    onDeleteNote,
    isSelected: isSelected2,
    sidebarRef,
    floating,
    onKeyDown
  }) {
    const isFloating = !!floating;
    const { toggleBlockHighlight, selectBlock: selectBlock2, toggleBlockSpotlight } = unlock(
      (0, import_data261.useDispatch)(import_block_editor100.store)
    );
    const { selectNote: selectNote2 } = unlock((0, import_data261.useDispatch)(store));
    const { getSelectedNote: getSelectedNote2 } = unlock((0, import_data261.useSelect)(store));
    const relatedBlockElement = useBlockElement2(note.blockClientId);
    const debouncedToggleBlockHighlight = (0, import_compose83.useDebounce)(
      toggleBlockHighlight,
      50
    );
    const floatingRef = (0, import_element337.useRef)(null);
    const isKeyboardTabbingRef = (0, import_element337.useRef)(false);
    const registerThread = floating?.registerThread;
    const unregisterThread = floating?.unregisterThread;
    (0, import_element337.useEffect)(() => {
      const floatingEl = floatingRef.current;
      if (floatingEl && registerThread) {
        registerThread(note.id, relatedBlockElement, floatingEl);
      }
      return () => unregisterThread?.(note.id);
    }, [relatedBlockElement, note.id, registerThread, unregisterThread]);
    (0, import_element337.useEffect)(() => {
      if (!isSelected2 || note.id === "new") {
        return;
      }
      scrollNoteThreadIntoView(note.id, sidebarRef.current);
    }, [isSelected2, floating?.y, note.id, sidebarRef]);
    const focusOutside = (0, import_compose83.__experimentalUseFocusOutside)((event) => {
      const isNoteFocused2 = event.relatedTarget?.closest(
        ".editor-collab-sidebar-panel__thread"
      );
      if (isNoteFocused2 && !isKeyboardTabbingRef.current) {
        return;
      }
      if (!isNoteFocused2) {
        debouncedToggleBlockHighlight.cancel();
        toggleBlockHighlight(note.blockClientId, false);
      }
      if (getSelectedNote2() === note.id) {
        onDeselectNote();
      }
    });
    function onMouseEnter() {
      debouncedToggleBlockHighlight(note.blockClientId, true);
    }
    function onMouseLeave() {
      debouncedToggleBlockHighlight(note.blockClientId, false);
    }
    function onFocus(event) {
      focusOutside.onFocus(event);
      debouncedToggleBlockHighlight.cancel();
      toggleBlockHighlight(note.blockClientId, true);
    }
    function onSelectNote() {
      if (isSelected2) {
        return;
      }
      selectNote2(note.id);
      focusNoteThread(note.id, sidebarRef.current);
      toggleBlockSpotlight(note.blockClientId, true);
      if (!!note.blockClientId) {
        selectBlock2(note.blockClientId, null);
      }
    }
    function onDeselectNote() {
      selectNote2(void 0);
      toggleBlockSpotlight(note.blockClientId, false);
    }
    function handleResolve() {
      onEditNote({ id: note.id, status: "approved" });
      onDeselectNote();
      if (isFloating) {
        relatedBlockElement?.focus();
      } else {
        focusNoteThread(note.id, sidebarRef.current);
      }
    }
    const allReplies = note?.reply || [];
    const lastReply = allReplies.length > 0 ? allReplies[allReplies.length - 1] : void 0;
    const restReplies = allReplies.length > 0 ? allReplies.slice(0, -1) : [];
    const noteExcerpt = getNoteExcerpt(
      (0, import_dom29.__unstableStripHTML)(note.content?.rendered),
      10
    );
    const ariaLabel = !!note.blockClientId ? (0, import_i18n339.sprintf)(
      // translators: %s: note excerpt
      (0, import_i18n339.__)("Note: %s"),
      noteExcerpt
    ) : (0, import_i18n339.sprintf)(
      // translators: %s: note excerpt
      (0, import_i18n339.__)("Original block deleted. Note: %s"),
      noteExcerpt
    );
    if (isFloating && note.id === "new") {
      return /* @__PURE__ */ (0, import_jsx_runtime552.jsx)(
        AddNote,
        {
          onSubmit: onAddReply,
          sidebarRef,
          floating: { y: floating.y, ref: floatingRef }
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime552.jsxs)(
      FloatingContainer,
      {
        floating: isFloating ? { y: floating.y, ref: floatingRef } : void 0,
        className: clsx_default("editor-collab-sidebar-panel__thread", {
          "is-selected": isSelected2
        }),
        id: `note-thread-${note.id}`,
        gap: "md",
        onClick: onSelectNote,
        onMouseEnter,
        onMouseLeave,
        ...focusOutside,
        onFocus,
        onKeyUp: (event) => {
          if (event.key === "Tab") {
            isKeyboardTabbingRef.current = false;
          }
        },
        onKeyDown: (event) => {
          if (event.key === "Tab") {
            isKeyboardTabbingRef.current = true;
          } else {
            onKeyDown(event);
          }
        },
        tabIndex: 0,
        role: "treeitem",
        "aria-label": ariaLabel,
        "aria-expanded": isSelected2,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime552.jsx)(
            import_components281.Button,
            {
              className: "editor-collab-sidebar-panel__skip-to-note",
              variant: "secondary",
              size: "compact",
              onClick: () => {
                focusNoteThread(
                  note.id,
                  sidebarRef.current,
                  '[role="textbox"]'
                );
              },
              children: (0, import_i18n339.__)("Add new reply")
            }
          ),
          !note.blockClientId && /* @__PURE__ */ (0, import_jsx_runtime552.jsx)("p", { className: "editor-collab-sidebar-panel__deleted-block-notice", children: (0, import_i18n339.__)("Original block deleted.") }),
          /* @__PURE__ */ (0, import_jsx_runtime552.jsx)(
            Note,
            {
              note,
              isSelected: isSelected2,
              onEditNote,
              onDeleteNote,
              onResolve: handleResolve
            }
          ),
          isSelected2 && allReplies.map((reply) => /* @__PURE__ */ (0, import_jsx_runtime552.jsx)(
            Note,
            {
              note: reply,
              parentNote: note,
              isSelected: isSelected2,
              onEditNote,
              onDeleteNote
            },
            reply.id
          )),
          !isSelected2 && restReplies.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime552.jsx)(
            Stack,
            {
              direction: "row",
              align: "center",
              justify: "space-between",
              className: "editor-collab-sidebar-panel__more-reply-separator",
              children: /* @__PURE__ */ (0, import_jsx_runtime552.jsx)(
                import_components281.Button,
                {
                  size: "compact",
                  variant: "tertiary",
                  className: "editor-collab-sidebar-panel__more-reply-button",
                  onClick: (event) => {
                    event.stopPropagation();
                    onSelectNote();
                  },
                  children: (0, import_i18n339.sprintf)(
                    // translators: %s: number of replies.
                    (0, import_i18n339._n)(
                      "%s more reply",
                      "%s more replies",
                      restReplies.length
                    ),
                    restReplies.length
                  )
                }
              )
            }
          ),
          !isSelected2 && lastReply && /* @__PURE__ */ (0, import_jsx_runtime552.jsx)(
            Note,
            {
              note: lastReply,
              parentNote: note,
              isSelected: false,
              onEditNote,
              onDeleteNote
            }
          ),
          isSelected2 && /* @__PURE__ */ (0, import_jsx_runtime552.jsx)(NoteCard, { role: "treeitem", children: /* @__PURE__ */ (0, import_jsx_runtime552.jsx)(
            NoteForm,
            {
              onSubmit: (inputComment) => {
                if ("approved" === note.status) {
                  return onEditNote({
                    id: note.id,
                    status: "hold",
                    content: inputComment
                  });
                }
                return onAddReply({
                  content: inputComment,
                  parent: note.id
                });
              },
              onCancel: (event) => {
                event.stopPropagation();
                onDeselectNote();
                focusNoteThread(note.id, sidebarRef.current);
              },
              labels: {
                submit: "approved" === note.status ? (0, import_i18n339.__)("Reopen & Reply") : (0, import_i18n339.__)("Reply"),
                input: (0, import_i18n339.sprintf)(
                  // translators: %1$s: note identifier, %2$s: author name
                  (0, import_i18n339.__)("Reply to note %1$s by %2$s"),
                  note.id,
                  note.author_name
                ),
                placeholder: (0, import_i18n339.__)("Reply or @ mention")
              }
            }
          ) }),
          !!note.blockClientId && /* @__PURE__ */ (0, import_jsx_runtime552.jsx)(
            import_components281.Button,
            {
              className: "editor-collab-sidebar-panel__skip-to-block",
              variant: "secondary",
              size: "compact",
              onClick: (event) => {
                event.stopPropagation();
                relatedBlockElement?.focus();
              },
              children: (0, import_i18n339.__)("Back to block")
            }
          )
        ]
      }
    );
  }

  // packages/editor/build-module/components/collab-sidebar/hooks.mjs
  var import_a11y12 = __toESM(require_a11y(), 1);
  var import_i18n340 = __toESM(require_i18n(), 1);
  var import_element338 = __toESM(require_element(), 1);
  var import_core_data139 = __toESM(require_core_data(), 1);
  var import_data262 = __toESM(require_data(), 1);
  var import_block_editor101 = __toESM(require_block_editor(), 1);
  var import_notices37 = __toESM(require_notices(), 1);
  var import_dom30 = __toESM(require_dom(), 1);
  var import_html_entities37 = __toESM(require_html_entities(), 1);
  var import_rich_text9 = __toESM(require_rich_text(), 1);

  // packages/editor/build-module/components/collab-sidebar/board-store.mjs
  function createBoardStore() {
    const listeners2 = /* @__PURE__ */ new Set();
    const blockRefs = /* @__PURE__ */ new Map();
    const floatingRefs = /* @__PURE__ */ new Map();
    const idByElement = /* @__PURE__ */ new WeakMap();
    const heights = {};
    let snapshot = {};
    function emit() {
      snapshot = { ...heights };
      for (const listener of listeners2) {
        listener();
      }
    }
    const observer = new window.ResizeObserver((entries) => {
      let changed = false;
      for (const entry of entries) {
        const id = idByElement.get(entry.target);
        const newHeight = entry.borderBoxSize[0].blockSize;
        if (heights[id] !== newHeight) {
          heights[id] = newHeight;
          changed = true;
        }
      }
      if (changed) {
        emit();
      }
    });
    return {
      subscribe(listener) {
        listeners2.add(listener);
        return () => {
          listeners2.delete(listener);
          if (listeners2.size === 0) {
            observer.disconnect();
          }
        };
      },
      getSnapshot() {
        return snapshot;
      },
      registerThread(id, blockEl, floatingEl) {
        blockRefs.set(id, blockEl);
        const prev = floatingRefs.get(id);
        if (prev && prev !== floatingEl) {
          observer.unobserve(prev);
          idByElement.delete(prev);
        }
        if (floatingEl) {
          floatingRefs.set(id, floatingEl);
          idByElement.set(floatingEl, id);
          observer.observe(floatingEl);
        }
        emit();
      },
      unregisterThread(id) {
        blockRefs.delete(id);
        const prev = floatingRefs.get(id);
        if (prev) {
          observer.unobserve(prev);
          idByElement.delete(prev);
          floatingRefs.delete(id);
        }
        delete heights[id];
      },
      getAnchorRects() {
        return Object.fromEntries(
          Array.from(blockRefs).flatMap(([id, el]) => {
            if (!el) {
              return [];
            }
            if (id === "new") {
              const rect = getSelectionRect(el) ?? el.getBoundingClientRect();
              return [[id, rect]];
            }
            const anchor = el.querySelector(getNoteMarkerSelector(id)) ?? el;
            return [[id, anchor.getBoundingClientRect()]];
          })
        );
      },
      getFirstBlockElement() {
        return blockRefs.values().next().value ?? null;
      }
    };
  }

  // packages/editor/build-module/components/collab-sidebar/hooks.mjs
  var { cleanEmptyObject: cleanEmptyObject3 } = unlock(import_block_editor101.privateApis);
  function useNoteThreads(postId2) {
    const queryArgs = {
      post: postId2,
      type: "note",
      status: "all",
      per_page: -1
    };
    const { records: threads } = (0, import_core_data139.useEntityRecords)(
      "root",
      "comment",
      queryArgs,
      { enabled: !!postId2 && typeof postId2 === "number" }
    );
    const { getBlockAttributes: getBlockAttributes2 } = (0, import_data262.useSelect)(import_block_editor101.store);
    const { clientIds } = (0, import_data262.useSelect)((select9) => {
      const { getClientIdsWithDescendants: getClientIdsWithDescendants2 } = select9(import_block_editor101.store);
      return {
        clientIds: getClientIdsWithDescendants2()
      };
    }, []);
    const { notes, unresolvedNotes } = (0, import_element338.useMemo)(() => {
      if (!threads || threads.length === 0) {
        return { notes: [], unresolvedNotes: [] };
      }
      const blocksWithNotes = {};
      const clientIdByNoteId = /* @__PURE__ */ new Map();
      for (const clientId of clientIds) {
        const metadata = getBlockAttributes2(clientId)?.metadata;
        const noteIds = getNoteIdsFromMetadata(metadata);
        if (noteIds.length > 0) {
          blocksWithNotes[clientId] = noteIds;
          for (const noteId of noteIds) {
            clientIdByNoteId.set(noteId, clientId);
          }
        }
      }
      const threadsById = /* @__PURE__ */ new Map();
      const rootThreads = [];
      for (const item of threads) {
        const thread = {
          ...item,
          reply: [],
          blockClientId: item.parent === 0 ? clientIdByNoteId.get(item.id) ?? null : null
        };
        threadsById.set(item.id, thread);
        if (item.parent === 0) {
          rootThreads.push(thread);
        }
      }
      for (const item of threads) {
        if (item.parent !== 0) {
          threadsById.get(item.parent)?.reply.unshift(threadsById.get(item.id));
        }
      }
      if (rootThreads.length === 0) {
        return { notes: [], unresolvedNotes: [] };
      }
      const unresolved = [];
      const resolved = [];
      for (const [clientId, noteIds] of Object.entries(
        blocksWithNotes
      )) {
        const attributes = getBlockAttributes2(clientId);
        const orderedThreads = noteIds.map((noteId) => {
          const thread = threadsById.get(noteId);
          if (!thread) {
            return null;
          }
          return {
            thread,
            start: getInlineMarkerStart(thread, attributes)
          };
        }).filter(Boolean).sort((a3, b3) => {
          if (a3.start !== b3.start) {
            return a3.start - b3.start;
          }
          return a3.thread.id - b3.thread.id;
        });
        for (const { thread } of orderedThreads) {
          if (thread.status === "hold") {
            unresolved.push(thread);
          } else if (thread.status === "approved") {
            resolved.push(thread);
          }
        }
      }
      const orphans = rootThreads.filter(
        (thread) => !thread.blockClientId
      );
      return {
        notes: [...unresolved, ...orphans, ...resolved],
        unresolvedNotes: unresolved
      };
    }, [clientIds, threads, getBlockAttributes2]);
    return {
      notes,
      unresolvedNotes
    };
  }
  function readInlineSelection(getSelectionStart, getSelectionEnd) {
    const start2 = getSelectionStart();
    const end = getSelectionEnd();
    if (!start2?.clientId || start2.clientId !== end.clientId || !start2.attributeKey || start2.offset === void 0 || end.offset === void 0 || start2.offset === end.offset) {
      return null;
    }
    const [startOffset, endOffset] = start2.offset < end.offset ? [start2.offset, end.offset] : [end.offset, start2.offset];
    return {
      clientId: start2.clientId,
      attributeKey: start2.attributeKey,
      start: startOffset,
      end: endOffset
    };
  }
  function wrapInlineNote(value, id, start2, end) {
    if (!(value instanceof import_rich_text9.RichTextData)) {
      return null;
    }
    const record = applyNoteFormat(
      (0, import_rich_text9.create)({ html: value.toHTMLString() }),
      { type: NOTE_FORMAT_NAME, attributes: { "data-id": String(id) } },
      start2,
      end
    );
    return import_rich_text9.RichTextData.fromHTMLString(
      new import_rich_text9.RichTextData(record).toHTMLString()
    );
  }
  function clearInlineNoteMarker(noteId, getClientIdsWithDescendants2, getBlockAttributes2, updateBlockAttributes2) {
    for (const clientId of getClientIdsWithDescendants2()) {
      const attributes = getBlockAttributes2(clientId);
      const found = findNoteInBlock(attributes, noteId);
      if (!found) {
        continue;
      }
      const next = removeNoteFormat(
        attributes[found.attributeKey],
        noteId
      );
      if (next) {
        updateBlockAttributes2(clientId, { [found.attributeKey]: next });
      }
      return;
    }
  }
  function useNoteActions() {
    const { createNotice } = (0, import_data262.useDispatch)(import_notices37.store);
    const { saveEntityRecord, deleteEntityRecord } = (0, import_data262.useDispatch)(import_core_data139.store);
    const { getCurrentPostId: getCurrentPostId2 } = (0, import_data262.useSelect)(store);
    const {
      getBlockAttributes: getBlockAttributes2,
      getClientIdsWithDescendants: getClientIdsWithDescendants2,
      getSelectedBlockClientId: getSelectedBlockClientId2,
      getSelectionStart,
      getSelectionEnd
    } = (0, import_data262.useSelect)(import_block_editor101.store);
    const { updateBlockAttributes: updateBlockAttributes2 } = (0, import_data262.useDispatch)(import_block_editor101.store);
    const onError = (error2) => {
      const errorMessage = error2.message && error2.code !== "unknown_error" ? (0, import_html_entities37.decodeEntities)(error2.message) : (0, import_i18n340.__)("An error occurred while performing an update.");
      createNotice("error", errorMessage, {
        type: "snackbar",
        isDismissible: true
      });
    };
    const onCreate = async ({ content, parent }) => {
      try {
        const inlineSelection = !parent ? readInlineSelection(getSelectionStart, getSelectionEnd) : null;
        const clientId = !parent ? inlineSelection?.clientId || getSelectedBlockClientId2() : null;
        const savedRecord = await saveEntityRecord(
          "root",
          "comment",
          {
            post: getCurrentPostId2(),
            content,
            status: "hold",
            type: "note",
            parent: parent || 0
          },
          { throwOnError: true }
        );
        if (!parent && savedRecord?.id && clientId) {
          const attributes = getBlockAttributes2(clientId);
          const metadata = attributes?.metadata;
          const updatedMetadata = addNoteIdToMetadata(
            metadata,
            savedRecord.id
          );
          const newAttributes = {
            metadata: cleanEmptyObject3(updatedMetadata)
          };
          if (inlineSelection) {
            const wrapped = wrapInlineNote(
              attributes?.[inlineSelection.attributeKey],
              savedRecord.id,
              inlineSelection.start,
              inlineSelection.end
            );
            if (wrapped) {
              newAttributes[inlineSelection.attributeKey] = wrapped;
            }
          }
          updateBlockAttributes2(clientId, newAttributes);
        }
        createNotice(
          "snackbar",
          parent ? (0, import_i18n340.__)("Reply added.") : (0, import_i18n340.__)("Note added."),
          {
            type: "snackbar",
            isDismissible: true
          }
        );
        return savedRecord;
      } catch (error2) {
        onError(error2);
      }
    };
    const onEdit = async ({ id, content, status }) => {
      try {
        if (status === "approved" || status === "hold") {
          await saveEntityRecord(
            "root",
            "comment",
            {
              id,
              status
            },
            {
              throwOnError: true
            }
          );
          const newNoteData = {
            post: getCurrentPostId2(),
            content: content || "",
            // Empty content for resolve, content for reopen.
            type: "note",
            status,
            parent: id,
            meta: {
              _wp_note_status: status === "approved" ? "resolved" : "reopen"
            }
          };
          const savedRecord2 = await saveEntityRecord(
            "root",
            "comment",
            newNoteData,
            {
              throwOnError: true
            }
          );
          if (status === "approved") {
            clearInlineNoteMarker(
              id,
              getClientIdsWithDescendants2,
              getBlockAttributes2,
              updateBlockAttributes2
            );
          }
          (0, import_a11y12.speak)(
            status === "approved" ? (0, import_i18n340.__)("Note marked as resolved.") : (0, import_i18n340.__)("Note reopened.")
          );
          return savedRecord2;
        }
        const updateData = {
          id,
          content,
          status
        };
        const savedRecord = await saveEntityRecord(
          "root",
          "comment",
          updateData,
          {
            throwOnError: true
          }
        );
        createNotice("snackbar", (0, import_i18n340.__)("Note updated."), {
          type: "snackbar",
          isDismissible: true
        });
        return savedRecord;
      } catch (error2) {
        onError(error2);
      }
    };
    const onDelete = async (note) => {
      try {
        const clientId = !note.parent ? note.blockClientId || getSelectedBlockClientId2() : null;
        await deleteEntityRecord("root", "comment", note.id, void 0, {
          throwOnError: true
        });
        if (clientId) {
          const attributes = getBlockAttributes2(clientId);
          const newAttributes = {
            metadata: cleanEmptyObject3(
              removeNoteIdFromMetadata(
                attributes?.metadata,
                note.id
              )
            )
          };
          const found = findNoteInBlock(attributes, note.id);
          if (found) {
            const next = removeNoteFormat(
              attributes[found.attributeKey],
              note.id
            );
            if (next) {
              newAttributes[found.attributeKey] = next;
            }
          }
          updateBlockAttributes2(clientId, newAttributes);
        }
        createNotice("snackbar", (0, import_i18n340.__)("Note deleted."), {
          type: "snackbar",
          isDismissible: true
        });
        return true;
      } catch (error2) {
        onError(error2);
      }
    };
    return { onCreate, onEdit, onDelete };
  }
  function useEnableFloatingSidebar(enabled = false) {
    const registry = (0, import_data262.useRegistry)();
    (0, import_element338.useEffect)(() => {
      if (!enabled) {
        return;
      }
      const { getActiveComplementaryArea: getActiveComplementaryArea2 } = registry.select(store3);
      const { disableComplementaryArea: disableComplementaryArea2, enableComplementaryArea: enableComplementaryArea2 } = registry.dispatch(store3);
      const unsubscribe = registry.subscribe(() => {
        if (getActiveComplementaryArea2("core") === null) {
          enableComplementaryArea2("core", FLOATING_NOTES_SIDEBAR);
        }
      });
      return () => {
        unsubscribe();
        if (getActiveComplementaryArea2("core") === FLOATING_NOTES_SIDEBAR) {
          disableComplementaryArea2("core", FLOATING_NOTES_SIDEBAR);
        }
      };
    }, [enabled, registry]);
  }
  function useFloatingBoard({
    threads,
    selectedNoteId,
    isFloating,
    sidebarRef
  }) {
    const [notePositions, setNotePositions] = (0, import_element338.useState)({});
    const [store4] = (0, import_element338.useState)(createBoardStore);
    const heights = (0, import_element338.useSyncExternalStore)(store4.subscribe, store4.getSnapshot);
    (0, import_element338.useEffect)(() => {
      if (!isFloating || !sidebarRef?.current) {
        return;
      }
      const panel = sidebarRef.current;
      const blockEl = store4.getFirstBlockElement();
      const rootEl = blockEl?.closest(".is-root-container") ?? blockEl;
      const canvas = rootEl ? (0, import_dom30.getScrollContainer)(rootEl) : null;
      const applyScroll = () => {
        panel.style.setProperty(
          "--canvas-scroll",
          `${-(canvas?.scrollTop ?? 0)}px`
        );
      };
      let rafId;
      const schedule2 = () => {
        window.cancelAnimationFrame(rafId);
        rafId = window.requestAnimationFrame(() => {
          const result = calculateNotePositions({
            threads,
            selectedNoteId,
            blockRects: store4.getAnchorRects(),
            heights,
            scrollTop: canvas?.scrollTop ?? 0
          });
          setNotePositions(result.positions);
          applyScroll();
        });
      };
      schedule2();
      const contentObserver = new window.ResizeObserver(schedule2);
      if (rootEl) {
        contentObserver.observe(rootEl);
      }
      const view = canvas?.ownerDocument?.defaultView;
      const listenerOptions = { passive: true, capture: true };
      view?.addEventListener("scroll", applyScroll, listenerOptions);
      return () => {
        window.cancelAnimationFrame(rafId);
        contentObserver.disconnect();
        view?.removeEventListener("scroll", applyScroll, listenerOptions);
      };
    }, [sidebarRef, heights, isFloating, selectedNoteId, store4, threads]);
    return {
      notePositions,
      registerThread: store4.registerThread,
      unregisterThread: store4.unregisterThread
    };
  }

  // packages/editor/build-module/components/collab-sidebar/notes.mjs
  var import_jsx_runtime553 = __toESM(require_jsx_runtime(), 1);
  var { useBlockElement: useBlockElement3 } = unlock(import_block_editor102.privateApis);
  function Notes({ notes, sidebarRef, isFloating = false, styles }) {
    const {
      onCreate: onAddReply,
      onEdit: onEditNote,
      onDelete
    } = useNoteActions();
    const { selectNote: selectNote2 } = unlock((0, import_data263.useDispatch)(store));
    const { selectBlock: selectBlock2, toggleBlockSpotlight } = unlock(
      (0, import_data263.useDispatch)(import_block_editor102.store)
    );
    const { noteId, selectedBlockClientId, orderedBlockIds } = (0, import_data263.useSelect)(
      (select9) => {
        const {
          getBlockAttributes: getBlockAttributes2,
          getSelectedBlockClientId: getSelectedBlockClientId2,
          getClientIdsWithDescendants: getClientIdsWithDescendants2
        } = select9(import_block_editor102.store);
        const clientId = getSelectedBlockClientId2();
        return {
          noteId: clientId ? getBlockAttributes2(clientId)?.metadata?.noteId : null,
          selectedBlockClientId: clientId,
          orderedBlockIds: getClientIdsWithDescendants2()
        };
      },
      []
    );
    const { selectedNote: selectedNote2, noteFocused } = (0, import_data263.useSelect)((select9) => {
      const { getSelectedNote: getSelectedNote2, isNoteFocused: isNoteFocused2 } = unlock(
        select9(store)
      );
      return {
        selectedNote: getSelectedNote2(),
        noteFocused: isNoteFocused2()
      };
    }, []);
    const relatedBlockElement = useBlockElement3(selectedBlockClientId);
    const threads = (0, import_element339.useMemo)(() => {
      if (!isFloating || selectedNote2 !== "new") {
        return notes;
      }
      const newNoteThread = {
        id: "new",
        blockClientId: selectedBlockClientId,
        content: { rendered: "" }
      };
      const out = [];
      orderedBlockIds.forEach((blockId) => {
        const threadsForBlock = notes.filter(
          (t4) => t4.blockClientId === blockId
        );
        out.push(...threadsForBlock);
        if (blockId === selectedBlockClientId) {
          out.push(newNoteThread);
        }
      });
      return out;
    }, [
      notes,
      isFloating,
      selectedNote2,
      selectedBlockClientId,
      orderedBlockIds
    ]);
    const handleDelete = async (note) => {
      const currentIndex = threads.findIndex((t4) => t4.id === note.id);
      const nextThread = threads[currentIndex + 1];
      const prevThread = threads[currentIndex - 1];
      const deleted = await onDelete(note);
      if (!deleted) {
        return;
      }
      if (note.parent !== 0) {
        selectNote2(note.parent);
        focusNoteThread(note.parent, sidebarRef.current);
        return;
      }
      const adjacentThread = nextThread ?? prevThread;
      if (adjacentThread) {
        selectNote2(adjacentThread.id);
        focusNoteThread(adjacentThread.id, sidebarRef.current);
        if (adjacentThread.blockClientId) {
          toggleBlockSpotlight(adjacentThread.blockClientId, true);
          selectBlock2(adjacentThread.blockClientId, null);
        }
      } else {
        selectNote2(void 0);
        toggleBlockSpotlight(note.blockClientId, false);
        relatedBlockElement?.focus();
      }
    };
    const targetNoteId = (0, import_element339.useMemo)(() => {
      const blockNoteIds = getNoteIdsFromMetadata({ noteId });
      const blockThreads = notes.filter(
        (t4) => blockNoteIds.includes(t4.id)
      );
      return pickPrimaryNote(blockThreads)?.id;
    }, [noteId, notes]);
    const prevBlockIdRef = (0, import_element339.useRef)(selectedBlockClientId);
    (0, import_element339.useEffect)(() => {
      if (prevBlockIdRef.current === selectedBlockClientId) {
        return;
      }
      prevBlockIdRef.current = selectedBlockClientId;
      selectNote2(targetNoteId);
    }, [selectedBlockClientId, targetNoteId, selectNote2]);
    (0, import_element339.useEffect)(() => {
      if (noteFocused && selectedNote2) {
        focusNoteThread(
          selectedNote2,
          sidebarRef.current,
          selectedNote2 === "new" ? '[role="textbox"]' : void 0
        );
        selectNote2(selectedNote2);
      }
    }, [noteFocused, selectedNote2, selectNote2, sidebarRef]);
    const { notePositions, registerThread, unregisterThread } = useFloatingBoard({
      threads,
      selectedNoteId: selectedNote2,
      isFloating,
      sidebarRef
    });
    const hasThreads = Array.isArray(threads) && threads.length > 0;
    const navigate = (event, thread, isSelected2) => {
      if (event.defaultPrevented) {
        return;
      }
      const currentIndex = threads.findIndex((t4) => t4.id === thread.id);
      const isSelfTarget2 = event.currentTarget === event.target;
      if ((event.key === "Enter" || event.key === "ArrowRight") && isSelfTarget2 && !isSelected2) {
        selectNote2(thread.id);
        if (!!thread.blockClientId) {
          selectBlock2(thread.blockClientId, null);
          toggleBlockSpotlight(thread.blockClientId, true);
        }
      } else if ((event.key === "Enter" || event.key === "ArrowLeft") && isSelfTarget2 && isSelected2 || event.key === "Escape") {
        selectNote2(void 0);
        if (thread.blockClientId) {
          toggleBlockSpotlight(thread.blockClientId, false);
        }
        focusNoteThread(thread.id, sidebarRef.current);
      } else if (event.key === "ArrowDown" && currentIndex < threads.length - 1 && isSelfTarget2) {
        focusNoteThread(
          threads[currentIndex + 1].id,
          sidebarRef.current
        );
      } else if (event.key === "ArrowUp" && currentIndex > 0 && isSelfTarget2) {
        focusNoteThread(
          threads[currentIndex - 1].id,
          sidebarRef.current
        );
      } else if (event.key === "Home" && isSelfTarget2) {
        focusNoteThread(threads[0].id, sidebarRef.current);
      } else if (event.key === "End" && isSelfTarget2) {
        focusNoteThread(
          threads[threads.length - 1].id,
          sidebarRef.current
        );
      }
    };
    const firstResolvedIndex = isFloating ? -1 : threads.findIndex(
      (thread) => thread.status === "approved" && !!thread.blockClientId
    );
    return /* @__PURE__ */ (0, import_jsx_runtime553.jsx)(
      Stack,
      {
        className: "editor-collab-sidebar-panel",
        style: styles,
        role: "tree",
        direction: "column",
        gap: "md",
        justify: "flex-start",
        ref: (node) => {
          if (node) {
            sidebarRef.current = node;
          }
        },
        "aria-label": isFloating ? (0, import_i18n341.__)("Unresolved notes") : (0, import_i18n341.__)("All notes"),
        children: !hasThreads && !isFloating ? /* @__PURE__ */ (0, import_jsx_runtime553.jsx)(AddNote, { onSubmit: onAddReply, sidebarRef }) : /* @__PURE__ */ (0, import_jsx_runtime553.jsxs)(import_jsx_runtime553.Fragment, { children: [
          !isFloating && selectedNote2 === "new" && /* @__PURE__ */ (0, import_jsx_runtime553.jsx)(
            AddNote,
            {
              onSubmit: onAddReply,
              sidebarRef
            }
          ),
          threads.map((thread, index2) => /* @__PURE__ */ (0, import_jsx_runtime553.jsxs)(import_element339.Fragment, { children: [
            index2 === firstResolvedIndex && /* @__PURE__ */ (0, import_jsx_runtime553.jsx)(
              Stack,
              {
                direction: "row",
                align: "center",
                justify: "center",
                gap: "sm",
                className: "editor-collab-sidebar-panel__status-separator",
                children: /* @__PURE__ */ (0, import_jsx_runtime553.jsx)(Text, { variant: "heading-sm", render: /* @__PURE__ */ (0, import_jsx_runtime553.jsx)("p", {}), children: (0, import_i18n341.__)("Resolved") })
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime553.jsx)(
              NoteThread,
              {
                note: thread,
                onAddReply,
                onDeleteNote: handleDelete,
                onEditNote,
                isSelected: selectedNote2 === thread.id,
                sidebarRef,
                floating: isFloating ? {
                  y: notePositions[thread.id],
                  registerThread,
                  unregisterThread
                } : void 0,
                onKeyDown: (event) => navigate(
                  event,
                  thread,
                  selectedNote2 === thread.id
                )
              }
            )
          ] }, thread.id))
        ] })
      }
    );
  }

  // packages/editor/build-module/components/collab-sidebar/add-note-menu-item.mjs
  var import_components282 = __toESM(require_components(), 1);
  var import_i18n342 = __toESM(require_i18n(), 1);
  var import_block_editor103 = __toESM(require_block_editor(), 1);
  var import_data264 = __toESM(require_data(), 1);
  var import_blocks38 = __toESM(require_blocks(), 1);
  var import_keyboard_shortcuts12 = __toESM(require_keyboard_shortcuts(), 1);
  var import_jsx_runtime554 = __toESM(require_jsx_runtime(), 1);
  var { NoteIconSlotFill } = unlock(import_block_editor103.privateApis);
  function NoteMenuItem({ clientId, onClick, isDistractionFree }) {
    const block = (0, import_data264.useSelect)(
      (select9) => {
        return select9(import_block_editor103.store).getBlock(clientId);
      },
      [clientId]
    );
    const shortcut = (0, import_data264.useSelect)(
      (select9) => select9(import_keyboard_shortcuts12.store).getShortcutRepresentation(
        "core/editor/new-note"
      ),
      []
    );
    if (!block?.isValid || block?.name === (0, import_blocks38.getUnregisteredTypeHandlerName)()) {
      return null;
    }
    const isDisabled = isDistractionFree || block?.name === "core/freeform";
    let infoText;
    if (isDistractionFree) {
      infoText = (0, import_i18n342.__)("Notes are disabled in distraction free mode.");
    } else if (block?.name === "core/freeform") {
      infoText = (0, import_i18n342.__)("Convert to blocks to add notes.");
    }
    return /* @__PURE__ */ (0, import_jsx_runtime554.jsx)(
      import_components282.MenuItem,
      {
        onClick,
        "aria-haspopup": "dialog",
        disabled: isDisabled,
        info: infoText,
        shortcut,
        children: (0, import_i18n342.__)("Add note")
      }
    );
  }
  function AddNoteMenuItem({ onClick, isDistractionFree }) {
    return /* @__PURE__ */ (0, import_jsx_runtime554.jsx)(NoteIconSlotFill.Fill, { children: ({ clientId, onClose }) => /* @__PURE__ */ (0, import_jsx_runtime554.jsx)(
      NoteMenuItem,
      {
        clientId,
        isDistractionFree,
        onClick: () => {
          onClick(clientId);
          onClose();
        }
      }
    ) });
  }

  // packages/editor/build-module/components/collab-sidebar/note-indicator-toolbar.mjs
  var import_components283 = __toESM(require_components(), 1);
  var import_i18n343 = __toESM(require_i18n(), 1);
  var import_element340 = __toESM(require_element(), 1);
  var import_block_editor104 = __toESM(require_block_editor(), 1);
  var import_data265 = __toESM(require_data(), 1);
  var import_jsx_runtime555 = __toESM(require_jsx_runtime(), 1);
  var { NoteIconToolbarSlotFill } = unlock(import_block_editor104.privateApis);
  function ThreadParticipants({ participants }) {
    const defaultAvatar = (0, import_data265.useSelect)((select9) => {
      const { getSettings: getSettings10 } = select9(import_block_editor104.store);
      const { __experimentalDiscussionSettings } = getSettings10();
      return __experimentalDiscussionSettings?.avatarURL;
    }, []);
    const maxAvatars = 3;
    const isOverflow = participants.length > maxAvatars;
    const visibleParticipants = isOverflow ? participants.slice(0, maxAvatars - 1) : participants;
    const overflowCount = Math.max(
      0,
      participants.length - visibleParticipants.length
    );
    const threadHasMoreParticipants = participants.length > 100;
    const overflowText = threadHasMoreParticipants && overflowCount > 0 ? (0, import_i18n343.__)("100+") : (0, import_i18n343.sprintf)(
      // translators: %s: Number of participants.
      (0, import_i18n343.__)("+%s"),
      overflowCount
    );
    return /* @__PURE__ */ (0, import_jsx_runtime555.jsxs)(Stack, { direction: "row", align: "center", gap: "xs", children: [
      visibleParticipants.map((participant) => /* @__PURE__ */ (0, import_jsx_runtime555.jsx)(
        "img",
        {
          src: participant.avatar || defaultAvatar,
          alt: participant.name,
          className: "editor-note-indicator__avatar",
          style: {
            borderColor: getAvatarBorderColor(participant.id)
          }
        },
        participant.id
      )),
      overflowCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime555.jsx)("span", { className: "editor-note-indicator__overflow", children: overflowText })
    ] });
  }
  function NoteAvatarIndicator({ onClick, note }) {
    const threadParticipants = (0, import_element340.useMemo)(() => {
      if (!note) {
        return [];
      }
      const participantsMap = /* @__PURE__ */ new Map();
      const allNotes = [note, ...note.reply].sort(
        (a3, b3) => new Date(a3.date) - new Date(b3.date)
      );
      for (const entry of allNotes) {
        if (!entry.author_name || participantsMap.has(entry.author)) {
          continue;
        }
        participantsMap.set(entry.author, {
          id: entry.author,
          name: entry.author_name,
          avatar: entry.author_avatar_urls?.["48"] || entry.author_avatar_urls?.["96"]
        });
      }
      return Array.from(participantsMap.values());
    }, [note]);
    if (!threadParticipants.length) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime555.jsx)(NoteIconToolbarSlotFill.Fill, { children: /* @__PURE__ */ (0, import_jsx_runtime555.jsx)(
      import_components283.ToolbarButton,
      {
        className: "editor-note-indicator",
        label: (0, import_i18n343.__)("View notes"),
        onClick: () => onClick(),
        showTooltip: true,
        children: /* @__PURE__ */ (0, import_jsx_runtime555.jsx)(ThreadParticipants, { participants: threadParticipants })
      }
    ) });
  }

  // packages/editor/build-module/components/collab-sidebar/note-highlight-styles.mjs
  var import_element341 = __toESM(require_element(), 1);
  var import_block_editor105 = __toESM(require_block_editor(), 1);
  var REST_ALPHA = "40";
  var ACTIVE_ALPHA = "80";
  var BASE_RESET = "mark.wp-note{background-color:transparent;color:inherit;}";
  function buildHighlightCss(threads, selectedId = null) {
    const rules = [BASE_RESET];
    for (const thread of threads ?? []) {
      if (!thread?.id) {
        continue;
      }
      const color = getAvatarBorderColor(thread.author ?? 0);
      const sel = getNoteMarkerSelector(thread.id);
      rules.push(`${sel}{background-color:${color}${REST_ALPHA};}`);
      rules.push(
        `${sel}:hover,${sel}:focus-within{background-color:${color}${ACTIVE_ALPHA};}`
      );
      if (selectedId && String(selectedId) === String(thread.id)) {
        rules.push(
          `${sel}{background-color:${color}${ACTIVE_ALPHA};}`
        );
      }
    }
    return rules.join("");
  }
  function NoteHighlightStyles({ threads, selectedId }) {
    const css = (0, import_element341.useMemo)(
      () => buildHighlightCss(threads, selectedId),
      [threads, selectedId]
    );
    (0, import_block_editor105.useStyleOverride)({ id: "core-note-highlights", css });
    return null;
  }

  // packages/editor/build-module/components/collab-sidebar/index.mjs
  var import_jsx_runtime556 = __toESM(require_jsx_runtime(), 1);
  function NotesSidebar({ postId: postId2 }) {
    const { getActiveComplementaryArea: getActiveComplementaryArea2 } = (0, import_data266.useSelect)(store3);
    const { enableComplementaryArea: enableComplementaryArea2 } = (0, import_data266.useDispatch)(store3);
    const { toggleBlockSpotlight, selectBlock: selectBlock2 } = unlock(
      (0, import_data266.useDispatch)(import_block_editor106.store)
    );
    const { selectNote: selectNote2 } = unlock((0, import_data266.useDispatch)(store));
    const isLargeViewport = (0, import_compose84.useViewportMatch)("medium");
    const sidebarRef = (0, import_element342.useRef)(null);
    const { clientId, noteId, isClassicBlock } = (0, import_data266.useSelect)((select9) => {
      const { getBlockAttributes: getBlockAttributes2, getSelectedBlockClientId: getSelectedBlockClientId2, getBlockName: getBlockName2 } = select9(import_block_editor106.store);
      const _clientId = getSelectedBlockClientId2();
      return {
        clientId: _clientId,
        noteId: _clientId ? getBlockAttributes2(_clientId)?.metadata?.noteId : null,
        isClassicBlock: _clientId ? getBlockName2(_clientId) === "core/freeform" : false
      };
    }, []);
    const blockNoteIds = getNoteIdsFromMetadata({ noteId });
    const { isDistractionFree } = (0, import_data266.useSelect)((select9) => {
      const { get } = select9(import_preferences30.store);
      return {
        isDistractionFree: get("core", "distractionFree")
      };
    }, []);
    const selectedNoteId = (0, import_data266.useSelect)(
      (select9) => unlock(select9(store)).getSelectedNote(),
      []
    );
    const { notes, unresolvedNotes } = useNoteThreads(postId2);
    const showFloatingSidebar = isLargeViewport;
    const showAllNotesSidebar = notes.length > 0 || !showFloatingSidebar;
    useEnableFloatingSidebar(
      showFloatingSidebar && (unresolvedNotes.length > 0 || selectedNoteId !== void 0)
    );
    async function focusNote({
      targetClientId,
      noteId: targetNoteId,
      isApproved
    }) {
      if (!targetClientId) {
        return;
      }
      const prevArea = await getActiveComplementaryArea2("core");
      if (isApproved) {
        enableComplementaryArea2("core", ALL_NOTES_SIDEBAR);
      } else if (!SIDEBARS.includes(prevArea) || !showAllNotesSidebar) {
        enableComplementaryArea2(
          "core",
          showFloatingSidebar ? FLOATING_NOTES_SIDEBAR : ALL_NOTES_SIDEBAR
        );
      }
      const currentArea = await getActiveComplementaryArea2("core");
      if (!SIDEBARS.includes(currentArea)) {
        return;
      }
      selectBlock2(targetClientId, null);
      toggleBlockSpotlight(targetClientId, true);
      selectNote2(targetNoteId, { focus: true });
    }
    function openNoteForBlock(targetClientId) {
      const blockThreads = notes.filter(
        (thread) => thread.blockClientId === targetClientId
      );
      const target = pickPrimaryNote(blockThreads);
      return focusNote({
        targetClientId,
        noteId: target?.id ?? "new",
        isApproved: target?.status === "approved"
      });
    }
    function addNewNoteForBlock(targetClientId) {
      return focusNote({
        targetClientId,
        noteId: "new",
        isApproved: false
      });
    }
    (0, import_keyboard_shortcuts13.useShortcut)(
      "core/editor/new-note",
      (event) => {
        event.preventDefault();
        addNewNoteForBlock(clientId);
      },
      {
        isDisabled: isDistractionFree || isClassicBlock || !clientId
      }
    );
    const { merged: GlobalStyles } = useGlobalStyles();
    const backgroundColor = GlobalStyles?.styles?.color?.background;
    const currentThreads = blockNoteIds.length > 0 ? notes.filter((thread) => blockNoteIds.includes(thread.id)) : [];
    const currentThread = pickPrimaryNote(currentThreads);
    if (isDistractionFree) {
      return /* @__PURE__ */ (0, import_jsx_runtime556.jsx)(AddNoteMenuItem, { isDistractionFree: true });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime556.jsxs)(import_jsx_runtime556.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime556.jsx)(
        NoteHighlightStyles,
        {
          threads: unresolvedNotes,
          selectedId: selectedNoteId
        }
      ),
      !!currentThread && /* @__PURE__ */ (0, import_jsx_runtime556.jsx)(
        NoteAvatarIndicator,
        {
          note: currentThread,
          onClick: () => openNoteForBlock(clientId)
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime556.jsx)(
        AddNoteMenuItem,
        {
          onClick: (menuClientId) => addNewNoteForBlock(menuClientId)
        }
      ),
      showAllNotesSidebar && /* @__PURE__ */ (0, import_jsx_runtime556.jsx)(
        PluginSidebar,
        {
          identifier: ALL_NOTES_SIDEBAR,
          name: ALL_NOTES_SIDEBAR,
          title: (0, import_i18n344.__)("All notes"),
          header: /* @__PURE__ */ (0, import_jsx_runtime556.jsx)("h2", { className: "interface-complementary-area-header__title", children: (0, import_i18n344.__)("All notes") }),
          icon: comment_default,
          closeLabel: (0, import_i18n344.__)("Close Notes"),
          children: /* @__PURE__ */ (0, import_jsx_runtime556.jsx)(Notes, { notes, sidebarRef })
        }
      ),
      isLargeViewport && /* @__PURE__ */ (0, import_jsx_runtime556.jsx)(
        PluginSidebar,
        {
          isPinnable: false,
          header: false,
          identifier: FLOATING_NOTES_SIDEBAR,
          className: "editor-collab-sidebar",
          headerClassName: "editor-collab-sidebar__header",
          backgroundColor,
          children: /* @__PURE__ */ (0, import_jsx_runtime556.jsx)(
            Notes,
            {
              notes: unresolvedNotes,
              sidebarRef,
              styles: { backgroundColor },
              isFloating: true
            }
          )
        }
      )
    ] });
  }
  function NotesSidebarContainer() {
    const { postId: postId2, editorMode, revisionsMode } = (0, import_data266.useSelect)((select9) => {
      const { getCurrentPostId: getCurrentPostId2, getEditorMode: getEditorMode2, isRevisionsMode: isRevisionsMode2 } = unlock(
        select9(store)
      );
      return {
        postId: getCurrentPostId2(),
        editorMode: getEditorMode2(),
        revisionsMode: isRevisionsMode2()
      };
    }, []);
    if (!postId2 || typeof postId2 !== "number") {
      return null;
    }
    if (editorMode === "text" || revisionsMode) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime556.jsx)(post_type_support_check_default, { supportKeys: "editor.notes", children: /* @__PURE__ */ (0, import_jsx_runtime556.jsx)(NotesSidebar, { postId: postId2 }) });
  }

  // packages/editor/build-module/components/global-styles-sidebar/index.mjs
  var import_components286 = __toESM(require_components(), 1);
  var import_i18n347 = __toESM(require_i18n(), 1);
  var import_data269 = __toESM(require_data(), 1);
  var import_element343 = __toESM(require_element(), 1);
  var import_preferences33 = __toESM(require_preferences(), 1);
  var import_compose85 = __toESM(require_compose(), 1);
  var import_core_data141 = __toESM(require_core_data(), 1);
  var import_block_editor107 = __toESM(require_block_editor(), 1);

  // packages/editor/build-module/components/global-styles/menu.mjs
  var import_components284 = __toESM(require_components(), 1);
  var import_data267 = __toESM(require_data(), 1);
  var import_i18n345 = __toESM(require_i18n(), 1);
  var import_preferences31 = __toESM(require_preferences(), 1);
  var import_core_data140 = __toESM(require_core_data(), 1);
  var import_jsx_runtime557 = __toESM(require_jsx_runtime(), 1);
  function GlobalStylesActionMenu({
    hideWelcomeGuide = false,
    onChangePath
  }) {
    const { user, setUser } = useGlobalStyles();
    const canReset = !!user && (Object.keys(user?.styles ?? {}).length > 0 || Object.keys(user?.settings ?? {}).length > 0);
    const onReset = () => {
      setUser({ styles: {}, settings: {} });
    };
    const { toggle } = (0, import_data267.useDispatch)(import_preferences31.store);
    const { canEditCSS } = (0, import_data267.useSelect)((select9) => {
      const { getEntityRecord, __experimentalGetCurrentGlobalStylesId } = select9(import_core_data140.store);
      const globalStylesId = __experimentalGetCurrentGlobalStylesId();
      const globalStyles = globalStylesId ? getEntityRecord("root", "globalStyles", globalStylesId) : void 0;
      return {
        canEditCSS: !!globalStyles?._links?.["wp:action-edit-css"]
      };
    }, []);
    const loadCustomCSS = () => {
      onChangePath("/css");
    };
    return /* @__PURE__ */ (0, import_jsx_runtime557.jsx)(
      import_components284.DropdownMenu,
      {
        icon: more_vertical_default,
        label: (0, import_i18n345.__)("More"),
        toggleProps: { size: "compact" },
        children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime557.jsxs)(import_jsx_runtime557.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime557.jsxs)(import_components284.MenuGroup, { children: [
            canEditCSS && /* @__PURE__ */ (0, import_jsx_runtime557.jsx)(import_components284.MenuItem, { onClick: loadCustomCSS, children: (0, import_i18n345.__)("Additional CSS") }),
            !hideWelcomeGuide && /* @__PURE__ */ (0, import_jsx_runtime557.jsx)(
              import_components284.MenuItem,
              {
                onClick: () => {
                  toggle(
                    "core/edit-site",
                    "welcomeGuideStyles"
                  );
                  onClose();
                },
                children: (0, import_i18n345.__)("Welcome Guide")
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime557.jsx)(import_components284.MenuGroup, { children: /* @__PURE__ */ (0, import_jsx_runtime557.jsx)(
            import_components284.MenuItem,
            {
              onClick: () => {
                onReset();
                onClose();
              },
              disabled: !canReset,
              children: (0, import_i18n345.__)("Reset styles")
            }
          ) })
        ] })
      }
    );
  }

  // packages/editor/build-module/components/global-styles-sidebar/default-sidebar.mjs
  var import_jsx_runtime558 = __toESM(require_jsx_runtime(), 1);
  function DefaultSidebar({
    className,
    identifier,
    title,
    icon,
    children,
    closeLabel,
    header,
    headerClassName,
    panelClassName,
    isActiveByDefault
  }) {
    return /* @__PURE__ */ (0, import_jsx_runtime558.jsxs)(import_jsx_runtime558.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime558.jsx)(
        complementary_area_default,
        {
          className,
          scope: "core",
          identifier,
          title,
          icon,
          closeLabel,
          header,
          headerClassName,
          panelClassName,
          isActiveByDefault,
          children
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime558.jsx)(
        ComplementaryAreaMoreMenuItem,
        {
          scope: "core",
          identifier,
          icon,
          children: title
        }
      )
    ] });
  }

  // packages/editor/build-module/components/global-styles-sidebar/welcome-guide.mjs
  var import_data268 = __toESM(require_data(), 1);
  var import_components285 = __toESM(require_components(), 1);
  var import_i18n346 = __toESM(require_i18n(), 1);
  var import_preferences32 = __toESM(require_preferences(), 1);

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

  // packages/editor/build-module/components/global-styles-sidebar/welcome-guide.mjs
  var import_jsx_runtime560 = __toESM(require_jsx_runtime(), 1);
  function WelcomeGuideStyles() {
    const { toggle } = (0, import_data268.useDispatch)(import_preferences32.store);
    const { isActive, isStylesOpen } = (0, import_data268.useSelect)((select9) => {
      const sidebar = select9(store3).getActiveComplementaryArea("core");
      return {
        isActive: !!select9(import_preferences32.store).get(
          "core/edit-site",
          "welcomeGuideStyles"
        ),
        isStylesOpen: sidebar === "edit-site/global-styles"
      };
    }, []);
    if (!isActive || !isStylesOpen) {
      return null;
    }
    const welcomeLabel = (0, import_i18n346.__)("Welcome to Styles");
    return /* @__PURE__ */ (0, import_jsx_runtime560.jsx)(
      import_components285.Guide,
      {
        className: "editor-welcome-guide guide-styles",
        contentLabel: welcomeLabel,
        finishButtonText: (0, import_i18n346.__)("Get started"),
        onFinish: () => toggle("core/edit-site", "welcomeGuideStyles"),
        pages: [
          {
            image: /* @__PURE__ */ (0, import_jsx_runtime560.jsx)(
              WelcomeGuideImage,
              {
                nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-to-styles.svg?1",
                animatedSrc: "https://s.w.org/images/block-editor/welcome-to-styles.gif?1"
              }
            ),
            content: /* @__PURE__ */ (0, import_jsx_runtime560.jsxs)(import_jsx_runtime560.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime560.jsx)("h1", { className: "editor-welcome-guide__heading", children: welcomeLabel }),
              /* @__PURE__ */ (0, import_jsx_runtime560.jsx)("p", { className: "editor-welcome-guide__text", children: (0, import_i18n346.__)(
                "Tweak your site, or give it a whole new look! Get creative \u2014 how about a new color palette for your buttons, or choosing a new font? Take a look at what you can do here."
              ) })
            ] })
          },
          {
            image: /* @__PURE__ */ (0, import_jsx_runtime560.jsx)(
              WelcomeGuideImage,
              {
                nonAnimatedSrc: "https://s.w.org/images/block-editor/set-the-design.svg?1",
                animatedSrc: "https://s.w.org/images/block-editor/set-the-design.gif?1"
              }
            ),
            content: /* @__PURE__ */ (0, import_jsx_runtime560.jsxs)(import_jsx_runtime560.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime560.jsx)("h1", { className: "editor-welcome-guide__heading", children: (0, import_i18n346.__)("Set the design") }),
              /* @__PURE__ */ (0, import_jsx_runtime560.jsx)("p", { className: "editor-welcome-guide__text", children: (0, import_i18n346.__)(
                "You can customize your site as much as you like with different colors, typography, and layouts. Or if you prefer, just leave it up to your theme to handle!"
              ) })
            ] })
          },
          {
            image: /* @__PURE__ */ (0, import_jsx_runtime560.jsx)(
              WelcomeGuideImage,
              {
                nonAnimatedSrc: "https://s.w.org/images/block-editor/personalize-blocks.svg?1",
                animatedSrc: "https://s.w.org/images/block-editor/personalize-blocks.gif?1"
              }
            ),
            content: /* @__PURE__ */ (0, import_jsx_runtime560.jsxs)(import_jsx_runtime560.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime560.jsx)("h1", { className: "editor-welcome-guide__heading", children: (0, import_i18n346.__)("Personalize blocks") }),
              /* @__PURE__ */ (0, import_jsx_runtime560.jsx)("p", { className: "editor-welcome-guide__text", children: (0, import_i18n346.__)(
                "You can adjust your blocks to ensure a cohesive experience across your site \u2014 add your unique colors to a branded Button block, or adjust the Heading block to your preferred size."
              ) })
            ] })
          },
          {
            image: /* @__PURE__ */ (0, import_jsx_runtime560.jsx)(
              WelcomeGuideImage,
              {
                nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-documentation.svg",
                animatedSrc: "https://s.w.org/images/block-editor/welcome-documentation.gif"
              }
            ),
            content: /* @__PURE__ */ (0, import_jsx_runtime560.jsxs)(import_jsx_runtime560.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime560.jsx)("h1", { className: "editor-welcome-guide__heading", children: (0, import_i18n346.__)("Learn more") }),
              /* @__PURE__ */ (0, import_jsx_runtime560.jsxs)("p", { className: "editor-welcome-guide__text", children: [
                (0, import_i18n346.__)(
                  "New to block themes and styling your site?"
                ),
                " ",
                /* @__PURE__ */ (0, import_jsx_runtime560.jsx)(
                  import_components285.ExternalLink,
                  {
                    href: (0, import_i18n346.__)(
                      "https://wordpress.org/documentation/article/styles-overview/"
                    ),
                    children: (0, import_i18n346.__)(
                      "Here\u2019s a detailed guide to learn how to make the most of it."
                    )
                  }
                )
              ] })
            ] })
          }
        ]
      }
    );
  }

  // packages/editor/build-module/components/global-styles-sidebar/index.mjs
  var import_jsx_runtime561 = __toESM(require_jsx_runtime(), 1);
  function GlobalStylesSidebar() {
    const {
      shouldResetNavigation,
      stylesPath: stylesPath2,
      showStylebook: showStylebook2,
      showListViewByDefault,
      hasRevisions,
      activeComplementaryArea,
      editorSettings: editorSettings2,
      styleStateViewport
    } = (0, import_data269.useSelect)((select9) => {
      const { getActiveComplementaryArea: getActiveComplementaryArea2 } = select9(store3);
      const { getStylesPath: getStylesPath2, getShowStylebook: getShowStylebook2 } = unlock(
        select9(store)
      );
      const _isVisualEditorMode = "visual" === select9(store).getEditorMode();
      const _showListViewByDefault = select9(import_preferences33.store).get(
        "core",
        "showListViewByDefault"
      );
      const { getEntityRecord, __experimentalGetCurrentGlobalStylesId } = select9(import_core_data141.store);
      const globalStylesId = __experimentalGetCurrentGlobalStylesId();
      const globalStyles = globalStylesId ? getEntityRecord("root", "globalStyles", globalStylesId) : void 0;
      return {
        stylesPath: getStylesPath2(),
        showStylebook: getShowStylebook2(),
        shouldResetNavigation: "edit-site/global-styles" !== getActiveComplementaryArea2("core") || !_isVisualEditorMode,
        showListViewByDefault: _showListViewByDefault,
        hasRevisions: !!globalStyles?._links?.["version-history"]?.[0]?.count,
        activeComplementaryArea: select9(store3).getActiveComplementaryArea("core"),
        editorSettings: select9(store).getEditorSettings(),
        styleStateViewport: unlock(
          select9(import_block_editor107.store)
        ).getStyleStateViewport()
      };
    }, []);
    const { setStylesPath: setStylesPath2, setShowStylebook: setShowStylebook2, resetStylesNavigation: resetStylesNavigation2 } = unlock(
      (0, import_data269.useDispatch)(store)
    );
    const isMobileViewport = (0, import_compose85.useViewportMatch)("medium", "<");
    const isRevisionsOpened = stylesPath2.startsWith("/revisions") && !showStylebook2;
    const isRevisionsStyleBookOpened = stylesPath2.startsWith("/revisions") && showStylebook2;
    const previousActiveArea = (0, import_compose85.usePrevious)(activeComplementaryArea);
    (0, import_element343.useEffect)(() => {
      if (activeComplementaryArea === "edit-site/global-styles" && previousActiveArea !== "edit-site/global-styles") {
        resetStylesNavigation2();
      }
    }, [activeComplementaryArea, previousActiveArea, resetStylesNavigation2]);
    (0, import_element343.useEffect)(() => {
      if (shouldResetNavigation) {
        resetStylesNavigation2();
      }
    }, [shouldResetNavigation, resetStylesNavigation2]);
    const { setIsListViewOpened: setIsListViewOpened2 } = (0, import_data269.useDispatch)(store);
    const toggleRevisions = () => {
      setIsListViewOpened2(false);
      if (isRevisionsOpened || isRevisionsStyleBookOpened) {
        setStylesPath2("/");
      } else {
        setStylesPath2("/revisions");
      }
    };
    const toggleStyleBook = () => {
      setIsListViewOpened2(showStylebook2 && showListViewByDefault);
      setShowStylebook2(!showStylebook2);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime561.jsxs)(import_jsx_runtime561.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime561.jsx)(
        DefaultSidebar,
        {
          className: "editor-global-styles-sidebar",
          identifier: "edit-site/global-styles",
          title: (0, import_i18n347.__)("Styles"),
          icon: styles_default,
          closeLabel: (0, import_i18n347.__)("Close Styles"),
          panelClassName: "editor-global-styles-sidebar__panel",
          header: /* @__PURE__ */ (0, import_jsx_runtime561.jsxs)(
            import_components286.Flex,
            {
              className: "editor-global-styles-sidebar__header",
              gap: 1,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime561.jsx)(import_components286.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime561.jsx)("h2", { className: "editor-global-styles-sidebar__header-title", children: (0, import_i18n347.__)("Styles") }) }),
                /* @__PURE__ */ (0, import_jsx_runtime561.jsxs)(
                  import_components286.Flex,
                  {
                    justify: "flex-end",
                    gap: 1,
                    className: "editor-global-styles-sidebar__header-actions",
                    children: [
                      !isMobileViewport && /* @__PURE__ */ (0, import_jsx_runtime561.jsx)(import_components286.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime561.jsx)(
                        import_components286.Button,
                        {
                          icon: seen_default,
                          label: (0, import_i18n347.__)("Style Book"),
                          isPressed: showStylebook2,
                          accessibleWhenDisabled: true,
                          disabled: shouldResetNavigation,
                          onClick: toggleStyleBook,
                          size: "compact"
                        }
                      ) }),
                      /* @__PURE__ */ (0, import_jsx_runtime561.jsx)(import_components286.FlexItem, { children: /* @__PURE__ */ (0, import_jsx_runtime561.jsx)(
                        import_components286.Button,
                        {
                          label: (0, import_i18n347.__)("Revisions"),
                          icon: backup_default,
                          onClick: toggleRevisions,
                          accessibleWhenDisabled: true,
                          disabled: !hasRevisions,
                          isPressed: isRevisionsOpened || isRevisionsStyleBookOpened,
                          size: "compact"
                        }
                      ) }),
                      /* @__PURE__ */ (0, import_jsx_runtime561.jsx)(
                        GlobalStylesActionMenu,
                        {
                          onChangePath: setStylesPath2
                        }
                      )
                    ]
                  }
                )
              ]
            }
          ),
          children: /* @__PURE__ */ (0, import_jsx_runtime561.jsx)(
            GlobalStylesUIWrapper,
            {
              path: stylesPath2,
              onPathChange: setStylesPath2,
              settings: editorSettings2,
              selectedViewport: styleStateViewport,
              showResponsiveStateControls: false
            }
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime561.jsx)(WelcomeGuideStyles, {})
    ] });
  }

  // packages/editor/build-module/components/editor/index.mjs
  var import_jsx_runtime562 = __toESM(require_jsx_runtime(), 1);
  function Editor({
    postType: postType2,
    postId: postId2,
    templateId: templateId2,
    settings,
    children,
    initialEdits,
    // This could be part of the settings.
    onActionPerformed,
    // The following abstractions are not ideal but necessary
    // to account for site editor and post editor differences for now.
    extraContent,
    extraSidebarPanels,
    ...props
  }) {
    const {
      post: post2,
      template: template2,
      hasLoadedPost,
      error: error2,
      isBlockTheme,
      showGlobalStyles
    } = (0, import_data270.useSelect)(
      (select9) => {
        const {
          getEntityRecord,
          getResolutionError,
          hasFinishedResolution,
          getCurrentTheme,
          __experimentalGetCurrentGlobalStylesId,
          canUser
        } = select9(import_core_data142.store);
        const { getRenderingMode: getRenderingMode2, getCurrentPostType: getCurrentPostType2 } = select9(store);
        const postArgs = ["postType", postType2, postId2];
        const renderingMode2 = getRenderingMode2();
        const currentPostType = getCurrentPostType2();
        const _isBlockTheme = getCurrentTheme()?.is_block_theme;
        const globalStylesId = __experimentalGetCurrentGlobalStylesId();
        const userCanEditGlobalStyles = globalStylesId ? canUser("update", {
          kind: "root",
          name: "globalStyles",
          id: globalStylesId
        }) : false;
        return {
          post: getEntityRecord(...postArgs),
          template: templateId2 ? getEntityRecord(
            "postType",
            TEMPLATE_POST_TYPE,
            templateId2
          ) : void 0,
          hasLoadedPost: hasFinishedResolution(
            "getEntityRecord",
            postArgs
          ),
          error: getResolutionError("getEntityRecord", postArgs)?.message,
          isBlockTheme: _isBlockTheme,
          showGlobalStyles: _isBlockTheme && userCanEditGlobalStyles && (currentPostType === "wp_template" || renderingMode2 === "template-locked")
        };
      },
      [postType2, postId2, templateId2]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime562.jsxs)(import_jsx_runtime562.Fragment, { children: [
      hasLoadedPost && !post2 && /* @__PURE__ */ (0, import_jsx_runtime562.jsx)(
        import_components287.Notice,
        {
          status: !!error2 ? "error" : "warning",
          isDismissible: false,
          children: !error2 ? (0, import_i18n348.__)(
            "You attempted to edit an item that doesn't exist. Perhaps it was deleted?"
          ) : error2
        }
      ),
      !!post2 && /* @__PURE__ */ (0, import_jsx_runtime562.jsxs)(
        ExperimentalEditorProvider,
        {
          post: post2,
          __unstableTemplate: template2,
          settings,
          initialEdits,
          useSubRegistry: false,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime562.jsx)(EditorInterface, { ...props, children: extraContent }),
            children,
            /* @__PURE__ */ (0, import_jsx_runtime562.jsx)(
              sidebar_default2,
              {
                onActionPerformed,
                extraPanels: extraSidebarPanels
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime562.jsx)(NotesSidebarContainer, {}),
            isBlockTheme && /* @__PURE__ */ (0, import_jsx_runtime562.jsx)(GlobalStylesRenderer, {}),
            showGlobalStyles && /* @__PURE__ */ (0, import_jsx_runtime562.jsx)(GlobalStylesSidebar, {})
          ]
        }
      )
    ] });
  }
  var editor_default = Editor;

  // packages/editor/build-module/components/preferences-modal/index.mjs
  var import_i18n350 = __toESM(require_i18n(), 1);
  var import_compose86 = __toESM(require_compose(), 1);
  var import_data273 = __toESM(require_data(), 1);
  var import_element345 = __toESM(require_element(), 1);
  var import_preferences36 = __toESM(require_preferences(), 1);

  // packages/editor/build-module/components/preferences-modal/enable-publish-sidebar.mjs
  var import_data271 = __toESM(require_data(), 1);
  var import_preferences34 = __toESM(require_preferences(), 1);
  var import_jsx_runtime563 = __toESM(require_jsx_runtime(), 1);
  var { PreferenceBaseOption: PreferenceBaseOption2 } = unlock(import_preferences34.privateApis);
  function EnablePublishSidebarOption(props) {
    const isChecked = (0, import_data271.useSelect)((select9) => {
      return select9(store).isPublishSidebarEnabled();
    }, []);
    const { enablePublishSidebar: enablePublishSidebar2, disablePublishSidebar: disablePublishSidebar2 } = (0, import_data271.useDispatch)(store);
    return /* @__PURE__ */ (0, import_jsx_runtime563.jsx)(
      PreferenceBaseOption2,
      {
        isChecked,
        onChange: (isEnabled) => isEnabled ? enablePublishSidebar2() : disablePublishSidebar2(),
        ...props
      }
    );
  }

  // packages/editor/build-module/components/block-visibility/index.mjs
  var import_data272 = __toESM(require_data(), 1);
  var import_preferences35 = __toESM(require_preferences(), 1);
  var import_blocks39 = __toESM(require_blocks(), 1);
  var import_element344 = __toESM(require_element(), 1);
  var import_components288 = __toESM(require_components(), 1);
  var import_i18n349 = __toESM(require_i18n(), 1);
  var import_block_editor108 = __toESM(require_block_editor(), 1);
  var import_jsx_runtime564 = __toESM(require_jsx_runtime(), 1);
  var { BlockManager } = unlock(import_block_editor108.privateApis);
  var EMPTY_ARRAY17 = [];
  function BlockVisibility() {
    const { showBlockTypes: showBlockTypes2, hideBlockTypes: hideBlockTypes2 } = unlock(
      (0, import_data272.useDispatch)(store)
    );
    const {
      blockTypes,
      allowedBlockTypes: _allowedBlockTypes,
      hiddenBlockTypes: _hiddenBlockTypes
    } = (0, import_data272.useSelect)((select9) => {
      return {
        blockTypes: select9(import_blocks39.store).getBlockTypes(),
        allowedBlockTypes: select9(store).getEditorSettings().allowedBlockTypes,
        hiddenBlockTypes: select9(import_preferences35.store).get("core", "hiddenBlockTypes") ?? EMPTY_ARRAY17
      };
    }, []);
    const allowedBlockTypes = (0, import_element344.useMemo)(() => {
      if (_allowedBlockTypes === true) {
        return blockTypes;
      }
      return blockTypes.filter(({ name: name2 }) => {
        return _allowedBlockTypes?.includes(name2);
      });
    }, [_allowedBlockTypes, blockTypes]);
    const filteredBlockTypes = allowedBlockTypes.filter(
      (blockType) => (0, import_blocks39.hasBlockSupport)(blockType, "inserter", true) && (!blockType.parent || blockType.parent.includes("core/post-content"))
    );
    const hiddenBlockTypes = _hiddenBlockTypes.filter((hiddenBlock) => {
      return filteredBlockTypes.some(
        (registeredBlock) => registeredBlock.name === hiddenBlock
      );
    });
    const selectedBlockTypes = filteredBlockTypes.filter(
      (blockType) => !hiddenBlockTypes.includes(blockType.name)
    );
    const numberOfHiddenBlocks = filteredBlockTypes.length - selectedBlockTypes.length;
    function enableAllBlockTypes() {
      onChangeSelectedBlockTypes(filteredBlockTypes);
    }
    const onChangeSelectedBlockTypes = (newSelectedBlockTypes) => {
      if (selectedBlockTypes.length > newSelectedBlockTypes.length) {
        const blockTypesToHide = selectedBlockTypes.filter(
          (blockType) => !newSelectedBlockTypes.find(
            ({ name: name2 }) => name2 === blockType.name
          )
        );
        hideBlockTypes2(blockTypesToHide.map(({ name: name2 }) => name2));
      } else if (selectedBlockTypes.length < newSelectedBlockTypes.length) {
        const blockTypesToShow = newSelectedBlockTypes.filter(
          (blockType) => !selectedBlockTypes.find(
            ({ name: name2 }) => name2 === blockType.name
          )
        );
        showBlockTypes2(blockTypesToShow.map(({ name: name2 }) => name2));
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime564.jsxs)("div", { className: "editor-block-visibility", children: [
      !!numberOfHiddenBlocks && /* @__PURE__ */ (0, import_jsx_runtime564.jsxs)("div", { className: "editor-block-visibility__disabled-blocks-count", children: [
        (0, import_i18n349.sprintf)(
          /* translators: %d: number of blocks. */
          (0, import_i18n349._n)(
            "%d block is hidden.",
            "%d blocks are hidden.",
            numberOfHiddenBlocks
          ),
          numberOfHiddenBlocks
        ),
        /* @__PURE__ */ (0, import_jsx_runtime564.jsx)(
          import_components288.Button,
          {
            __next40pxDefaultSize: true,
            variant: "link",
            onClick: enableAllBlockTypes,
            children: (0, import_i18n349.__)("Reset")
          }
        )
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime564.jsx)(
        BlockManager,
        {
          blockTypes: filteredBlockTypes,
          selectedBlockTypes,
          onChange: onChangeSelectedBlockTypes,
          showSelectAll: false
        }
      )
    ] });
  }

  // packages/editor/build-module/components/preferences-modal/index.mjs
  var import_jsx_runtime565 = __toESM(require_jsx_runtime(), 1);
  var {
    PreferencesModal,
    PreferencesModalTabs,
    PreferencesModalSection,
    PreferenceToggleControl
  } = unlock(import_preferences36.privateApis);
  function EditorPreferencesModal({ extraSections = {} }) {
    const isActive = (0, import_data273.useSelect)((select9) => {
      return select9(store3).isModalActive("editor/preferences");
    }, []);
    const { closeModal: closeModal2 } = (0, import_data273.useDispatch)(store3);
    if (!isActive) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(PreferencesModal, { closeModal: closeModal2, children: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(PreferencesModalContents, { extraSections }) });
  }
  function PreferencesModalContents({ extraSections = {} }) {
    const isLargeViewport = (0, import_compose86.useViewportMatch)("medium");
    const { showBlockBreadcrumbsOption, showCollaborationOptions } = (0, import_data273.useSelect)(
      (select9) => {
        const { getEditorSettings: getEditorSettings2, isCollaborationEnabledForCurrentPost: isCollaborationEnabledForCurrentPost2 } = unlock(select9(store));
        const { get } = select9(import_preferences36.store);
        const isRichEditingEnabled = getEditorSettings2().richEditingEnabled;
        const isDistractionFreeEnabled = get("core", "distractionFree");
        return {
          showBlockBreadcrumbsOption: !isDistractionFreeEnabled && isLargeViewport && isRichEditingEnabled,
          showCollaborationOptions: isCollaborationEnabledForCurrentPost2()
        };
      },
      [isLargeViewport]
    );
    const { setIsListViewOpened: setIsListViewOpened2, setIsInserterOpened: setIsInserterOpened2 } = (0, import_data273.useDispatch)(store);
    const { set: setPreference } = (0, import_data273.useDispatch)(import_preferences36.store);
    const sections = (0, import_element345.useMemo)(
      () => [
        {
          name: "general",
          tabLabel: (0, import_i18n350.__)("General"),
          content: /* @__PURE__ */ (0, import_jsx_runtime565.jsxs)(import_jsx_runtime565.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime565.jsxs)(
              PreferencesModalSection,
              {
                title: (0, import_i18n350.__)("Interface"),
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    PreferenceToggleControl,
                    {
                      scope: "core",
                      featureName: "showListViewByDefault",
                      help: (0, import_i18n350.__)(
                        "Opens the List View panel by default."
                      ),
                      label: (0, import_i18n350.__)("Always open List View")
                    }
                  ),
                  showBlockBreadcrumbsOption && /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    PreferenceToggleControl,
                    {
                      scope: "core",
                      featureName: "showBlockBreadcrumbs",
                      help: (0, import_i18n350.__)(
                        "Display the block hierarchy trail at the bottom of the editor."
                      ),
                      label: (0, import_i18n350.__)("Show block breadcrumbs")
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    PreferenceToggleControl,
                    {
                      scope: "core",
                      featureName: "allowRightClickOverrides",
                      help: (0, import_i18n350.__)(
                        "Allows contextual List View menus via right-click, overriding browser defaults."
                      ),
                      label: (0, import_i18n350.__)(
                        "Allow right-click contextual menus"
                      )
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    PreferenceToggleControl,
                    {
                      scope: "core",
                      featureName: "enableChoosePatternModal",
                      help: (0, import_i18n350.__)(
                        "Pick from starter content when creating a new page."
                      ),
                      label: (0, import_i18n350.__)("Show starter patterns")
                    }
                  ),
                  showCollaborationOptions && /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    PreferenceToggleControl,
                    {
                      scope: "core",
                      featureName: "showCollaborationCursor",
                      help: (0, import_i18n350.__)(
                        "Show your own avatar inside blocks during collaborative editing sessions."
                      ),
                      label: (0, import_i18n350.__)("Show avatar in blocks")
                    }
                  )
                ]
              }
            ),
            showCollaborationOptions && /* @__PURE__ */ (0, import_jsx_runtime565.jsxs)(
              PreferencesModalSection,
              {
                title: (0, import_i18n350.__)(
                  "Collaboration notifications"
                ),
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    PreferenceToggleControl,
                    {
                      scope: "core",
                      featureName: "showCollaborationJoinNotifications",
                      help: (0, import_i18n350.__)(
                        "Show notifications when collaborators join the post."
                      ),
                      label: (0, import_i18n350.__)("Collaborator joined")
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    PreferenceToggleControl,
                    {
                      scope: "core",
                      featureName: "showCollaborationLeaveNotifications",
                      help: (0, import_i18n350.__)(
                        "Show notifications when collaborators leave the post."
                      ),
                      label: (0, import_i18n350.__)("Collaborator left")
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    PreferenceToggleControl,
                    {
                      scope: "core",
                      featureName: "showCollaborationPostSaveNotifications",
                      help: (0, import_i18n350.__)(
                        "Show notifications when collaborators save, update, or publish the post."
                      ),
                      label: (0, import_i18n350.__)("Post updated")
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime565.jsxs)(
              PreferencesModalSection,
              {
                title: (0, import_i18n350.__)("Document settings"),
                description: (0, import_i18n350.__)(
                  "Select what settings are shown in the document panel."
                ),
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(enable_plugin_document_setting_panel_default.Slot, {}),
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    post_taxonomies_default,
                    {
                      taxonomyWrapper: (content, taxonomy) => /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                        EnablePanelOption,
                        {
                          label: taxonomy.labels.menu_name,
                          panelName: `taxonomy-panel-${taxonomy.slug}`
                        }
                      )
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(check_default4, { children: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    EnablePanelOption,
                    {
                      label: (0, import_i18n350.__)("Featured image"),
                      panelName: "featured-image"
                    }
                  ) }),
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(check_default3, { children: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    EnablePanelOption,
                    {
                      label: (0, import_i18n350.__)("Excerpt"),
                      panelName: "post-excerpt"
                    }
                  ) }),
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    post_type_support_check_default,
                    {
                      supportKeys: ["comments", "trackbacks"],
                      children: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                        EnablePanelOption,
                        {
                          label: (0, import_i18n350.__)("Discussion"),
                          panelName: "discussion-panel"
                        }
                      )
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(check_default2, { children: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                    EnablePanelOption,
                    {
                      label: (0, import_i18n350.__)("Page attributes"),
                      panelName: "page-attributes"
                    }
                  ) })
                ]
              }
            ),
            isLargeViewport && /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
              PreferencesModalSection,
              {
                title: (0, import_i18n350.__)("Publishing"),
                children: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                  EnablePublishSidebarOption,
                  {
                    help: (0, import_i18n350.__)(
                      "Review settings, such as visibility and tags."
                    ),
                    label: (0, import_i18n350.__)(
                      "Enable pre-publish checks"
                    )
                  }
                )
              }
            ),
            extraSections?.general
          ] })
        },
        {
          name: "appearance",
          tabLabel: (0, import_i18n350.__)("Appearance"),
          content: /* @__PURE__ */ (0, import_jsx_runtime565.jsxs)(
            PreferencesModalSection,
            {
              title: (0, import_i18n350.__)("Appearance"),
              description: (0, import_i18n350.__)(
                "Customize the editor interface to suit your needs."
              ),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                  PreferenceToggleControl,
                  {
                    scope: "core",
                    featureName: "fixedToolbar",
                    onToggle: () => setPreference(
                      "core",
                      "distractionFree",
                      false
                    ),
                    help: (0, import_i18n350.__)(
                      "Access all block and document tools in a single place."
                    ),
                    label: (0, import_i18n350.__)("Top toolbar")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                  PreferenceToggleControl,
                  {
                    scope: "core",
                    featureName: "distractionFree",
                    onToggle: () => {
                      setPreference(
                        "core",
                        "fixedToolbar",
                        true
                      );
                      setIsInserterOpened2(false);
                      setIsListViewOpened2(false);
                    },
                    help: (0, import_i18n350.__)(
                      "Reduce visual distractions by hiding the toolbar and other elements to focus on writing."
                    ),
                    label: (0, import_i18n350.__)("Distraction free")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                  PreferenceToggleControl,
                  {
                    scope: "core",
                    featureName: "focusMode",
                    help: (0, import_i18n350.__)(
                      "Highlights the current block and fades other content."
                    ),
                    label: (0, import_i18n350.__)("Spotlight mode")
                  }
                ),
                extraSections?.appearance
              ]
            }
          )
        },
        {
          name: "accessibility",
          tabLabel: (0, import_i18n350.__)("Accessibility"),
          content: /* @__PURE__ */ (0, import_jsx_runtime565.jsxs)(import_jsx_runtime565.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
              PreferencesModalSection,
              {
                title: (0, import_i18n350.__)("Navigation"),
                description: (0, import_i18n350.__)(
                  "Optimize the editing experience for enhanced control."
                ),
                children: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                  PreferenceToggleControl,
                  {
                    scope: "core",
                    featureName: "keepCaretInsideBlock",
                    help: (0, import_i18n350.__)(
                      "Keeps the text cursor within blocks while navigating with arrow keys, preventing it from moving to other blocks and enhancing accessibility for keyboard users."
                    ),
                    label: (0, import_i18n350.__)(
                      "Contain text cursor inside block"
                    )
                  }
                )
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
              PreferencesModalSection,
              {
                title: (0, import_i18n350.__)("Interface"),
                children: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                  PreferenceToggleControl,
                  {
                    scope: "core",
                    featureName: "showIconLabels",
                    label: (0, import_i18n350.__)("Show button text labels"),
                    help: (0, import_i18n350.__)(
                      "Show text instead of icons on buttons across the interface."
                    )
                  }
                )
              }
            )
          ] })
        },
        {
          name: "blocks",
          tabLabel: (0, import_i18n350.__)("Blocks"),
          content: /* @__PURE__ */ (0, import_jsx_runtime565.jsxs)(import_jsx_runtime565.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(PreferencesModalSection, { title: (0, import_i18n350.__)("Inserter"), children: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
              PreferenceToggleControl,
              {
                scope: "core",
                featureName: "mostUsedBlocks",
                help: (0, import_i18n350.__)(
                  "Adds a category with the most frequently used blocks in the inserter."
                ),
                label: (0, import_i18n350.__)("Show most used blocks")
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
              PreferencesModalSection,
              {
                title: (0, import_i18n350.__)("Manage block visibility"),
                description: (0, import_i18n350.__)(
                  "Disable blocks that you don't want to appear in the inserter. They can always be toggled back on later."
                ),
                children: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(BlockVisibility, {})
              }
            )
          ] })
        },
        window.__clientSideMediaProcessing && {
          name: "media",
          tabLabel: (0, import_i18n350.__)("Media"),
          content: /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(import_jsx_runtime565.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime565.jsxs)(
            PreferencesModalSection,
            {
              title: (0, import_i18n350.__)("General"),
              description: (0, import_i18n350.__)(
                "Customize options related to the media upload flow."
              ),
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                  PreferenceToggleControl,
                  {
                    scope: "core/media",
                    featureName: "optimizeOnUpload",
                    help: (0, import_i18n350.__)(
                      "Compress media items before uploading to the server."
                    ),
                    label: (0, import_i18n350.__)("Pre-upload compression")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(
                  PreferenceToggleControl,
                  {
                    scope: "core/media",
                    featureName: "requireApproval",
                    help: (0, import_i18n350.__)(
                      "Require approval step when optimizing existing media."
                    ),
                    label: (0, import_i18n350.__)("Approval step")
                  }
                )
              ]
            }
          ) })
        }
      ].filter(Boolean),
      [
        showBlockBreadcrumbsOption,
        showCollaborationOptions,
        extraSections,
        setIsInserterOpened2,
        setIsListViewOpened2,
        setPreference,
        isLargeViewport
      ]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime565.jsx)(PreferencesModalTabs, { sections });
  }

  // packages/editor/build-module/bindings/api.mjs
  var import_blocks40 = __toESM(require_blocks(), 1);

  // packages/editor/build-module/bindings/pattern-overrides.mjs
  var import_block_editor109 = __toESM(require_block_editor(), 1);
  var CONTENT = "content";
  var pattern_overrides_default = {
    name: "core/pattern-overrides",
    getValues({ select: select9, clientId, context, bindings }) {
      const patternOverridesContent = context["pattern/overrides"];
      const { getBlockAttributes: getBlockAttributes2 } = select9(import_block_editor109.store);
      const currentBlockAttributes = getBlockAttributes2(clientId);
      const overridesValues = {};
      for (const attributeName of Object.keys(bindings)) {
        const overridableValue = patternOverridesContent?.[currentBlockAttributes?.metadata?.name]?.[attributeName];
        if (overridableValue === void 0) {
          overridesValues[attributeName] = currentBlockAttributes?.[attributeName];
          continue;
        } else {
          overridesValues[attributeName] = overridableValue === "" ? void 0 : overridableValue;
        }
      }
      return overridesValues;
    },
    setValues({ select: select9, dispatch: dispatch8, clientId, bindings }) {
      const { getBlockAttributes: getBlockAttributes2, getBlockParentsByBlockName, getBlocks: getBlocks2 } = select9(import_block_editor109.store);
      const currentBlockAttributes = getBlockAttributes2(clientId);
      const blockName = currentBlockAttributes?.metadata?.name;
      if (!blockName) {
        return;
      }
      const [patternClientId] = getBlockParentsByBlockName(
        clientId,
        "core/block",
        true
      );
      const attributes = Object.entries(bindings).reduce(
        (attrs, [key, { newValue }]) => {
          attrs[key] = newValue;
          return attrs;
        },
        {}
      );
      if (!patternClientId) {
        const syncBlocksWithSameName = (blocks) => {
          for (const block of blocks) {
            if (block.attributes?.metadata?.name === blockName) {
              dispatch8(import_block_editor109.store).updateBlockAttributes(
                block.clientId,
                attributes
              );
            }
            syncBlocksWithSameName(block.innerBlocks);
          }
        };
        syncBlocksWithSameName(getBlocks2());
        return;
      }
      const currentBindingValue = getBlockAttributes2(patternClientId)?.[CONTENT];
      dispatch8(import_block_editor109.store).updateBlockAttributes(patternClientId, {
        [CONTENT]: {
          ...currentBindingValue,
          [blockName]: {
            ...currentBindingValue?.[blockName],
            ...Object.entries(attributes).reduce(
              (acc, [key, value]) => {
                acc[key] = value === void 0 ? "" : value;
                return acc;
              },
              {}
            )
          }
        }
      });
    },
    canUserEditValue: () => true
  };

  // packages/editor/build-module/bindings/post-data.mjs
  var import_i18n351 = __toESM(require_i18n(), 1);
  var import_core_data143 = __toESM(require_core_data(), 1);
  var import_block_editor110 = __toESM(require_block_editor(), 1);
  var NAVIGATION_BLOCK_TYPES = [
    "core/navigation-link",
    "core/navigation-submenu"
  ];
  var postDataFields = [
    {
      label: (0, import_i18n351.__)("Post Date"),
      args: { field: "date" },
      type: "string"
    },
    {
      label: (0, import_i18n351.__)("Post Modified Date"),
      args: { field: "modified" },
      type: "string"
    },
    {
      label: (0, import_i18n351.__)("Post Link"),
      args: { field: "link" },
      type: "string"
    }
  ];
  var post_data_default = {
    name: "core/post-data",
    getValues({ select: select9, context, bindings, clientId }) {
      const { getBlockAttributes: getBlockAttributes2, getBlockName: getBlockName2 } = select9(import_block_editor110.store);
      const blockName = getBlockName2(clientId);
      const isNavigationBlock = NAVIGATION_BLOCK_TYPES.includes(blockName);
      let postId2, postType2;
      if (isNavigationBlock) {
        const blockAttributes = getBlockAttributes2(clientId);
        postId2 = blockAttributes?.id;
        postType2 = blockAttributes?.type;
      } else {
        postId2 = context?.postId;
        postType2 = context?.postType;
      }
      const { getEditedEntityRecord } = select9(import_core_data143.store);
      const entityDataValues = getEditedEntityRecord(
        "postType",
        postType2,
        postId2
      );
      const newValues = {};
      for (const [attributeName, binding] of Object.entries(bindings)) {
        const postDataField = postDataFields.find(
          (field) => field.args.field === binding.args.field
        );
        if (!postDataField) {
          newValues[attributeName] = binding.args.field;
        } else if (!entityDataValues) {
          newValues[attributeName] = postDataField.label;
        } else {
          newValues[attributeName] = entityDataValues[binding.args.field];
        }
      }
      return newValues;
    },
    setValues({ dispatch: dispatch8, context, bindings, clientId, select: select9 }) {
      const { getBlockName: getBlockName2 } = select9(import_block_editor110.store);
      const blockName = getBlockName2(clientId);
      if (NAVIGATION_BLOCK_TYPES.includes(blockName)) {
        return false;
      }
      const newData = {};
      Object.values(bindings).forEach(({ args, newValue }) => {
        newData[args.field] = newValue;
      });
      dispatch8(import_core_data143.store).editEntityRecord(
        "postType",
        context?.postType,
        context?.postId,
        newData
      );
    },
    canUserEditValue({ select: select9, context }) {
      const { getBlockName: getBlockName2, getSelectedBlockClientId: getSelectedBlockClientId2 } = select9(import_block_editor110.store);
      const clientId = getSelectedBlockClientId2();
      const blockName = getBlockName2(clientId);
      if (NAVIGATION_BLOCK_TYPES.includes(blockName)) {
        return false;
      }
      if (context?.query || context?.queryId) {
        return false;
      }
      if (!context?.postType) {
        return false;
      }
      const canUserEdit = select9(import_core_data143.store).canUser("update", {
        kind: "postType",
        name: context?.postType,
        id: context?.postId
      });
      if (!canUserEdit) {
        return false;
      }
      return true;
    },
    getFieldsList({ context, select: select9 }) {
      const selectedBlock = select9(import_block_editor110.store).getSelectedBlock();
      if (selectedBlock?.name !== "core/post-date") {
        return [];
      }
      if (!context || !context.postId || !context.postType) {
        return [];
      }
      return postDataFields;
    }
  };

  // packages/editor/build-module/bindings/post-meta.mjs
  var import_core_data144 = __toESM(require_core_data(), 1);
  function getPostMetaFields(select9, context) {
    const { getRegisteredPostMeta } = unlock(select9(import_core_data144.store));
    const registeredFields = getRegisteredPostMeta(context?.postType);
    const metaFields = [];
    Object.entries(registeredFields).forEach(([key, props]) => {
      if (key === "footnotes" || key.charAt(0) === "_") {
        return;
      }
      metaFields.push({
        label: props.title || key,
        args: { key },
        default: props.default,
        type: props.type
      });
    });
    return metaFields;
  }
  function getValue2({ select: select9, context, args }) {
    const metaFields = getPostMetaFields(select9, context);
    const metaField = metaFields.find(
      (field) => field.args.key === args.key
    );
    if (!metaField) {
      return args.key;
    }
    if (!context?.postId) {
      return metaField.default || metaField.label || args.key;
    }
    const { getEditedEntityRecord } = select9(import_core_data144.store);
    const entityMetaValues = getEditedEntityRecord(
      "postType",
      context?.postType,
      context?.postId
    ).meta;
    return entityMetaValues?.[args.key] ?? metaField?.label ?? args.key;
  }
  var post_meta_default = {
    name: "core/post-meta",
    getValues({ select: select9, context, bindings }) {
      const newValues = {};
      for (const [attributeName, binding] of Object.entries(bindings)) {
        newValues[attributeName] = getValue2({
          select: select9,
          context,
          args: binding.args
        });
      }
      return newValues;
    },
    setValues({ dispatch: dispatch8, context, bindings }) {
      const newMeta = {};
      Object.values(bindings).forEach(({ args, newValue }) => {
        newMeta[args.key] = newValue;
      });
      dispatch8(import_core_data144.store).editEntityRecord(
        "postType",
        context?.postType,
        context?.postId,
        {
          meta: newMeta
        }
      );
    },
    canUserEditValue({ select: select9, context, args }) {
      if (context?.query || context?.queryId) {
        return false;
      }
      if (!context?.postType) {
        return false;
      }
      const metaFields = getPostMetaFields(select9, context);
      const hasMatchingMetaField = metaFields.some(
        (field) => field.args.key === args.key
      );
      if (!hasMatchingMetaField) {
        return false;
      }
      const areCustomFieldsEnabled = select9(store).getEditorSettings().enableCustomFields;
      if (areCustomFieldsEnabled) {
        return false;
      }
      const canUserEdit = select9(import_core_data144.store).canUser("update", {
        kind: "postType",
        name: context?.postType,
        id: context?.postId
      });
      if (!canUserEdit) {
        return false;
      }
      return true;
    },
    getFieldsList({ select: select9, context }) {
      const metaFields = getPostMetaFields(select9, context);
      return metaFields.map(
        ({ default: defaultProp, ...otherProps }) => ({
          ...otherProps
        })
      );
    }
  };

  // packages/editor/build-module/bindings/term-data.mjs
  var import_i18n352 = __toESM(require_i18n(), 1);
  var import_core_data145 = __toESM(require_core_data(), 1);
  var import_block_editor111 = __toESM(require_block_editor(), 1);
  var NAVIGATION_BLOCK_TYPES2 = [
    "core/navigation-link",
    "core/navigation-submenu"
  ];
  var termDataFields = [
    {
      label: (0, import_i18n352.__)("Term ID"),
      args: { field: "id" },
      type: "string"
    },
    {
      label: (0, import_i18n352.__)("Name"),
      args: { field: "name" },
      type: "string"
    },
    {
      label: (0, import_i18n352.__)("Slug"),
      args: { field: "slug" },
      type: "string"
    },
    {
      label: (0, import_i18n352.__)("Link"),
      args: { field: "link" },
      type: "string"
    },
    {
      label: (0, import_i18n352.__)("Description"),
      args: { field: "description" },
      type: "string"
    },
    {
      label: (0, import_i18n352.__)("Parent ID"),
      args: { field: "parent" },
      type: "string"
    },
    {
      label: (0, import_i18n352.__)("Count"),
      args: { field: "count" },
      type: "string"
    }
  ];
  var term_data_default = {
    name: "core/term-data",
    usesContext: ["taxonomy", "termId", "termData"],
    getValues({ select: select9, context, bindings, clientId }) {
      const { getEntityRecord } = select9(import_core_data145.store);
      const { getBlockAttributes: getBlockAttributes2, getBlockName: getBlockName2 } = select9(import_block_editor111.store);
      const blockName = getBlockName2(clientId);
      const isNavigationBlock = NAVIGATION_BLOCK_TYPES2.includes(blockName);
      let termDataValues;
      if (isNavigationBlock) {
        const blockAttributes = getBlockAttributes2(clientId);
        const typeFromAttributes = blockAttributes?.type;
        const taxonomy = typeFromAttributes === "tag" ? "post_tag" : typeFromAttributes;
        termDataValues = getEntityRecord(
          "taxonomy",
          taxonomy,
          blockAttributes?.id
        );
      } else if (context.termId && context.taxonomy) {
        termDataValues = getEntityRecord(
          "taxonomy",
          context.taxonomy,
          context.termId
        );
      }
      if (!termDataValues && context?.termData && !isNavigationBlock) {
        termDataValues = context.termData;
      }
      const newValues = {};
      for (const [attributeName, binding] of Object.entries(bindings)) {
        const termDataField = termDataFields.find(
          (field) => field.args.field === binding.args.field
        );
        if (!termDataField) {
          newValues[attributeName] = binding.args.field;
        } else if (!termDataValues || termDataValues[binding.args.field] === void 0) {
          newValues[attributeName] = termDataField.label;
        } else if (binding.args.field === "count") {
          newValues[attributeName] = "(" + termDataValues[binding.args.field] + ")";
        } else {
          newValues[attributeName] = termDataValues[binding.args.field];
        }
      }
      return newValues;
    },
    // eslint-disable-next-line no-unused-vars
    setValues({ dispatch: dispatch8, context, bindings }) {
      return false;
    },
    canUserEditValue({ select: select9, context }) {
      const { getBlockName: getBlockName2, getSelectedBlockClientId: getSelectedBlockClientId2 } = select9(import_block_editor111.store);
      const clientId = getSelectedBlockClientId2();
      const blockName = getBlockName2(clientId);
      if (NAVIGATION_BLOCK_TYPES2.includes(blockName)) {
        return false;
      }
      if (context?.termQuery) {
        return false;
      }
      if (!context?.taxonomy || !context?.termId) {
        return false;
      }
      return false;
    },
    getFieldsList({ context, select: select9 }) {
      const { getBlockAttributes: getBlockAttributes2, getBlockName: getBlockName2, getSelectedBlockClientId: getSelectedBlockClientId2 } = select9(import_block_editor111.store);
      const clientId = getSelectedBlockClientId2();
      const blockName = getBlockName2(clientId);
      if (NAVIGATION_BLOCK_TYPES2.includes(blockName)) {
        const blockAttributes = getBlockAttributes2(clientId);
        if (!blockAttributes || !blockAttributes.id || !blockAttributes.type) {
          return [];
        }
        return termDataFields;
      }
      if (!context) {
        return [];
      }
      if (context.taxonomy && context.termId || context.termData) {
        return termDataFields;
      }
      return [];
    }
  };

  // packages/editor/build-module/bindings/api.mjs
  function registerCoreBlockBindingsSources() {
    (0, import_blocks40.registerBlockBindingsSource)(pattern_overrides_default);
    (0, import_blocks40.registerBlockBindingsSource)(post_data_default);
    (0, import_blocks40.registerBlockBindingsSource)(post_meta_default);
    (0, import_blocks40.registerBlockBindingsSource)(term_data_default);
  }

  // packages/editor/build-module/components/upload-progress-snackbar/index.mjs
  var import_data274 = __toESM(require_data(), 1);
  var import_element346 = __toESM(require_element(), 1);
  var import_i18n353 = __toESM(require_i18n(), 1);
  var import_a11y13 = __toESM(require_a11y(), 1);
  var import_upload_media3 = __toESM(require_upload_media(), 1);
  var import_notices38 = __toESM(require_notices(), 1);
  var import_components289 = __toESM(require_components(), 1);
  var import_jsx_runtime566 = __toESM(require_jsx_runtime(), 1);
  var NOTICE_ID = "upload-progress";
  var COMPLETION_DISPLAY_MS = 3e3;
  var MAX_FILENAME_LENGTH = 40;
  function truncateFilename(filename) {
    if (filename.length <= MAX_FILENAME_LENGTH) {
      return filename;
    }
    const ellipsis = "\u2026";
    const visible = MAX_FILENAME_LENGTH - ellipsis.length;
    const front = Math.ceil(visible / 2);
    const back = Math.floor(visible / 2);
    return filename.slice(0, front) + ellipsis + filename.slice(filename.length - back);
  }
  var UPLOAD_SPINNER = /* @__PURE__ */ (0, import_jsx_runtime566.jsx)(
    "span",
    {
      className: "editor-upload-progress-snackbar__spinner",
      "aria-hidden": "true",
      children: /* @__PURE__ */ (0, import_jsx_runtime566.jsx)(import_components289.Spinner, {})
    }
  );
  var UPLOAD_DONE = /* @__PURE__ */ (0, import_jsx_runtime566.jsx)("span", { className: "editor-upload-progress-snackbar__check", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime566.jsx)(import_components289.Icon, { icon: check_default }) });
  function UploadProgressSnackbar() {
    const items = (0, import_data274.useSelect)(
      (select9) => select9(import_upload_media3.store).getItems(),
      []
    );
    const tracker = useTracker();
    const csmOriginals = (0, import_element346.useMemo)(
      () => items.filter((item) => !item.parentId),
      [items]
    );
    const csmRemaining = csmOriginals.length;
    const trackedRemaining = tracker ? tracker.total - tracker.completed : 0;
    const remaining = csmRemaining + trackedRemaining;
    const sessionTotal = csmRemaining + (tracker ? tracker.total : 0);
    const peakRef = (0, import_element346.useRef)(0);
    const { createNotice, removeNotice } = (0, import_data274.useDispatch)(import_notices38.store);
    const dismissedRef = (0, import_element346.useRef)(false);
    const wasUploadingRef = (0, import_element346.useRef)(false);
    const completionTimeoutRef = (0, import_element346.useRef)(null);
    (0, import_element346.useEffect)(() => {
      return () => {
        if (completionTimeoutRef.current) {
          clearTimeout(completionTimeoutRef.current);
        }
      };
    }, []);
    (0, import_element346.useEffect)(() => {
      const isUploading = remaining > 0;
      if (isUploading && !wasUploadingRef.current) {
        dismissedRef.current = false;
        (0, import_a11y13.speak)((0, import_i18n353.__)("Media upload started"), "polite");
        if (completionTimeoutRef.current) {
          clearTimeout(completionTimeoutRef.current);
          completionTimeoutRef.current = null;
          peakRef.current = 0;
        }
      } else if (!isUploading && wasUploadingRef.current) {
        (0, import_a11y13.speak)((0, import_i18n353.__)("Media upload complete"), "polite");
        if (!dismissedRef.current) {
          createNotice("info", (0, import_i18n353.__)("Upload complete"), {
            id: NOTICE_ID,
            type: "snackbar",
            isDismissible: false,
            explicitDismiss: false,
            speak: false,
            icon: UPLOAD_DONE,
            onDismiss: () => {
              dismissedRef.current = true;
            }
          });
          completionTimeoutRef.current = setTimeout(() => {
            removeNotice(NOTICE_ID);
            completionTimeoutRef.current = null;
            peakRef.current = 0;
          }, COMPLETION_DISPLAY_MS);
        } else {
          peakRef.current = 0;
        }
      }
      wasUploadingRef.current = isUploading;
      if (!isUploading || dismissedRef.current) {
        return;
      }
      if (sessionTotal > peakRef.current) {
        peakRef.current = sessionTotal;
      }
      const total = peakRef.current;
      const current = total - remaining + 1;
      const filename = truncateFilename(
        csmOriginals[0]?.sourceFile?.name || tracker?.pending[0] || (0, import_i18n353.__)("Uploading")
      );
      const content = total === 1 ? (0, import_i18n353.sprintf)(
        /* translators: %s: filename. */
        (0, import_i18n353.__)("Uploading \u2014 %s"),
        filename
      ) : (0, import_i18n353.sprintf)(
        /* translators: 1: current upload number, 2: total uploads, 3: filename. */
        (0, import_i18n353.__)("Uploading %1$d of %2$d \u2014 %3$s"),
        current,
        total,
        filename
      );
      createNotice("info", content, {
        id: NOTICE_ID,
        type: "snackbar",
        isDismissible: false,
        explicitDismiss: true,
        speak: false,
        icon: UPLOAD_SPINNER,
        onDismiss: () => {
          dismissedRef.current = true;
        }
      });
    }, [
      remaining,
      sessionTotal,
      csmOriginals,
      tracker,
      createNotice,
      removeNotice
    ]);
    return null;
  }

  // packages/editor/build-module/private-apis.mjs
  var { store: interfaceStore, ...remainingInterfaceApis } = build_module_exports;
  var privateApis21 = {};
  lock(privateApis21, {
    CreateTemplatePartModal,
    patternTitleField: pattern_title_default,
    templateTitleField: template_title_default,
    BackButton: back_button_default,
    EntitiesSavedStatesExtensible,
    Editor: editor_default,
    PluginPostExcerpt: plugin_default,
    PostCardPanel,
    PreferencesModal: EditorPreferencesModal,
    usePostActions,
    usePostFields: post_fields_default,
    ToolsMoreMenuGroup: tools_more_menu_group_default,
    ViewMoreMenuGroup: view_more_menu_group_default,
    ResizableEditor: resizable_editor_default,
    UploadProgressSnackbar,
    registerCoreBlockBindingsSources,
    getTemplateInfo,
    // Global Styles
    GlobalStylesUIWrapper,
    GlobalStylesActionMenu,
    StyleBookPreview,
    useGlobalStyles,
    useStyle: useStyle2,
    // This is a temporary private API while we're updating the site editor to use EditorProvider.
    interfaceStore,
    ...remainingInterfaceApis
  });

  // packages/editor/build-module/dataviews/api.mjs
  var import_data275 = __toESM(require_data(), 1);
  function registerEntityAction2(kind, name2, config2) {
    const { registerEntityAction: _registerEntityAction } = unlock(
      (0, import_data275.dispatch)(store)
    );
    if (false) {
      _registerEntityAction(kind, name2, config2);
    }
  }
  function unregisterEntityAction2(kind, name2, actionId) {
    const { unregisterEntityAction: _unregisterEntityAction } = unlock(
      (0, import_data275.dispatch)(store)
    );
    if (false) {
      _unregisterEntityAction(kind, name2, actionId);
    }
  }
  function registerEntityField2(kind, name2, config2) {
    const { registerEntityField: _registerEntityField } = unlock(
      (0, import_data275.dispatch)(store)
    );
    if (false) {
      _registerEntityField(kind, name2, config2);
    }
  }
  function unregisterEntityField2(kind, name2, fieldId) {
    const { unregisterEntityField: _unregisterEntityField } = unlock(
      (0, import_data275.dispatch)(store)
    );
    if (false) {
      _unregisterEntityField(kind, name2, fieldId);
    }
  }

  // packages/editor/build-module/index.mjs
  var import_block_editor112 = __toESM(require_block_editor(), 1);
  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.
   *)

react-is/cjs/react-is.development.js:
  (** @license React v16.13.1
   * react-is.development.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

object-assign/index.js:
  (*
  object-assign
  (c) Sindre Sorhus
  @license MIT
  *)

autosize/dist/autosize.js:
  (*!
  	autosize 4.0.2
  	license: MIT
  	http://www.jacklmoore.com/autosize
  *)

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.
   *)
*/
(window.wp ||= {}).editor = wp.editor;
})();
